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/DeclLookups.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/FileSystemStatCache.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/SourceManagerInternals.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/TargetOptions.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/MacroInfo.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/PreprocessorOptions.h"
41 #include "clang/Sema/IdentifierResolver.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Serialization/ASTReader.h"
44 #include "llvm/ADT/APFloat.h"
45 #include "llvm/ADT/APInt.h"
46 #include "llvm/ADT/Hashing.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Bitcode/BitstreamWriter.h"
49 #include "llvm/Support/EndianStream.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/OnDiskHashTable.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Process.h"
59 using namespace clang;
60 using namespace clang::serialization;
62 template <typename T, typename Allocator>
63 static StringRef bytes(const std::vector<T, Allocator> &v) {
64 if (v.empty()) return StringRef();
65 return StringRef(reinterpret_cast<const char*>(&v[0]),
66 sizeof(T) * v.size());
70 static StringRef bytes(const SmallVectorImpl<T> &v) {
71 return StringRef(reinterpret_cast<const char*>(v.data()),
72 sizeof(T) * v.size());
75 //===----------------------------------------------------------------------===//
77 //===----------------------------------------------------------------------===//
82 ASTWriter::RecordDataImpl &Record;
85 /// \brief Type code that corresponds to the record generated.
87 /// \brief Abbreviation to use for the record, if any.
90 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
91 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
93 void VisitArrayType(const ArrayType *T);
94 void VisitFunctionType(const FunctionType *T);
95 void VisitTagType(const TagType *T);
97 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
98 #define ABSTRACT_TYPE(Class, Base)
99 #include "clang/AST/TypeNodes.def"
103 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
104 llvm_unreachable("Built-in types are never serialized");
107 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
108 Writer.AddTypeRef(T->getElementType(), Record);
112 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
113 Writer.AddTypeRef(T->getPointeeType(), Record);
117 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
118 Writer.AddTypeRef(T->getOriginalType(), Record);
122 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
123 Writer.AddTypeRef(T->getOriginalType(), Record);
124 Writer.AddTypeRef(T->getAdjustedType(), Record);
125 Code = TYPE_ADJUSTED;
128 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
129 Writer.AddTypeRef(T->getPointeeType(), Record);
130 Code = TYPE_BLOCK_POINTER;
133 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
134 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
135 Record.push_back(T->isSpelledAsLValue());
136 Code = TYPE_LVALUE_REFERENCE;
139 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
140 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
141 Code = TYPE_RVALUE_REFERENCE;
144 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
145 Writer.AddTypeRef(T->getPointeeType(), Record);
146 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
147 Code = TYPE_MEMBER_POINTER;
150 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
151 Writer.AddTypeRef(T->getElementType(), Record);
152 Record.push_back(T->getSizeModifier()); // FIXME: stable values
153 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
156 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
158 Writer.AddAPInt(T->getSize(), Record);
159 Code = TYPE_CONSTANT_ARRAY;
162 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
164 Code = TYPE_INCOMPLETE_ARRAY;
167 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
169 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
170 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
171 Writer.AddStmt(T->getSizeExpr());
172 Code = TYPE_VARIABLE_ARRAY;
175 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
176 Writer.AddTypeRef(T->getElementType(), Record);
177 Record.push_back(T->getNumElements());
178 Record.push_back(T->getVectorKind());
182 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
184 Code = TYPE_EXT_VECTOR;
187 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
188 Writer.AddTypeRef(T->getReturnType(), Record);
189 FunctionType::ExtInfo C = T->getExtInfo();
190 Record.push_back(C.getNoReturn());
191 Record.push_back(C.getHasRegParm());
192 Record.push_back(C.getRegParm());
193 // FIXME: need to stabilize encoding of calling convention...
194 Record.push_back(C.getCC());
195 Record.push_back(C.getProducesResult());
197 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
201 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
202 VisitFunctionType(T);
203 Code = TYPE_FUNCTION_NO_PROTO;
206 static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
207 ASTWriter::RecordDataImpl &Record) {
208 Record.push_back(T->getExceptionSpecType());
209 if (T->getExceptionSpecType() == EST_Dynamic) {
210 Record.push_back(T->getNumExceptions());
211 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
212 Writer.AddTypeRef(T->getExceptionType(I), Record);
213 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
214 Writer.AddStmt(T->getNoexceptExpr());
215 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
216 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
217 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
218 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
219 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
223 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
224 VisitFunctionType(T);
226 Record.push_back(T->isVariadic());
227 Record.push_back(T->hasTrailingReturn());
228 Record.push_back(T->getTypeQuals());
229 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
230 addExceptionSpec(Writer, T, Record);
232 Record.push_back(T->getNumParams());
233 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
234 Writer.AddTypeRef(T->getParamType(I), Record);
236 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
237 T->getRefQualifier() || T->getExceptionSpecType() != EST_None)
240 Code = TYPE_FUNCTION_PROTO;
243 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
244 Writer.AddDeclRef(T->getDecl(), Record);
245 Code = TYPE_UNRESOLVED_USING;
248 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
249 Writer.AddDeclRef(T->getDecl(), Record);
250 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
251 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
255 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
256 Writer.AddStmt(T->getUnderlyingExpr());
257 Code = TYPE_TYPEOF_EXPR;
260 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
261 Writer.AddTypeRef(T->getUnderlyingType(), Record);
265 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
266 Writer.AddTypeRef(T->getUnderlyingType(), Record);
267 Writer.AddStmt(T->getUnderlyingExpr());
268 Code = TYPE_DECLTYPE;
271 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
272 Writer.AddTypeRef(T->getBaseType(), Record);
273 Writer.AddTypeRef(T->getUnderlyingType(), Record);
274 Record.push_back(T->getUTTKind());
275 Code = TYPE_UNARY_TRANSFORM;
278 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
279 Writer.AddTypeRef(T->getDeducedType(), Record);
280 Record.push_back(T->isDecltypeAuto());
281 if (T->getDeducedType().isNull())
282 Record.push_back(T->isDependentType());
286 void ASTTypeWriter::VisitTagType(const TagType *T) {
287 Record.push_back(T->isDependentType());
288 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
289 assert(!T->isBeingDefined() &&
290 "Cannot serialize in the middle of a type definition");
293 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
298 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
303 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
304 Writer.AddTypeRef(T->getModifiedType(), Record);
305 Writer.AddTypeRef(T->getEquivalentType(), Record);
306 Record.push_back(T->getAttrKind());
307 Code = TYPE_ATTRIBUTED;
311 ASTTypeWriter::VisitSubstTemplateTypeParmType(
312 const SubstTemplateTypeParmType *T) {
313 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
314 Writer.AddTypeRef(T->getReplacementType(), Record);
315 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
319 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
320 const SubstTemplateTypeParmPackType *T) {
321 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
322 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
323 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
327 ASTTypeWriter::VisitTemplateSpecializationType(
328 const TemplateSpecializationType *T) {
329 Record.push_back(T->isDependentType());
330 Writer.AddTemplateName(T->getTemplateName(), Record);
331 Record.push_back(T->getNumArgs());
332 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
333 ArgI != ArgE; ++ArgI)
334 Writer.AddTemplateArgument(*ArgI, Record);
335 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
336 T->isCanonicalUnqualified() ? QualType()
337 : T->getCanonicalTypeInternal(),
339 Code = TYPE_TEMPLATE_SPECIALIZATION;
343 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
345 Writer.AddStmt(T->getSizeExpr());
346 Writer.AddSourceRange(T->getBracketsRange(), Record);
347 Code = TYPE_DEPENDENT_SIZED_ARRAY;
351 ASTTypeWriter::VisitDependentSizedExtVectorType(
352 const DependentSizedExtVectorType *T) {
353 // FIXME: Serialize this type (C++ only)
354 llvm_unreachable("Cannot serialize dependent sized extended vector types");
358 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
359 Record.push_back(T->getDepth());
360 Record.push_back(T->getIndex());
361 Record.push_back(T->isParameterPack());
362 Writer.AddDeclRef(T->getDecl(), Record);
363 Code = TYPE_TEMPLATE_TYPE_PARM;
367 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
368 Record.push_back(T->getKeyword());
369 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
370 Writer.AddIdentifierRef(T->getIdentifier(), Record);
371 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
372 : T->getCanonicalTypeInternal(),
374 Code = TYPE_DEPENDENT_NAME;
378 ASTTypeWriter::VisitDependentTemplateSpecializationType(
379 const DependentTemplateSpecializationType *T) {
380 Record.push_back(T->getKeyword());
381 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
382 Writer.AddIdentifierRef(T->getIdentifier(), Record);
383 Record.push_back(T->getNumArgs());
384 for (DependentTemplateSpecializationType::iterator
385 I = T->begin(), E = T->end(); I != E; ++I)
386 Writer.AddTemplateArgument(*I, Record);
387 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
390 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
391 Writer.AddTypeRef(T->getPattern(), Record);
392 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
393 Record.push_back(*NumExpansions + 1);
396 Code = TYPE_PACK_EXPANSION;
399 void ASTTypeWriter::VisitParenType(const ParenType *T) {
400 Writer.AddTypeRef(T->getInnerType(), Record);
404 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
405 Record.push_back(T->getKeyword());
406 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
407 Writer.AddTypeRef(T->getNamedType(), Record);
408 Code = TYPE_ELABORATED;
411 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
412 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
413 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
414 Code = TYPE_INJECTED_CLASS_NAME;
417 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
418 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
419 Code = TYPE_OBJC_INTERFACE;
422 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
423 Writer.AddTypeRef(T->getBaseType(), Record);
424 Record.push_back(T->getNumProtocols());
425 for (const auto *I : T->quals())
426 Writer.AddDeclRef(I, Record);
427 Code = TYPE_OBJC_OBJECT;
431 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
432 Writer.AddTypeRef(T->getPointeeType(), Record);
433 Code = TYPE_OBJC_OBJECT_POINTER;
437 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
438 Writer.AddTypeRef(T->getValueType(), Record);
444 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
446 ASTWriter::RecordDataImpl &Record;
449 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
450 : Writer(Writer), Record(Record) { }
452 #define ABSTRACT_TYPELOC(CLASS, PARENT)
453 #define TYPELOC(CLASS, PARENT) \
454 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
455 #include "clang/AST/TypeLocNodes.def"
457 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
458 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
463 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
466 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
467 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
468 if (TL.needsExtraLocalData()) {
469 Record.push_back(TL.getWrittenTypeSpec());
470 Record.push_back(TL.getWrittenSignSpec());
471 Record.push_back(TL.getWrittenWidthSpec());
472 Record.push_back(TL.hasModeAttr());
475 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
476 Writer.AddSourceLocation(TL.getNameLoc(), Record);
478 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
479 Writer.AddSourceLocation(TL.getStarLoc(), Record);
481 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
484 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
487 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
488 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
490 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
491 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
493 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
494 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
496 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
497 Writer.AddSourceLocation(TL.getStarLoc(), Record);
498 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
500 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
501 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
502 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
503 Record.push_back(TL.getSizeExpr() ? 1 : 0);
504 if (TL.getSizeExpr())
505 Writer.AddStmt(TL.getSizeExpr());
507 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
508 VisitArrayTypeLoc(TL);
510 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
511 VisitArrayTypeLoc(TL);
513 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
514 VisitArrayTypeLoc(TL);
516 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
517 DependentSizedArrayTypeLoc TL) {
518 VisitArrayTypeLoc(TL);
520 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
521 DependentSizedExtVectorTypeLoc TL) {
522 Writer.AddSourceLocation(TL.getNameLoc(), Record);
524 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
525 Writer.AddSourceLocation(TL.getNameLoc(), Record);
527 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
528 Writer.AddSourceLocation(TL.getNameLoc(), Record);
530 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
531 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
532 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
533 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
534 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
535 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
536 Writer.AddDeclRef(TL.getParam(i), Record);
538 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
539 VisitFunctionTypeLoc(TL);
541 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
542 VisitFunctionTypeLoc(TL);
544 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
545 Writer.AddSourceLocation(TL.getNameLoc(), Record);
547 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
548 Writer.AddSourceLocation(TL.getNameLoc(), Record);
550 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
551 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
552 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
553 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
555 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
556 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
557 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
558 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
559 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
561 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
562 Writer.AddSourceLocation(TL.getNameLoc(), Record);
564 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
565 Writer.AddSourceLocation(TL.getKWLoc(), Record);
566 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
567 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
568 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
570 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
571 Writer.AddSourceLocation(TL.getNameLoc(), Record);
573 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
574 Writer.AddSourceLocation(TL.getNameLoc(), Record);
576 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
577 Writer.AddSourceLocation(TL.getNameLoc(), Record);
579 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
580 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
581 if (TL.hasAttrOperand()) {
582 SourceRange range = TL.getAttrOperandParensRange();
583 Writer.AddSourceLocation(range.getBegin(), Record);
584 Writer.AddSourceLocation(range.getEnd(), Record);
586 if (TL.hasAttrExprOperand()) {
587 Expr *operand = TL.getAttrExprOperand();
588 Record.push_back(operand ? 1 : 0);
589 if (operand) Writer.AddStmt(operand);
590 } else if (TL.hasAttrEnumOperand()) {
591 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
594 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
595 Writer.AddSourceLocation(TL.getNameLoc(), Record);
597 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
598 SubstTemplateTypeParmTypeLoc TL) {
599 Writer.AddSourceLocation(TL.getNameLoc(), Record);
601 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
602 SubstTemplateTypeParmPackTypeLoc TL) {
603 Writer.AddSourceLocation(TL.getNameLoc(), Record);
605 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
606 TemplateSpecializationTypeLoc TL) {
607 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
608 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
609 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
610 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
611 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
612 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
613 TL.getArgLoc(i).getLocInfo(), Record);
615 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
616 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
617 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
619 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
620 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
621 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
623 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
624 Writer.AddSourceLocation(TL.getNameLoc(), Record);
626 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
627 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
628 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
629 Writer.AddSourceLocation(TL.getNameLoc(), Record);
631 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
632 DependentTemplateSpecializationTypeLoc TL) {
633 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
634 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
635 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
636 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
637 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
638 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
639 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
640 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
641 TL.getArgLoc(I).getLocInfo(), Record);
643 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
644 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
646 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
647 Writer.AddSourceLocation(TL.getNameLoc(), Record);
649 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
650 Record.push_back(TL.hasBaseTypeAsWritten());
651 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
652 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
653 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
654 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
656 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
657 Writer.AddSourceLocation(TL.getStarLoc(), Record);
659 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
660 Writer.AddSourceLocation(TL.getKWLoc(), Record);
661 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
662 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
665 void ASTWriter::WriteTypeAbbrevs() {
666 using namespace llvm;
670 // Abbreviation for TYPE_EXT_QUAL
671 Abv = new BitCodeAbbrev();
672 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
673 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
674 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
675 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
677 // Abbreviation for TYPE_FUNCTION_PROTO
678 Abv = new BitCodeAbbrev();
679 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
681 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
682 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
683 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
684 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
685 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
686 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
688 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
689 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
690 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
691 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
692 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
693 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
694 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
695 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
696 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
699 //===----------------------------------------------------------------------===//
700 // ASTWriter Implementation
701 //===----------------------------------------------------------------------===//
703 static void EmitBlockID(unsigned ID, const char *Name,
704 llvm::BitstreamWriter &Stream,
705 ASTWriter::RecordDataImpl &Record) {
707 Record.push_back(ID);
708 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
710 // Emit the block name if present.
711 if (!Name || Name[0] == 0)
715 Record.push_back(*Name++);
716 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
719 static void EmitRecordID(unsigned ID, const char *Name,
720 llvm::BitstreamWriter &Stream,
721 ASTWriter::RecordDataImpl &Record) {
723 Record.push_back(ID);
725 Record.push_back(*Name++);
726 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
729 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
730 ASTWriter::RecordDataImpl &Record) {
731 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
733 RECORD(STMT_NULL_PTR);
734 RECORD(STMT_REF_PTR);
736 RECORD(STMT_COMPOUND);
738 RECORD(STMT_DEFAULT);
740 RECORD(STMT_ATTRIBUTED);
747 RECORD(STMT_INDIRECT_GOTO);
748 RECORD(STMT_CONTINUE);
754 RECORD(EXPR_PREDEFINED);
755 RECORD(EXPR_DECL_REF);
756 RECORD(EXPR_INTEGER_LITERAL);
757 RECORD(EXPR_FLOATING_LITERAL);
758 RECORD(EXPR_IMAGINARY_LITERAL);
759 RECORD(EXPR_STRING_LITERAL);
760 RECORD(EXPR_CHARACTER_LITERAL);
762 RECORD(EXPR_PAREN_LIST);
763 RECORD(EXPR_UNARY_OPERATOR);
764 RECORD(EXPR_SIZEOF_ALIGN_OF);
765 RECORD(EXPR_ARRAY_SUBSCRIPT);
768 RECORD(EXPR_BINARY_OPERATOR);
769 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
770 RECORD(EXPR_CONDITIONAL_OPERATOR);
771 RECORD(EXPR_IMPLICIT_CAST);
772 RECORD(EXPR_CSTYLE_CAST);
773 RECORD(EXPR_COMPOUND_LITERAL);
774 RECORD(EXPR_EXT_VECTOR_ELEMENT);
775 RECORD(EXPR_INIT_LIST);
776 RECORD(EXPR_DESIGNATED_INIT);
777 RECORD(EXPR_IMPLICIT_VALUE_INIT);
779 RECORD(EXPR_ADDR_LABEL);
782 RECORD(EXPR_GNU_NULL);
783 RECORD(EXPR_SHUFFLE_VECTOR);
785 RECORD(EXPR_GENERIC_SELECTION);
786 RECORD(EXPR_OBJC_STRING_LITERAL);
787 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
788 RECORD(EXPR_OBJC_ARRAY_LITERAL);
789 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
790 RECORD(EXPR_OBJC_ENCODE);
791 RECORD(EXPR_OBJC_SELECTOR_EXPR);
792 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
793 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
794 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
795 RECORD(EXPR_OBJC_KVC_REF_EXPR);
796 RECORD(EXPR_OBJC_MESSAGE_EXPR);
797 RECORD(STMT_OBJC_FOR_COLLECTION);
798 RECORD(STMT_OBJC_CATCH);
799 RECORD(STMT_OBJC_FINALLY);
800 RECORD(STMT_OBJC_AT_TRY);
801 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
802 RECORD(STMT_OBJC_AT_THROW);
803 RECORD(EXPR_OBJC_BOOL_LITERAL);
804 RECORD(STMT_CXX_CATCH);
805 RECORD(STMT_CXX_TRY);
806 RECORD(STMT_CXX_FOR_RANGE);
807 RECORD(EXPR_CXX_OPERATOR_CALL);
808 RECORD(EXPR_CXX_MEMBER_CALL);
809 RECORD(EXPR_CXX_CONSTRUCT);
810 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
811 RECORD(EXPR_CXX_STATIC_CAST);
812 RECORD(EXPR_CXX_DYNAMIC_CAST);
813 RECORD(EXPR_CXX_REINTERPRET_CAST);
814 RECORD(EXPR_CXX_CONST_CAST);
815 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
816 RECORD(EXPR_USER_DEFINED_LITERAL);
817 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
818 RECORD(EXPR_CXX_BOOL_LITERAL);
819 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
820 RECORD(EXPR_CXX_TYPEID_EXPR);
821 RECORD(EXPR_CXX_TYPEID_TYPE);
822 RECORD(EXPR_CXX_THIS);
823 RECORD(EXPR_CXX_THROW);
824 RECORD(EXPR_CXX_DEFAULT_ARG);
825 RECORD(EXPR_CXX_DEFAULT_INIT);
826 RECORD(EXPR_CXX_BIND_TEMPORARY);
827 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
828 RECORD(EXPR_CXX_NEW);
829 RECORD(EXPR_CXX_DELETE);
830 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
831 RECORD(EXPR_EXPR_WITH_CLEANUPS);
832 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
833 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
834 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
835 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
836 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
837 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
838 RECORD(EXPR_CXX_NOEXCEPT);
839 RECORD(EXPR_OPAQUE_VALUE);
840 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
841 RECORD(EXPR_TYPE_TRAIT);
842 RECORD(EXPR_ARRAY_TYPE_TRAIT);
843 RECORD(EXPR_PACK_EXPANSION);
844 RECORD(EXPR_SIZEOF_PACK);
845 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
846 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
847 RECORD(EXPR_FUNCTION_PARM_PACK);
848 RECORD(EXPR_MATERIALIZE_TEMPORARY);
849 RECORD(EXPR_CUDA_KERNEL_CALL);
850 RECORD(EXPR_CXX_UUIDOF_EXPR);
851 RECORD(EXPR_CXX_UUIDOF_TYPE);
856 void ASTWriter::WriteBlockInfoBlock() {
858 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
860 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
861 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
864 BLOCK(CONTROL_BLOCK);
868 RECORD(MODULE_MAP_FILE);
870 RECORD(KNOWN_MODULE_FILES);
871 RECORD(LANGUAGE_OPTIONS);
872 RECORD(TARGET_OPTIONS);
873 RECORD(ORIGINAL_FILE);
874 RECORD(ORIGINAL_PCH_DIR);
875 RECORD(ORIGINAL_FILE_ID);
876 RECORD(INPUT_FILE_OFFSETS);
877 RECORD(DIAGNOSTIC_OPTIONS);
878 RECORD(FILE_SYSTEM_OPTIONS);
879 RECORD(HEADER_SEARCH_OPTIONS);
880 RECORD(PREPROCESSOR_OPTIONS);
882 BLOCK(INPUT_FILES_BLOCK);
885 // AST Top-Level Block.
889 RECORD(IDENTIFIER_OFFSET);
890 RECORD(IDENTIFIER_TABLE);
891 RECORD(EAGERLY_DESERIALIZED_DECLS);
892 RECORD(SPECIAL_TYPES);
894 RECORD(TENTATIVE_DEFINITIONS);
895 RECORD(UNUSED_FILESCOPED_DECLS);
896 RECORD(SELECTOR_OFFSETS);
898 RECORD(PP_COUNTER_VALUE);
899 RECORD(SOURCE_LOCATION_OFFSETS);
900 RECORD(SOURCE_LOCATION_PRELOADS);
901 RECORD(EXT_VECTOR_DECLS);
902 RECORD(PPD_ENTITIES_OFFSETS);
903 RECORD(REFERENCED_SELECTOR_POOL);
904 RECORD(TU_UPDATE_LEXICAL);
905 RECORD(LOCAL_REDECLARATIONS_MAP);
906 RECORD(SEMA_DECL_REFS);
907 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
908 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
909 RECORD(DECL_REPLACEMENTS);
910 RECORD(UPDATE_VISIBLE);
911 RECORD(DECL_UPDATE_OFFSETS);
912 RECORD(DECL_UPDATES);
913 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
914 RECORD(DIAG_PRAGMA_MAPPINGS);
915 RECORD(CUDA_SPECIAL_DECL_REFS);
916 RECORD(HEADER_SEARCH_TABLE);
917 RECORD(FP_PRAGMA_OPTIONS);
918 RECORD(OPENCL_EXTENSIONS);
919 RECORD(DELEGATING_CTORS);
920 RECORD(KNOWN_NAMESPACES);
921 RECORD(UNDEFINED_BUT_USED);
922 RECORD(MODULE_OFFSET_MAP);
923 RECORD(SOURCE_MANAGER_LINE_TABLE);
924 RECORD(OBJC_CATEGORIES_MAP);
925 RECORD(FILE_SORTED_DECLS);
926 RECORD(IMPORTED_MODULES);
927 RECORD(LOCAL_REDECLARATIONS);
928 RECORD(OBJC_CATEGORIES);
929 RECORD(MACRO_OFFSET);
930 RECORD(LATE_PARSED_TEMPLATE);
931 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
933 // SourceManager Block.
934 BLOCK(SOURCE_MANAGER_BLOCK);
935 RECORD(SM_SLOC_FILE_ENTRY);
936 RECORD(SM_SLOC_BUFFER_ENTRY);
937 RECORD(SM_SLOC_BUFFER_BLOB);
938 RECORD(SM_SLOC_EXPANSION_ENTRY);
940 // Preprocessor Block.
941 BLOCK(PREPROCESSOR_BLOCK);
942 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
943 RECORD(PP_MACRO_FUNCTION_LIKE);
944 RECORD(PP_MACRO_OBJECT_LIKE);
945 RECORD(PP_MODULE_MACRO);
948 // Decls and Types block.
949 BLOCK(DECLTYPES_BLOCK);
950 RECORD(TYPE_EXT_QUAL);
951 RECORD(TYPE_COMPLEX);
952 RECORD(TYPE_POINTER);
953 RECORD(TYPE_BLOCK_POINTER);
954 RECORD(TYPE_LVALUE_REFERENCE);
955 RECORD(TYPE_RVALUE_REFERENCE);
956 RECORD(TYPE_MEMBER_POINTER);
957 RECORD(TYPE_CONSTANT_ARRAY);
958 RECORD(TYPE_INCOMPLETE_ARRAY);
959 RECORD(TYPE_VARIABLE_ARRAY);
961 RECORD(TYPE_EXT_VECTOR);
962 RECORD(TYPE_FUNCTION_NO_PROTO);
963 RECORD(TYPE_FUNCTION_PROTO);
964 RECORD(TYPE_TYPEDEF);
965 RECORD(TYPE_TYPEOF_EXPR);
969 RECORD(TYPE_OBJC_INTERFACE);
970 RECORD(TYPE_OBJC_OBJECT_POINTER);
971 RECORD(TYPE_DECLTYPE);
972 RECORD(TYPE_ELABORATED);
973 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
974 RECORD(TYPE_UNRESOLVED_USING);
975 RECORD(TYPE_INJECTED_CLASS_NAME);
976 RECORD(TYPE_OBJC_OBJECT);
977 RECORD(TYPE_TEMPLATE_TYPE_PARM);
978 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
979 RECORD(TYPE_DEPENDENT_NAME);
980 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
981 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
983 RECORD(TYPE_PACK_EXPANSION);
984 RECORD(TYPE_ATTRIBUTED);
985 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
987 RECORD(TYPE_UNARY_TRANSFORM);
989 RECORD(TYPE_DECAYED);
990 RECORD(TYPE_ADJUSTED);
991 RECORD(DECL_TYPEDEF);
992 RECORD(DECL_TYPEALIAS);
995 RECORD(DECL_ENUM_CONSTANT);
996 RECORD(DECL_FUNCTION);
997 RECORD(DECL_OBJC_METHOD);
998 RECORD(DECL_OBJC_INTERFACE);
999 RECORD(DECL_OBJC_PROTOCOL);
1000 RECORD(DECL_OBJC_IVAR);
1001 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1002 RECORD(DECL_OBJC_CATEGORY);
1003 RECORD(DECL_OBJC_CATEGORY_IMPL);
1004 RECORD(DECL_OBJC_IMPLEMENTATION);
1005 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1006 RECORD(DECL_OBJC_PROPERTY);
1007 RECORD(DECL_OBJC_PROPERTY_IMPL);
1009 RECORD(DECL_MS_PROPERTY);
1011 RECORD(DECL_IMPLICIT_PARAM);
1012 RECORD(DECL_PARM_VAR);
1013 RECORD(DECL_FILE_SCOPE_ASM);
1015 RECORD(DECL_CONTEXT_LEXICAL);
1016 RECORD(DECL_CONTEXT_VISIBLE);
1017 RECORD(DECL_NAMESPACE);
1018 RECORD(DECL_NAMESPACE_ALIAS);
1020 RECORD(DECL_USING_SHADOW);
1021 RECORD(DECL_USING_DIRECTIVE);
1022 RECORD(DECL_UNRESOLVED_USING_VALUE);
1023 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1024 RECORD(DECL_LINKAGE_SPEC);
1025 RECORD(DECL_CXX_RECORD);
1026 RECORD(DECL_CXX_METHOD);
1027 RECORD(DECL_CXX_CONSTRUCTOR);
1028 RECORD(DECL_CXX_DESTRUCTOR);
1029 RECORD(DECL_CXX_CONVERSION);
1030 RECORD(DECL_ACCESS_SPEC);
1031 RECORD(DECL_FRIEND);
1032 RECORD(DECL_FRIEND_TEMPLATE);
1033 RECORD(DECL_CLASS_TEMPLATE);
1034 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1035 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1036 RECORD(DECL_VAR_TEMPLATE);
1037 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1038 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1039 RECORD(DECL_FUNCTION_TEMPLATE);
1040 RECORD(DECL_TEMPLATE_TYPE_PARM);
1041 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1042 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1043 RECORD(DECL_STATIC_ASSERT);
1044 RECORD(DECL_CXX_BASE_SPECIFIERS);
1045 RECORD(DECL_INDIRECTFIELD);
1046 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1048 // Statements and Exprs can occur in the Decls and Types block.
1049 AddStmtsExprs(Stream, Record);
1051 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1052 RECORD(PPD_MACRO_EXPANSION);
1053 RECORD(PPD_MACRO_DEFINITION);
1054 RECORD(PPD_INCLUSION_DIRECTIVE);
1061 /// \brief Prepares a path for being written to an AST file by converting it
1062 /// to an absolute path and removing nested './'s.
1064 /// \return \c true if the path was changed.
1065 static bool cleanPathForOutput(FileManager &FileMgr,
1066 SmallVectorImpl<char> &Path) {
1067 bool Changed = false;
1069 if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
1070 llvm::sys::fs::make_absolute(Path);
1074 return Changed | FileMgr.removeDotPaths(Path);
1077 /// \brief Adjusts the given filename to only write out the portion of the
1078 /// filename that is not part of the system root directory.
1080 /// \param Filename the file name to adjust.
1082 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1083 /// the returned filename will be adjusted by this root directory.
1085 /// \returns either the original filename (if it needs no adjustment) or the
1086 /// adjusted filename (which points into the @p Filename parameter).
1088 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1089 assert(Filename && "No file name to adjust?");
1091 if (BaseDir.empty())
1094 // Verify that the filename and the system root have the same prefix.
1096 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1097 if (Filename[Pos] != BaseDir[Pos])
1098 return Filename; // Prefixes don't match.
1100 // We hit the end of the filename before we hit the end of the system root.
1104 // If there's not a path separator at the end of the base directory nor
1105 // immediately after it, then this isn't within the base directory.
1106 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1107 if (!llvm::sys::path::is_separator(BaseDir.back()))
1110 // If the file name has a '/' at the current position, skip over the '/'.
1111 // We distinguish relative paths from absolute paths by the
1112 // absence of '/' at the beginning of relative paths.
1114 // FIXME: This is wrong. We distinguish them by asking if the path is
1115 // absolute, which isn't the same thing. And there might be multiple '/'s
1116 // in a row. Use a better mechanism to indicate whether we have emitted an
1117 // absolute or relative path.
1121 return Filename + Pos;
1124 static ASTFileSignature getSignature() {
1126 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1128 // Rely on GetRandomNumber to eventually return non-zero...
1132 /// \brief Write the control block.
1133 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1135 const std::string &OutputFile) {
1136 using namespace llvm;
1137 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1141 BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1142 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1143 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1144 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1145 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1146 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1147 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1148 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1149 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1150 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1151 Record.push_back(METADATA);
1152 Record.push_back(VERSION_MAJOR);
1153 Record.push_back(VERSION_MINOR);
1154 Record.push_back(CLANG_VERSION_MAJOR);
1155 Record.push_back(CLANG_VERSION_MINOR);
1156 assert((!WritingModule || isysroot.empty()) &&
1157 "writing module as a relocatable PCH?");
1158 Record.push_back(!isysroot.empty());
1159 Record.push_back(ASTHasCompilerErrors);
1160 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1161 getClangFullRepositoryVersion());
1163 if (WritingModule) {
1164 // For implicit modules we output a signature that we can use to ensure
1165 // duplicate module builds don't collide in the cache as their output order
1166 // is non-deterministic.
1167 // FIXME: Remove this when output is deterministic.
1168 if (Context.getLangOpts().ImplicitModules) {
1170 Record.push_back(getSignature());
1171 Stream.EmitRecord(SIGNATURE, Record);
1175 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1176 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1178 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1180 Record.push_back(MODULE_NAME);
1181 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1184 if (WritingModule && WritingModule->Directory) {
1185 // Module directory.
1186 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1187 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1188 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1189 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1191 Record.push_back(MODULE_DIRECTORY);
1193 SmallString<128> BaseDir(WritingModule->Directory->getName());
1194 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1195 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1197 // Write out all other paths relative to the base directory if possible.
1198 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1199 } else if (!isysroot.empty()) {
1200 // Write out paths relative to the sysroot if possible.
1201 BaseDirectory = isysroot;
1205 if (WritingModule) {
1208 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1210 // Primary module map file.
1211 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1213 // Additional module map files.
1214 if (auto *AdditionalModMaps =
1215 Map.getAdditionalModuleMapFiles(WritingModule)) {
1216 Record.push_back(AdditionalModMaps->size());
1217 for (const FileEntry *F : *AdditionalModMaps)
1218 AddPath(F->getName(), Record);
1220 Record.push_back(0);
1223 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1228 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1231 for (auto *M : Mgr) {
1232 // Skip modules that weren't directly imported.
1233 if (!M->isDirectlyImported())
1236 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1237 AddSourceLocation(M->ImportLoc, Record);
1238 Record.push_back(M->File->getSize());
1239 Record.push_back(M->File->getModificationTime());
1240 Record.push_back(M->Signature);
1241 AddPath(M->FileName, Record);
1243 Stream.EmitRecord(IMPORTS, Record);
1245 // Also emit a list of known module files that were not imported,
1246 // but are made available by this module.
1247 // FIXME: Should we also include a signature here?
1249 for (auto *E : Mgr.getAdditionalKnownModuleFiles())
1250 AddPath(E->getName(), Record);
1251 if (!Record.empty())
1252 Stream.EmitRecord(KNOWN_MODULE_FILES, Record);
1255 // Language options.
1257 const LangOptions &LangOpts = Context.getLangOpts();
1258 #define LANGOPT(Name, Bits, Default, Description) \
1259 Record.push_back(LangOpts.Name);
1260 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1261 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1262 #include "clang/Basic/LangOptions.def"
1263 #define SANITIZER(NAME, ID) \
1264 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1265 #include "clang/Basic/Sanitizers.def"
1267 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1268 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1270 Record.push_back(LangOpts.CurrentModule.size());
1271 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1274 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1275 for (CommentOptions::BlockCommandNamesTy::const_iterator
1276 I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1277 IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1279 AddString(*I, Record);
1281 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1283 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1287 const TargetInfo &Target = Context.getTargetInfo();
1288 const TargetOptions &TargetOpts = Target.getTargetOpts();
1289 AddString(TargetOpts.Triple, Record);
1290 AddString(TargetOpts.CPU, Record);
1291 AddString(TargetOpts.ABI, Record);
1292 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1293 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1294 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1296 Record.push_back(TargetOpts.Features.size());
1297 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1298 AddString(TargetOpts.Features[I], Record);
1300 Stream.EmitRecord(TARGET_OPTIONS, Record);
1302 // Diagnostic options.
1304 const DiagnosticOptions &DiagOpts
1305 = Context.getDiagnostics().getDiagnosticOptions();
1306 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1307 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1308 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1309 #include "clang/Basic/DiagnosticOptions.def"
1310 Record.push_back(DiagOpts.Warnings.size());
1311 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1312 AddString(DiagOpts.Warnings[I], Record);
1313 Record.push_back(DiagOpts.Remarks.size());
1314 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1315 AddString(DiagOpts.Remarks[I], Record);
1316 // Note: we don't serialize the log or serialization file names, because they
1317 // are generally transient files and will almost always be overridden.
1318 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1320 // File system options.
1322 const FileSystemOptions &FSOpts
1323 = Context.getSourceManager().getFileManager().getFileSystemOptions();
1324 AddString(FSOpts.WorkingDir, Record);
1325 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1327 // Header search options.
1329 const HeaderSearchOptions &HSOpts
1330 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1331 AddString(HSOpts.Sysroot, Record);
1334 Record.push_back(HSOpts.UserEntries.size());
1335 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1336 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1337 AddString(Entry.Path, Record);
1338 Record.push_back(static_cast<unsigned>(Entry.Group));
1339 Record.push_back(Entry.IsFramework);
1340 Record.push_back(Entry.IgnoreSysRoot);
1343 // System header prefixes.
1344 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1345 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1346 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1347 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1350 AddString(HSOpts.ResourceDir, Record);
1351 AddString(HSOpts.ModuleCachePath, Record);
1352 AddString(HSOpts.ModuleUserBuildPath, Record);
1353 Record.push_back(HSOpts.DisableModuleHash);
1354 Record.push_back(HSOpts.UseBuiltinIncludes);
1355 Record.push_back(HSOpts.UseStandardSystemIncludes);
1356 Record.push_back(HSOpts.UseStandardCXXIncludes);
1357 Record.push_back(HSOpts.UseLibcxx);
1358 // Write out the specific module cache path that contains the module files.
1359 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1360 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1362 // Preprocessor options.
1364 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1366 // Macro definitions.
1367 Record.push_back(PPOpts.Macros.size());
1368 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1369 AddString(PPOpts.Macros[I].first, Record);
1370 Record.push_back(PPOpts.Macros[I].second);
1374 Record.push_back(PPOpts.Includes.size());
1375 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1376 AddString(PPOpts.Includes[I], Record);
1379 Record.push_back(PPOpts.MacroIncludes.size());
1380 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1381 AddString(PPOpts.MacroIncludes[I], Record);
1383 Record.push_back(PPOpts.UsePredefines);
1384 // Detailed record is important since it is used for the module cache hash.
1385 Record.push_back(PPOpts.DetailedRecord);
1386 AddString(PPOpts.ImplicitPCHInclude, Record);
1387 AddString(PPOpts.ImplicitPTHInclude, Record);
1388 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1389 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1391 // Original file name and file ID
1392 SourceManager &SM = Context.getSourceManager();
1393 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1394 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1395 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1396 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1397 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1398 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1401 Record.push_back(ORIGINAL_FILE);
1402 Record.push_back(SM.getMainFileID().getOpaqueValue());
1403 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1407 Record.push_back(SM.getMainFileID().getOpaqueValue());
1408 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1410 // Original PCH directory
1411 if (!OutputFile.empty() && OutputFile != "-") {
1412 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1413 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1414 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1415 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1417 SmallString<128> OutputPath(OutputFile);
1419 llvm::sys::fs::make_absolute(OutputPath);
1420 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1423 Record.push_back(ORIGINAL_PCH_DIR);
1424 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1427 WriteInputFiles(Context.SourceMgr,
1428 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1429 PP.getLangOpts().Modules);
1434 /// \brief An input file.
1435 struct InputFileEntry {
1436 const FileEntry *File;
1438 bool BufferOverridden;
1442 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1443 HeaderSearchOptions &HSOpts,
1445 using namespace llvm;
1446 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1449 // Create input-file abbreviation.
1450 BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1451 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1452 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1453 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1454 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1455 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1456 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1457 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1459 // Get all ContentCache objects for files, sorted by whether the file is a
1460 // system one or not. System files go at the back, users files at the front.
1461 std::deque<InputFileEntry> SortedFiles;
1462 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1463 // Get this source location entry.
1464 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1465 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1467 // We only care about file entries that were not overridden.
1468 if (!SLoc->isFile())
1470 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1471 if (!Cache->OrigEntry)
1474 InputFileEntry Entry;
1475 Entry.File = Cache->OrigEntry;
1476 Entry.IsSystemFile = Cache->IsSystemFile;
1477 Entry.BufferOverridden = Cache->BufferOverridden;
1478 if (Cache->IsSystemFile)
1479 SortedFiles.push_back(Entry);
1481 SortedFiles.push_front(Entry);
1484 unsigned UserFilesNum = 0;
1485 // Write out all of the input files.
1486 std::vector<uint64_t> InputFileOffsets;
1487 for (std::deque<InputFileEntry>::iterator
1488 I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
1489 const InputFileEntry &Entry = *I;
1491 uint32_t &InputFileID = InputFileIDs[Entry.File];
1492 if (InputFileID != 0)
1493 continue; // already recorded this file.
1495 // Record this entry's offset.
1496 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1498 InputFileID = InputFileOffsets.size();
1500 if (!Entry.IsSystemFile)
1504 Record.push_back(INPUT_FILE);
1505 Record.push_back(InputFileOffsets.size());
1507 // Emit size/modification time for this file.
1508 Record.push_back(Entry.File->getSize());
1509 Record.push_back(Entry.File->getModificationTime());
1511 // Whether this file was overridden.
1512 Record.push_back(Entry.BufferOverridden);
1514 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1519 // Create input file offsets abbreviation.
1520 BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1521 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1522 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1523 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1525 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1526 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1528 // Write input file offsets.
1530 Record.push_back(INPUT_FILE_OFFSETS);
1531 Record.push_back(InputFileOffsets.size());
1532 Record.push_back(UserFilesNum);
1533 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1536 //===----------------------------------------------------------------------===//
1537 // Source Manager Serialization
1538 //===----------------------------------------------------------------------===//
1540 /// \brief Create an abbreviation for the SLocEntry that refers to a
1542 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1543 using namespace llvm;
1544 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1545 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1546 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1548 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1549 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1550 // FileEntry fields.
1551 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1555 return Stream.EmitAbbrev(Abbrev);
1558 /// \brief Create an abbreviation for the SLocEntry that refers to a
1560 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1561 using namespace llvm;
1562 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1563 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1569 return Stream.EmitAbbrev(Abbrev);
1572 /// \brief Create an abbreviation for the SLocEntry that refers to a
1574 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1575 using namespace llvm;
1576 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1577 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1578 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1579 return Stream.EmitAbbrev(Abbrev);
1582 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1584 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1585 using namespace llvm;
1586 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1587 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1588 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1590 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1591 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1592 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1593 return Stream.EmitAbbrev(Abbrev);
1597 // Trait used for the on-disk hash table of header search information.
1598 class HeaderFileInfoTrait {
1600 const HeaderSearch &HS;
1602 // Keep track of the framework names we've used during serialization.
1603 SmallVector<char, 128> FrameworkStringData;
1604 llvm::StringMap<unsigned> FrameworkNameOffset;
1607 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1608 : Writer(Writer), HS(HS) { }
1611 const FileEntry *FE;
1612 const char *Filename;
1614 typedef const key_type &key_type_ref;
1616 typedef HeaderFileInfo data_type;
1617 typedef const data_type &data_type_ref;
1618 typedef unsigned hash_value_type;
1619 typedef unsigned offset_type;
1621 static hash_value_type ComputeHash(key_type_ref key) {
1622 // The hash is based only on size/time of the file, so that the reader can
1623 // match even when symlinking or excess path elements ("foo/../", "../")
1624 // change the form of the name. However, complete path is still the key.
1626 // FIXME: Using the mtime here will cause problems for explicit module
1628 return llvm::hash_combine(key.FE->getSize(),
1629 key.FE->getModificationTime());
1632 std::pair<unsigned,unsigned>
1633 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1634 using namespace llvm::support;
1635 endian::Writer<little> Writer(Out);
1636 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1637 Writer.write<uint16_t>(KeyLen);
1638 unsigned DataLen = 1 + 2 + 4 + 4;
1639 if (Data.isModuleHeader)
1641 Writer.write<uint8_t>(DataLen);
1642 return std::make_pair(KeyLen, DataLen);
1645 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1646 using namespace llvm::support;
1647 endian::Writer<little> LE(Out);
1648 LE.write<uint64_t>(key.FE->getSize());
1650 LE.write<uint64_t>(key.FE->getModificationTime());
1652 Out.write(key.Filename, KeyLen);
1655 void EmitData(raw_ostream &Out, key_type_ref key,
1656 data_type_ref Data, unsigned DataLen) {
1657 using namespace llvm::support;
1658 endian::Writer<little> LE(Out);
1659 uint64_t Start = Out.tell(); (void)Start;
1661 unsigned char Flags = (Data.HeaderRole << 6)
1662 | (Data.isImport << 5)
1663 | (Data.isPragmaOnce << 4)
1664 | (Data.DirInfo << 2)
1665 | (Data.Resolved << 1)
1666 | Data.IndexHeaderMapHeader;
1667 LE.write<uint8_t>(Flags);
1668 LE.write<uint16_t>(Data.NumIncludes);
1670 if (!Data.ControllingMacro)
1671 LE.write<uint32_t>(Data.ControllingMacroID);
1673 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1675 unsigned Offset = 0;
1676 if (!Data.Framework.empty()) {
1677 // If this header refers into a framework, save the framework name.
1678 llvm::StringMap<unsigned>::iterator Pos
1679 = FrameworkNameOffset.find(Data.Framework);
1680 if (Pos == FrameworkNameOffset.end()) {
1681 Offset = FrameworkStringData.size() + 1;
1682 FrameworkStringData.append(Data.Framework.begin(),
1683 Data.Framework.end());
1684 FrameworkStringData.push_back(0);
1686 FrameworkNameOffset[Data.Framework] = Offset;
1688 Offset = Pos->second;
1690 LE.write<uint32_t>(Offset);
1692 if (Data.isModuleHeader) {
1693 Module *Mod = HS.findModuleForHeader(key.FE).getModule();
1694 LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod));
1697 assert(Out.tell() - Start == DataLen && "Wrong data length");
1700 const char *strings_begin() const { return FrameworkStringData.begin(); }
1701 const char *strings_end() const { return FrameworkStringData.end(); }
1703 } // end anonymous namespace
1705 /// \brief Write the header search block for the list of files that
1707 /// \param HS The header search structure to save.
1708 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1709 SmallVector<const FileEntry *, 16> FilesByUID;
1710 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1712 if (FilesByUID.size() > HS.header_file_size())
1713 FilesByUID.resize(HS.header_file_size());
1715 HeaderFileInfoTrait GeneratorTrait(*this, HS);
1716 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1717 SmallVector<const char *, 4> SavedStrings;
1718 unsigned NumHeaderSearchEntries = 0;
1719 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1720 const FileEntry *File = FilesByUID[UID];
1724 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1725 // from the external source if it was not provided already.
1727 if (!HS.tryGetFileInfo(File, HFI) ||
1728 (HFI.External && Chain) ||
1729 (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
1732 // Massage the file path into an appropriate form.
1733 const char *Filename = File->getName();
1734 SmallString<128> FilenameTmp(Filename);
1735 if (PreparePathForOutput(FilenameTmp)) {
1736 // If we performed any translation on the file name at all, we need to
1737 // save this string, since the generator will refer to it later.
1738 Filename = strdup(FilenameTmp.c_str());
1739 SavedStrings.push_back(Filename);
1742 HeaderFileInfoTrait::key_type key = { File, Filename };
1743 Generator.insert(key, HFI, GeneratorTrait);
1744 ++NumHeaderSearchEntries;
1747 // Create the on-disk hash table in a buffer.
1748 SmallString<4096> TableData;
1749 uint32_t BucketOffset;
1751 using namespace llvm::support;
1752 llvm::raw_svector_ostream Out(TableData);
1753 // Make sure that no bucket is at offset 0
1754 endian::Writer<little>(Out).write<uint32_t>(0);
1755 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1758 // Create a blob abbreviation
1759 using namespace llvm;
1760 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1761 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1766 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1768 // Write the header search table
1770 Record.push_back(HEADER_SEARCH_TABLE);
1771 Record.push_back(BucketOffset);
1772 Record.push_back(NumHeaderSearchEntries);
1773 Record.push_back(TableData.size());
1774 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1775 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1777 // Free all of the strings we had to duplicate.
1778 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1779 free(const_cast<char *>(SavedStrings[I]));
1782 /// \brief Writes the block containing the serialized form of the
1785 /// TODO: We should probably use an on-disk hash table (stored in a
1786 /// blob), indexed based on the file name, so that we only create
1787 /// entries for files that we actually need. In the common case (no
1788 /// errors), we probably won't have to create file entries for any of
1789 /// the files in the AST.
1790 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1791 const Preprocessor &PP) {
1794 // Enter the source manager block.
1795 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1797 // Abbreviations for the various kinds of source-location entries.
1798 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1799 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1800 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1801 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1803 // Write out the source location entry table. We skip the first
1804 // entry, which is always the same dummy entry.
1805 std::vector<uint32_t> SLocEntryOffsets;
1806 RecordData PreloadSLocs;
1807 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1808 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1810 // Get this source location entry.
1811 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1812 FileID FID = FileID::get(I);
1813 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1815 // Record the offset of this source-location entry.
1816 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1818 // Figure out which record code to use.
1820 if (SLoc->isFile()) {
1821 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1822 if (Cache->OrigEntry) {
1823 Code = SM_SLOC_FILE_ENTRY;
1825 Code = SM_SLOC_BUFFER_ENTRY;
1827 Code = SM_SLOC_EXPANSION_ENTRY;
1829 Record.push_back(Code);
1831 // Starting offset of this entry within this module, so skip the dummy.
1832 Record.push_back(SLoc->getOffset() - 2);
1833 if (SLoc->isFile()) {
1834 const SrcMgr::FileInfo &File = SLoc->getFile();
1835 Record.push_back(File.getIncludeLoc().getRawEncoding());
1836 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1837 Record.push_back(File.hasLineDirectives());
1839 const SrcMgr::ContentCache *Content = File.getContentCache();
1840 if (Content->OrigEntry) {
1841 assert(Content->OrigEntry == Content->ContentsEntry &&
1842 "Writing to AST an overridden file is not supported");
1844 // The source location entry is a file. Emit input file ID.
1845 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1846 Record.push_back(InputFileIDs[Content->OrigEntry]);
1848 Record.push_back(File.NumCreatedFIDs);
1850 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1851 if (FDI != FileDeclIDs.end()) {
1852 Record.push_back(FDI->second->FirstDeclIndex);
1853 Record.push_back(FDI->second->DeclIDs.size());
1855 Record.push_back(0);
1856 Record.push_back(0);
1859 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1861 if (Content->BufferOverridden) {
1863 Record.push_back(SM_SLOC_BUFFER_BLOB);
1864 const llvm::MemoryBuffer *Buffer
1865 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1866 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1867 StringRef(Buffer->getBufferStart(),
1868 Buffer->getBufferSize() + 1));
1871 // The source location entry is a buffer. The blob associated
1872 // with this entry contains the contents of the buffer.
1874 // We add one to the size so that we capture the trailing NULL
1875 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1876 // the reader side).
1877 const llvm::MemoryBuffer *Buffer
1878 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1879 const char *Name = Buffer->getBufferIdentifier();
1880 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1881 StringRef(Name, strlen(Name) + 1));
1883 Record.push_back(SM_SLOC_BUFFER_BLOB);
1884 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1885 StringRef(Buffer->getBufferStart(),
1886 Buffer->getBufferSize() + 1));
1888 if (strcmp(Name, "<built-in>") == 0) {
1889 PreloadSLocs.push_back(SLocEntryOffsets.size());
1893 // The source location entry is a macro expansion.
1894 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1895 Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1896 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1897 Record.push_back(Expansion.isMacroArgExpansion() ? 0
1898 : Expansion.getExpansionLocEnd().getRawEncoding());
1900 // Compute the token length for this macro expansion.
1901 unsigned NextOffset = SourceMgr.getNextLocalOffset();
1903 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1904 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1905 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1911 if (SLocEntryOffsets.empty())
1914 // Write the source-location offsets table into the AST block. This
1915 // table is used for lazily loading source-location information.
1916 using namespace llvm;
1917 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1918 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1920 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1922 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1925 Record.push_back(SOURCE_LOCATION_OFFSETS);
1926 Record.push_back(SLocEntryOffsets.size());
1927 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1928 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, bytes(SLocEntryOffsets));
1930 // Write the source location entry preloads array, telling the AST
1931 // reader which source locations entries it should load eagerly.
1932 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1934 // Write the line table. It depends on remapping working, so it must come
1935 // after the source location offsets.
1936 if (SourceMgr.hasLineTable()) {
1937 LineTableInfo &LineTable = SourceMgr.getLineTable();
1940 // Emit the file names.
1941 Record.push_back(LineTable.getNumFilenames());
1942 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I)
1943 AddPath(LineTable.getFilename(I), Record);
1945 // Emit the line entries
1946 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1948 // Only emit entries for local files.
1949 if (L->first.ID < 0)
1953 Record.push_back(L->first.ID);
1955 // Emit the line entries
1956 Record.push_back(L->second.size());
1957 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1958 LEEnd = L->second.end();
1959 LE != LEEnd; ++LE) {
1960 Record.push_back(LE->FileOffset);
1961 Record.push_back(LE->LineNo);
1962 Record.push_back(LE->FilenameID);
1963 Record.push_back((unsigned)LE->FileKind);
1964 Record.push_back(LE->IncludeOffset);
1967 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1971 //===----------------------------------------------------------------------===//
1972 // Preprocessor Serialization
1973 //===----------------------------------------------------------------------===//
1975 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1976 const Preprocessor &PP) {
1977 if (MacroInfo *MI = MD->getMacroInfo())
1978 if (MI->isBuiltinMacro())
1982 SourceLocation Loc = MD->getLocation();
1983 if (Loc.isInvalid())
1985 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1992 /// \brief Writes the block containing the serialized form of the
1995 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1996 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1998 WritePreprocessorDetail(*PPRec);
2001 RecordData ModuleMacroRecord;
2003 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2004 if (PP.getCounterValue() != 0) {
2005 Record.push_back(PP.getCounterValue());
2006 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2010 // Enter the preprocessor block.
2011 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2013 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2014 // FIXME: use diagnostics subsystem for localization etc.
2015 if (PP.SawDateOrTime())
2016 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
2019 // Loop over all the macro directives that are live at the end of the file,
2020 // emitting each to the PP section.
2022 // Construct the list of identifiers with macro directives that need to be
2024 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2025 for (auto &Id : PP.getIdentifierTable())
2026 if (Id.second->hadMacroDefinition() &&
2027 (!Id.second->isFromAST() ||
2028 Id.second->hasChangedSinceDeserialization()))
2029 MacroIdentifiers.push_back(Id.second);
2030 // Sort the set of macro definitions that need to be serialized by the
2031 // name of the macro, to provide a stable ordering.
2032 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2033 llvm::less_ptr<IdentifierInfo>());
2035 // Emit the macro directives as a list and associate the offset with the
2036 // identifier they belong to.
2037 for (const IdentifierInfo *Name : MacroIdentifiers) {
2038 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2039 auto StartOffset = Stream.GetCurrentBitNo();
2041 // Emit the macro directives in reverse source order.
2042 for (; MD; MD = MD->getPrevious()) {
2043 // Once we hit an ignored macro, we're done: the rest of the chain
2044 // will all be ignored macros.
2045 if (shouldIgnoreMacro(MD, IsModule, PP))
2048 AddSourceLocation(MD->getLocation(), Record);
2049 Record.push_back(MD->getKind());
2050 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2051 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2052 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2053 Record.push_back(VisMD->isPublic());
2057 // Write out any exported module macros.
2058 bool EmittedModuleMacros = false;
2060 auto Leafs = PP.getLeafModuleMacros(Name);
2061 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2062 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2063 while (!Worklist.empty()) {
2064 auto *Macro = Worklist.pop_back_val();
2066 // Emit a record indicating this submodule exports this macro.
2067 ModuleMacroRecord.push_back(
2068 getSubmoduleID(Macro->getOwningModule()));
2069 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2070 for (auto *M : Macro->overrides())
2071 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2073 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2074 ModuleMacroRecord.clear();
2076 // Enqueue overridden macros once we've visited all their ancestors.
2077 for (auto *M : Macro->overrides())
2078 if (++Visits[M] == M->getNumOverridingMacros())
2079 Worklist.push_back(M);
2081 EmittedModuleMacros = true;
2085 if (Record.empty() && !EmittedModuleMacros)
2088 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2089 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2093 /// \brief Offsets of each of the macros into the bitstream, indexed by
2094 /// the local macro ID
2096 /// For each identifier that is associated with a macro, this map
2097 /// provides the offset into the bitstream where that macro is
2099 std::vector<uint32_t> MacroOffsets;
2101 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2102 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2103 MacroInfo *MI = MacroInfosToEmit[I].MI;
2104 MacroID ID = MacroInfosToEmit[I].ID;
2106 if (ID < FirstMacroID) {
2107 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2111 // Record the local offset of this macro.
2112 unsigned Index = ID - FirstMacroID;
2113 if (Index == MacroOffsets.size())
2114 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2116 if (Index > MacroOffsets.size())
2117 MacroOffsets.resize(Index + 1);
2119 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2122 AddIdentifierRef(Name, Record);
2123 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2124 AddSourceLocation(MI->getDefinitionLoc(), Record);
2125 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2126 Record.push_back(MI->isUsed());
2127 Record.push_back(MI->isUsedForHeaderGuard());
2129 if (MI->isObjectLike()) {
2130 Code = PP_MACRO_OBJECT_LIKE;
2132 Code = PP_MACRO_FUNCTION_LIKE;
2134 Record.push_back(MI->isC99Varargs());
2135 Record.push_back(MI->isGNUVarargs());
2136 Record.push_back(MI->hasCommaPasting());
2137 Record.push_back(MI->getNumArgs());
2138 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
2140 AddIdentifierRef(*I, Record);
2143 // If we have a detailed preprocessing record, record the macro definition
2144 // ID that corresponds to this macro.
2146 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2148 Stream.EmitRecord(Code, Record);
2151 // Emit the tokens array.
2152 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2153 // Note that we know that the preprocessor does not have any annotation
2154 // tokens in it because they are created by the parser, and thus can't
2155 // be in a macro definition.
2156 const Token &Tok = MI->getReplacementToken(TokNo);
2157 AddToken(Tok, Record);
2158 Stream.EmitRecord(PP_TOKEN, Record);
2166 // Write the offsets table for macro IDs.
2167 using namespace llvm;
2168 auto *Abbrev = new BitCodeAbbrev();
2169 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2171 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2172 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2174 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2176 Record.push_back(MACRO_OFFSET);
2177 Record.push_back(MacroOffsets.size());
2178 Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2179 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2180 bytes(MacroOffsets));
2183 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2184 if (PPRec.local_begin() == PPRec.local_end())
2187 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2189 // Enter the preprocessor block.
2190 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2192 // If the preprocessor has a preprocessing record, emit it.
2193 unsigned NumPreprocessingRecords = 0;
2194 using namespace llvm;
2196 // Set up the abbreviation for
2197 unsigned InclusionAbbrev = 0;
2199 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2200 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2203 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2204 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2205 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2206 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2209 unsigned FirstPreprocessorEntityID
2210 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2211 + NUM_PREDEF_PP_ENTITY_IDS;
2212 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2214 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2215 EEnd = PPRec.local_end();
2217 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2220 PreprocessedEntityOffsets.push_back(
2221 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2223 if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2224 // Record this macro definition's ID.
2225 MacroDefinitions[MD] = NextPreprocessorEntityID;
2227 AddIdentifierRef(MD->getName(), Record);
2228 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2232 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
2233 Record.push_back(ME->isBuiltinMacro());
2234 if (ME->isBuiltinMacro())
2235 AddIdentifierRef(ME->getName(), Record);
2237 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2238 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2242 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2243 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2244 Record.push_back(ID->getFileName().size());
2245 Record.push_back(ID->wasInQuotes());
2246 Record.push_back(static_cast<unsigned>(ID->getKind()));
2247 Record.push_back(ID->importedModule());
2248 SmallString<64> Buffer;
2249 Buffer += ID->getFileName();
2250 // Check that the FileEntry is not null because it was not resolved and
2251 // we create a PCH even with compiler errors.
2253 Buffer += ID->getFile()->getName();
2254 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2258 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2262 // Write the offsets table for the preprocessing record.
2263 if (NumPreprocessingRecords > 0) {
2264 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2266 // Write the offsets table for identifier IDs.
2267 using namespace llvm;
2268 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2269 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2270 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2272 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2275 Record.push_back(PPD_ENTITIES_OFFSETS);
2276 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2277 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2278 bytes(PreprocessedEntityOffsets));
2282 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2283 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2284 if (Known != SubmoduleIDs.end())
2285 return Known->second;
2287 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2290 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2294 llvm::DenseMap<Module *, unsigned>::const_iterator
2295 Known = SubmoduleIDs.find(Mod);
2296 if (Known != SubmoduleIDs.end())
2297 return Known->second;
2302 /// \brief Compute the number of modules within the given tree (including the
2304 static unsigned getNumberOfModules(Module *Mod) {
2305 unsigned ChildModules = 0;
2306 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2307 SubEnd = Mod->submodule_end();
2308 Sub != SubEnd; ++Sub)
2309 ChildModules += getNumberOfModules(*Sub);
2311 return ChildModules + 1;
2314 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2315 // Enter the submodule description block.
2316 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2318 // Write the abbreviations needed for the submodules block.
2319 using namespace llvm;
2320 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2321 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2322 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2323 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2324 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2325 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2326 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2327 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2328 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2329 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2330 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2332 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2333 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2335 Abbrev = new BitCodeAbbrev();
2336 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2338 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2340 Abbrev = new BitCodeAbbrev();
2341 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2343 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2345 Abbrev = new BitCodeAbbrev();
2346 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2347 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2348 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2350 Abbrev = new BitCodeAbbrev();
2351 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2352 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2353 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2355 Abbrev = new BitCodeAbbrev();
2356 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2357 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2359 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2361 Abbrev = new BitCodeAbbrev();
2362 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2363 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2364 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2366 Abbrev = new BitCodeAbbrev();
2367 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2369 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2371 Abbrev = new BitCodeAbbrev();
2372 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2374 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2376 Abbrev = new BitCodeAbbrev();
2377 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2379 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2381 Abbrev = new BitCodeAbbrev();
2382 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2383 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2385 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2387 Abbrev = new BitCodeAbbrev();
2388 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2390 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2392 Abbrev = new BitCodeAbbrev();
2393 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2395 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2396 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2398 // Write the submodule metadata block.
2400 Record.push_back(getNumberOfModules(WritingModule));
2401 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2402 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2404 // Write all of the submodules.
2405 std::queue<Module *> Q;
2406 Q.push(WritingModule);
2407 while (!Q.empty()) {
2408 Module *Mod = Q.front();
2410 unsigned ID = getSubmoduleID(Mod);
2412 // Emit the definition of the block.
2414 Record.push_back(SUBMODULE_DEFINITION);
2415 Record.push_back(ID);
2417 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2418 Record.push_back(SubmoduleIDs[Mod->Parent]);
2420 Record.push_back(0);
2422 Record.push_back(Mod->IsFramework);
2423 Record.push_back(Mod->IsExplicit);
2424 Record.push_back(Mod->IsSystem);
2425 Record.push_back(Mod->IsExternC);
2426 Record.push_back(Mod->InferSubmodules);
2427 Record.push_back(Mod->InferExplicitSubmodules);
2428 Record.push_back(Mod->InferExportWildcard);
2429 Record.push_back(Mod->ConfigMacrosExhaustive);
2430 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2432 // Emit the requirements.
2433 for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
2435 Record.push_back(SUBMODULE_REQUIRES);
2436 Record.push_back(Mod->Requirements[I].second);
2437 Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2438 Mod->Requirements[I].first);
2441 // Emit the umbrella header, if there is one.
2442 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2444 Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2445 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2446 UmbrellaHeader.NameAsWritten);
2447 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2449 Record.push_back(SUBMODULE_UMBRELLA_DIR);
2450 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2451 UmbrellaDir.NameAsWritten);
2454 // Emit the headers.
2456 unsigned RecordKind;
2458 Module::HeaderKind HeaderKind;
2460 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2461 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2462 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2463 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2464 Module::HK_PrivateTextual},
2465 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2467 for (auto &HL : HeaderLists) {
2469 Record.push_back(HL.RecordKind);
2470 for (auto &H : Mod->Headers[HL.HeaderKind])
2471 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2474 // Emit the top headers.
2476 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2478 Record.push_back(SUBMODULE_TOPHEADER);
2479 for (auto *H : TopHeaders)
2480 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2483 // Emit the imports.
2484 if (!Mod->Imports.empty()) {
2486 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2487 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2488 assert(ImportedID && "Unknown submodule!");
2489 Record.push_back(ImportedID);
2491 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2494 // Emit the exports.
2495 if (!Mod->Exports.empty()) {
2497 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2498 if (Module *Exported = Mod->Exports[I].getPointer()) {
2499 unsigned ExportedID = getSubmoduleID(Exported);
2500 Record.push_back(ExportedID);
2502 Record.push_back(0);
2505 Record.push_back(Mod->Exports[I].getInt());
2507 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2510 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2511 // Might be unnecessary as use declarations are only used to build the
2514 // Emit the link libraries.
2515 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2517 Record.push_back(SUBMODULE_LINK_LIBRARY);
2518 Record.push_back(Mod->LinkLibraries[I].IsFramework);
2519 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2520 Mod->LinkLibraries[I].Library);
2523 // Emit the conflicts.
2524 for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2526 Record.push_back(SUBMODULE_CONFLICT);
2527 unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2528 assert(OtherID && "Unknown submodule!");
2529 Record.push_back(OtherID);
2530 Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2531 Mod->Conflicts[I].Message);
2534 // Emit the configuration macros.
2535 for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
2537 Record.push_back(SUBMODULE_CONFIG_MACRO);
2538 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2539 Mod->ConfigMacros[I]);
2542 // Queue up the submodules of this module.
2543 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2544 SubEnd = Mod->submodule_end();
2545 Sub != SubEnd; ++Sub)
2551 // FIXME: This can easily happen, if we have a reference to a submodule that
2552 // did not result in us loading a module file for that submodule. For
2553 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2554 assert((NextSubmoduleID - FirstSubmoduleID ==
2555 getNumberOfModules(WritingModule)) &&
2556 "Wrong # of submodules; found a reference to a non-local, "
2557 "non-imported submodule?");
2560 serialization::SubmoduleID
2561 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2562 if (Loc.isInvalid() || !WritingModule)
2563 return 0; // No submodule
2565 // Find the module that owns this location.
2566 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2568 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2572 // Check whether this submodule is part of our own module.
2573 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2576 return getSubmoduleID(OwningMod);
2579 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2581 // Make sure set diagnostic pragmas don't affect the translation unit that
2582 // imports the module.
2583 // FIXME: Make diagnostic pragma sections work properly with modules.
2587 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2589 unsigned CurrID = 0;
2590 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2592 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2593 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2595 const DiagnosticsEngine::DiagStatePoint &point = *I;
2596 if (point.Loc.isInvalid())
2599 Record.push_back(point.Loc.getRawEncoding());
2600 unsigned &DiagStateID = DiagStateIDMap[point.State];
2601 Record.push_back(DiagStateID);
2603 if (DiagStateID == 0) {
2604 DiagStateID = ++CurrID;
2605 for (DiagnosticsEngine::DiagState::const_iterator
2606 I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2607 if (I->second.isPragma()) {
2608 Record.push_back(I->first);
2609 Record.push_back((unsigned)I->second.getSeverity());
2612 Record.push_back(-1); // mark the end of the diag/map pairs for this
2617 if (!Record.empty())
2618 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2621 void ASTWriter::WriteCXXCtorInitializersOffsets() {
2622 if (CXXCtorInitializersOffsets.empty())
2627 // Create a blob abbreviation for the C++ ctor initializer offsets.
2628 using namespace llvm;
2630 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2631 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2632 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2634 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2636 // Write the base specifier offsets table.
2638 Record.push_back(CXX_CTOR_INITIALIZERS_OFFSETS);
2639 Record.push_back(CXXCtorInitializersOffsets.size());
2640 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
2641 bytes(CXXCtorInitializersOffsets));
2644 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2645 if (CXXBaseSpecifiersOffsets.empty())
2650 // Create a blob abbreviation for the C++ base specifiers offsets.
2651 using namespace llvm;
2653 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2654 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2655 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2657 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2659 // Write the base specifier offsets table.
2661 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2662 Record.push_back(CXXBaseSpecifiersOffsets.size());
2663 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2664 bytes(CXXBaseSpecifiersOffsets));
2667 //===----------------------------------------------------------------------===//
2668 // Type Serialization
2669 //===----------------------------------------------------------------------===//
2671 /// \brief Write the representation of a type to the AST stream.
2672 void ASTWriter::WriteType(QualType T) {
2673 TypeIdx &Idx = TypeIdxs[T];
2674 if (Idx.getIndex() == 0) // we haven't seen this type before.
2675 Idx = TypeIdx(NextTypeID++);
2677 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2679 // Record the offset for this type.
2680 unsigned Index = Idx.getIndex() - FirstTypeID;
2681 if (TypeOffsets.size() == Index)
2682 TypeOffsets.push_back(Stream.GetCurrentBitNo());
2683 else if (TypeOffsets.size() < Index) {
2684 TypeOffsets.resize(Index + 1);
2685 TypeOffsets[Index] = Stream.GetCurrentBitNo();
2690 // Emit the type's representation.
2691 ASTTypeWriter W(*this, Record);
2694 if (T.hasLocalNonFastQualifiers()) {
2695 Qualifiers Qs = T.getLocalQualifiers();
2696 AddTypeRef(T.getLocalUnqualifiedType(), Record);
2697 Record.push_back(Qs.getAsOpaqueValue());
2698 W.Code = TYPE_EXT_QUAL;
2699 W.AbbrevToUse = TypeExtQualAbbrev;
2701 switch (T->getTypeClass()) {
2702 // For all of the concrete, non-dependent types, call the
2703 // appropriate visitor function.
2704 #define TYPE(Class, Base) \
2705 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2706 #define ABSTRACT_TYPE(Class, Base)
2707 #include "clang/AST/TypeNodes.def"
2711 // Emit the serialized record.
2712 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
2714 // Flush any expressions that were written as part of this type.
2718 //===----------------------------------------------------------------------===//
2719 // Declaration Serialization
2720 //===----------------------------------------------------------------------===//
2722 /// \brief Write the block containing all of the declaration IDs
2723 /// lexically declared within the given DeclContext.
2725 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2726 /// bistream, or 0 if no block was written.
2727 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2729 if (DC->decls_empty())
2732 uint64_t Offset = Stream.GetCurrentBitNo();
2734 Record.push_back(DECL_CONTEXT_LEXICAL);
2735 SmallVector<KindDeclIDPair, 64> Decls;
2736 for (const auto *D : DC->decls())
2737 Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D)));
2739 ++NumLexicalDeclContexts;
2740 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, bytes(Decls));
2744 void ASTWriter::WriteTypeDeclOffsets() {
2745 using namespace llvm;
2748 // Write the type offsets array
2749 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2750 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2754 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2756 Record.push_back(TYPE_OFFSET);
2757 Record.push_back(TypeOffsets.size());
2758 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2759 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2761 // Write the declaration offsets array
2762 Abbrev = new BitCodeAbbrev();
2763 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2767 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2769 Record.push_back(DECL_OFFSET);
2770 Record.push_back(DeclOffsets.size());
2771 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2772 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2775 void ASTWriter::WriteFileDeclIDsMap() {
2776 using namespace llvm;
2779 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2780 FileDeclIDs.begin(), FileDeclIDs.end());
2781 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2782 llvm::less_first());
2784 // Join the vectors of DeclIDs from all files.
2785 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2786 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2787 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2788 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2789 for (auto &LocDeclEntry : Info.DeclIDs)
2790 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2793 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2794 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2797 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2798 Record.push_back(FILE_SORTED_DECLS);
2799 Record.push_back(FileGroupedDeclIDs.size());
2800 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2803 void ASTWriter::WriteComments() {
2804 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2805 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2807 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2808 E = RawComments.end();
2811 AddSourceRange((*I)->getSourceRange(), Record);
2812 Record.push_back((*I)->getKind());
2813 Record.push_back((*I)->isTrailingComment());
2814 Record.push_back((*I)->isAlmostTrailingComment());
2815 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2820 //===----------------------------------------------------------------------===//
2821 // Global Method Pool and Selector Serialization
2822 //===----------------------------------------------------------------------===//
2825 // Trait used for the on-disk hash table used in the method pool.
2826 class ASTMethodPoolTrait {
2830 typedef Selector key_type;
2831 typedef key_type key_type_ref;
2835 ObjCMethodList Instance, Factory;
2837 typedef const data_type& data_type_ref;
2839 typedef unsigned hash_value_type;
2840 typedef unsigned offset_type;
2842 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2844 static hash_value_type ComputeHash(Selector Sel) {
2845 return serialization::ComputeHash(Sel);
2848 std::pair<unsigned,unsigned>
2849 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2850 data_type_ref Methods) {
2851 using namespace llvm::support;
2852 endian::Writer<little> LE(Out);
2853 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2854 LE.write<uint16_t>(KeyLen);
2855 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2856 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2857 Method = Method->getNext())
2858 if (Method->getMethod())
2860 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2861 Method = Method->getNext())
2862 if (Method->getMethod())
2864 LE.write<uint16_t>(DataLen);
2865 return std::make_pair(KeyLen, DataLen);
2868 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2869 using namespace llvm::support;
2870 endian::Writer<little> LE(Out);
2871 uint64_t Start = Out.tell();
2872 assert((Start >> 32) == 0 && "Selector key offset too large");
2873 Writer.SetSelectorOffset(Sel, Start);
2874 unsigned N = Sel.getNumArgs();
2875 LE.write<uint16_t>(N);
2878 for (unsigned I = 0; I != N; ++I)
2880 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2883 void EmitData(raw_ostream& Out, key_type_ref,
2884 data_type_ref Methods, unsigned DataLen) {
2885 using namespace llvm::support;
2886 endian::Writer<little> LE(Out);
2887 uint64_t Start = Out.tell(); (void)Start;
2888 LE.write<uint32_t>(Methods.ID);
2889 unsigned NumInstanceMethods = 0;
2890 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2891 Method = Method->getNext())
2892 if (Method->getMethod())
2893 ++NumInstanceMethods;
2895 unsigned NumFactoryMethods = 0;
2896 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2897 Method = Method->getNext())
2898 if (Method->getMethod())
2899 ++NumFactoryMethods;
2901 unsigned InstanceBits = Methods.Instance.getBits();
2902 assert(InstanceBits < 4);
2903 unsigned InstanceHasMoreThanOneDeclBit =
2904 Methods.Instance.hasMoreThanOneDecl();
2905 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2906 (InstanceHasMoreThanOneDeclBit << 2) |
2908 unsigned FactoryBits = Methods.Factory.getBits();
2909 assert(FactoryBits < 4);
2910 unsigned FactoryHasMoreThanOneDeclBit =
2911 Methods.Factory.hasMoreThanOneDecl();
2912 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2913 (FactoryHasMoreThanOneDeclBit << 2) |
2915 LE.write<uint16_t>(FullInstanceBits);
2916 LE.write<uint16_t>(FullFactoryBits);
2917 for (const ObjCMethodList *Method = &Methods.Instance; Method;
2918 Method = Method->getNext())
2919 if (Method->getMethod())
2920 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2921 for (const ObjCMethodList *Method = &Methods.Factory; Method;
2922 Method = Method->getNext())
2923 if (Method->getMethod())
2924 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2926 assert(Out.tell() - Start == DataLen && "Data length is wrong");
2929 } // end anonymous namespace
2931 /// \brief Write ObjC data: selectors and the method pool.
2933 /// The method pool contains both instance and factory methods, stored
2934 /// in an on-disk hash table indexed by the selector. The hash table also
2935 /// contains an empty entry for every other selector known to Sema.
2936 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2937 using namespace llvm;
2939 // Do we have to do anything at all?
2940 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2942 unsigned NumTableEntries = 0;
2943 // Create and write out the blob that contains selectors and the method pool.
2945 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2946 ASTMethodPoolTrait Trait(*this);
2948 // Create the on-disk hash table representation. We walk through every
2949 // selector we've seen and look it up in the method pool.
2950 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2951 for (auto &SelectorAndID : SelectorIDs) {
2952 Selector S = SelectorAndID.first;
2953 SelectorID ID = SelectorAndID.second;
2954 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2955 ASTMethodPoolTrait::data_type Data = {
2960 if (F != SemaRef.MethodPool.end()) {
2961 Data.Instance = F->second.first;
2962 Data.Factory = F->second.second;
2964 // Only write this selector if it's not in an existing AST or something
2966 if (Chain && ID < FirstSelectorID) {
2967 // Selector already exists. Did it change?
2968 bool changed = false;
2969 for (ObjCMethodList *M = &Data.Instance;
2970 !changed && M && M->getMethod(); M = M->getNext()) {
2971 if (!M->getMethod()->isFromASTFile())
2974 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
2976 if (!M->getMethod()->isFromASTFile())
2981 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
2982 // A new method pool entry.
2985 Generator.insert(S, Data, Trait);
2988 // Create the on-disk hash table in a buffer.
2989 SmallString<4096> MethodPool;
2990 uint32_t BucketOffset;
2992 using namespace llvm::support;
2993 ASTMethodPoolTrait Trait(*this);
2994 llvm::raw_svector_ostream Out(MethodPool);
2995 // Make sure that no bucket is at offset 0
2996 endian::Writer<little>(Out).write<uint32_t>(0);
2997 BucketOffset = Generator.Emit(Out, Trait);
3000 // Create a blob abbreviation
3001 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3002 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3003 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3004 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3005 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3006 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3008 // Write the method pool
3010 Record.push_back(METHOD_POOL);
3011 Record.push_back(BucketOffset);
3012 Record.push_back(NumTableEntries);
3013 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3015 // Create a blob abbreviation for the selector table offsets.
3016 Abbrev = new BitCodeAbbrev();
3017 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3018 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3019 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3020 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3021 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3023 // Write the selector offsets table.
3025 Record.push_back(SELECTOR_OFFSETS);
3026 Record.push_back(SelectorOffsets.size());
3027 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
3028 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3029 bytes(SelectorOffsets));
3033 /// \brief Write the selectors referenced in @selector expression into AST file.
3034 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3035 using namespace llvm;
3036 if (SemaRef.ReferencedSelectors.empty())
3041 // Note: this writes out all references even for a dependent AST. But it is
3042 // very tricky to fix, and given that @selector shouldn't really appear in
3043 // headers, probably not worth it. It's not a correctness issue.
3044 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3045 Selector Sel = SelectorAndLocation.first;
3046 SourceLocation Loc = SelectorAndLocation.second;
3047 AddSelectorRef(Sel, Record);
3048 AddSourceLocation(Loc, Record);
3050 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
3053 //===----------------------------------------------------------------------===//
3054 // Identifier Table Serialization
3055 //===----------------------------------------------------------------------===//
3057 /// Determine the declaration that should be put into the name lookup table to
3058 /// represent the given declaration in this module. This is usually D itself,
3059 /// but if D was imported and merged into a local declaration, we want the most
3060 /// recent local declaration instead. The chosen declaration will be the most
3061 /// recent declaration in any module that imports this one.
3062 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3064 if (!LangOpts.Modules || !D->isFromASTFile())
3067 if (Decl *Redecl = D->getPreviousDecl()) {
3068 // For Redeclarable decls, a prior declaration might be local.
3069 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3070 if (!Redecl->isFromASTFile())
3071 return cast<NamedDecl>(Redecl);
3072 // If we find a decl from a (chained-)PCH stop since we won't find a
3074 if (D->getOwningModuleID() == 0)
3077 } else if (Decl *First = D->getCanonicalDecl()) {
3078 // For Mergeable decls, the first decl might be local.
3079 if (!First->isFromASTFile())
3080 return cast<NamedDecl>(First);
3083 // All declarations are imported. Our most recent declaration will also be
3084 // the most recent one in anyone who imports us.
3089 class ASTIdentifierTableTrait {
3092 IdentifierResolver &IdResolver;
3094 /// \brief Determines whether this is an "interesting" identifier that needs a
3095 /// full IdentifierInfo structure written into the hash table. Notably, this
3096 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3098 bool isInterestingIdentifier(IdentifierInfo *II, uint64_t MacroOffset) {
3101 II->isExtensionToken() ||
3102 II->getObjCOrBuiltinID() ||
3103 II->hasRevertedTokenIDToIdentifier() ||
3104 II->getFETokenInfo<void>())
3111 typedef IdentifierInfo* key_type;
3112 typedef key_type key_type_ref;
3114 typedef IdentID data_type;
3115 typedef data_type data_type_ref;
3117 typedef unsigned hash_value_type;
3118 typedef unsigned offset_type;
3120 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3121 IdentifierResolver &IdResolver)
3122 : Writer(Writer), PP(PP), IdResolver(IdResolver) {}
3124 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3125 return llvm::HashString(II->getName());
3128 std::pair<unsigned,unsigned>
3129 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3130 unsigned KeyLen = II->getLength() + 1;
3131 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3132 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3133 if (isInterestingIdentifier(II, MacroOffset)) {
3134 DataLen += 2; // 2 bytes for builtin ID
3135 DataLen += 2; // 2 bytes for flags
3137 DataLen += 4; // MacroDirectives offset.
3139 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3140 DEnd = IdResolver.end();
3144 using namespace llvm::support;
3145 endian::Writer<little> LE(Out);
3147 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3148 LE.write<uint16_t>(DataLen);
3149 // We emit the key length after the data length so that every
3150 // string is preceded by a 16-bit length. This matches the PTH
3151 // format for storing identifiers.
3152 LE.write<uint16_t>(KeyLen);
3153 return std::make_pair(KeyLen, DataLen);
3156 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3158 // Record the location of the key data. This is used when generating
3159 // the mapping from persistent IDs to strings.
3160 Writer.SetIdentifierOffset(II, Out.tell());
3161 Out.write(II->getNameStart(), KeyLen);
3164 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3165 IdentID ID, unsigned) {
3166 using namespace llvm::support;
3167 endian::Writer<little> LE(Out);
3169 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3170 if (!isInterestingIdentifier(II, MacroOffset)) {
3171 LE.write<uint32_t>(ID << 1);
3175 LE.write<uint32_t>((ID << 1) | 0x01);
3176 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3177 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3178 LE.write<uint16_t>(Bits);
3180 bool HadMacroDefinition = MacroOffset != 0;
3181 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3182 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3183 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3184 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3185 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3186 LE.write<uint16_t>(Bits);
3188 if (HadMacroDefinition)
3189 LE.write<uint32_t>(MacroOffset);
3191 // Emit the declaration IDs in reverse order, because the
3192 // IdentifierResolver provides the declarations as they would be
3193 // visible (e.g., the function "stat" would come before the struct
3194 // "stat"), but the ASTReader adds declarations to the end of the list
3195 // (so we need to see the struct "stat" before the function "stat").
3196 // Only emit declarations that aren't from a chained PCH, though.
3197 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), IdResolver.end());
3198 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3199 DEnd = Decls.rend();
3202 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3205 } // end anonymous namespace
3207 /// \brief Write the identifier table into the AST file.
3209 /// The identifier table consists of a blob containing string data
3210 /// (the actual identifiers themselves) and a separate "offsets" index
3211 /// that maps identifier IDs to locations within the blob.
3212 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3213 IdentifierResolver &IdResolver,
3215 using namespace llvm;
3217 // Create and write out the blob that contains the identifier
3220 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3221 ASTIdentifierTableTrait Trait(*this, PP, IdResolver);
3223 // Look for any identifiers that were named while processing the
3224 // headers, but are otherwise not needed. We add these to the hash
3225 // table to enable checking of the predefines buffer in the case
3226 // where the user adds new macro definitions when building the AST
3228 SmallVector<const IdentifierInfo *, 128> IIs;
3229 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3230 IDEnd = PP.getIdentifierTable().end();
3232 IIs.push_back(ID->second);
3233 // Sort the identifiers lexicographically before getting them references so
3234 // that their order is stable.
3235 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3236 for (const IdentifierInfo *II : IIs)
3237 getIdentifierRef(II);
3239 // Create the on-disk hash table representation. We only store offsets
3240 // for identifiers that appear here for the first time.
3241 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3242 for (auto IdentIDPair : IdentifierIDs) {
3243 IdentifierInfo *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3244 IdentID ID = IdentIDPair.second;
3245 assert(II && "NULL identifier in identifier table");
3246 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
3247 Generator.insert(II, ID, Trait);
3250 // Create the on-disk hash table in a buffer.
3251 SmallString<4096> IdentifierTable;
3252 uint32_t BucketOffset;
3254 using namespace llvm::support;
3255 llvm::raw_svector_ostream Out(IdentifierTable);
3256 // Make sure that no bucket is at offset 0
3257 endian::Writer<little>(Out).write<uint32_t>(0);
3258 BucketOffset = Generator.Emit(Out, Trait);
3261 // Create a blob abbreviation
3262 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3263 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3264 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3265 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3266 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3268 // Write the identifier table
3270 Record.push_back(IDENTIFIER_TABLE);
3271 Record.push_back(BucketOffset);
3272 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3275 // Write the offsets table for identifier IDs.
3276 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3277 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3278 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3279 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3280 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3281 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3284 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3285 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3289 Record.push_back(IDENTIFIER_OFFSET);
3290 Record.push_back(IdentifierOffsets.size());
3291 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
3292 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3293 bytes(IdentifierOffsets));
3296 //===----------------------------------------------------------------------===//
3297 // DeclContext's Name Lookup Table Serialization
3298 //===----------------------------------------------------------------------===//
3301 // Trait used for the on-disk hash table used in the method pool.
3302 class ASTDeclContextNameLookupTrait {
3306 typedef DeclarationName key_type;
3307 typedef key_type key_type_ref;
3309 typedef DeclContext::lookup_result data_type;
3310 typedef const data_type& data_type_ref;
3312 typedef unsigned hash_value_type;
3313 typedef unsigned offset_type;
3315 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3317 hash_value_type ComputeHash(DeclarationName Name) {
3318 llvm::FoldingSetNodeID ID;
3319 ID.AddInteger(Name.getNameKind());
3321 switch (Name.getNameKind()) {
3322 case DeclarationName::Identifier:
3323 ID.AddString(Name.getAsIdentifierInfo()->getName());
3325 case DeclarationName::ObjCZeroArgSelector:
3326 case DeclarationName::ObjCOneArgSelector:
3327 case DeclarationName::ObjCMultiArgSelector:
3328 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3330 case DeclarationName::CXXConstructorName:
3331 case DeclarationName::CXXDestructorName:
3332 case DeclarationName::CXXConversionFunctionName:
3334 case DeclarationName::CXXOperatorName:
3335 ID.AddInteger(Name.getCXXOverloadedOperator());
3337 case DeclarationName::CXXLiteralOperatorName:
3338 ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3339 case DeclarationName::CXXUsingDirective:
3343 return ID.ComputeHash();
3346 std::pair<unsigned,unsigned>
3347 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3348 data_type_ref Lookup) {
3349 using namespace llvm::support;
3350 endian::Writer<little> LE(Out);
3351 unsigned KeyLen = 1;
3352 switch (Name.getNameKind()) {
3353 case DeclarationName::Identifier:
3354 case DeclarationName::ObjCZeroArgSelector:
3355 case DeclarationName::ObjCOneArgSelector:
3356 case DeclarationName::ObjCMultiArgSelector:
3357 case DeclarationName::CXXLiteralOperatorName:
3360 case DeclarationName::CXXOperatorName:
3363 case DeclarationName::CXXConstructorName:
3364 case DeclarationName::CXXDestructorName:
3365 case DeclarationName::CXXConversionFunctionName:
3366 case DeclarationName::CXXUsingDirective:
3369 LE.write<uint16_t>(KeyLen);
3371 // 2 bytes for num of decls and 4 for each DeclID.
3372 unsigned DataLen = 2 + 4 * Lookup.size();
3373 LE.write<uint16_t>(DataLen);
3375 return std::make_pair(KeyLen, DataLen);
3378 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3379 using namespace llvm::support;
3380 endian::Writer<little> LE(Out);
3381 LE.write<uint8_t>(Name.getNameKind());
3382 switch (Name.getNameKind()) {
3383 case DeclarationName::Identifier:
3384 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3386 case DeclarationName::ObjCZeroArgSelector:
3387 case DeclarationName::ObjCOneArgSelector:
3388 case DeclarationName::ObjCMultiArgSelector:
3389 LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
3391 case DeclarationName::CXXOperatorName:
3392 assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3393 "Invalid operator?");
3394 LE.write<uint8_t>(Name.getCXXOverloadedOperator());
3396 case DeclarationName::CXXLiteralOperatorName:
3397 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3399 case DeclarationName::CXXConstructorName:
3400 case DeclarationName::CXXDestructorName:
3401 case DeclarationName::CXXConversionFunctionName:
3402 case DeclarationName::CXXUsingDirective:
3406 llvm_unreachable("Invalid name kind?");
3409 void EmitData(raw_ostream& Out, key_type_ref,
3410 data_type Lookup, unsigned DataLen) {
3411 using namespace llvm::support;
3412 endian::Writer<little> LE(Out);
3413 uint64_t Start = Out.tell(); (void)Start;
3414 LE.write<uint16_t>(Lookup.size());
3415 for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3418 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), *I)));
3420 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3423 } // end anonymous namespace
3425 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3427 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3430 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3432 for (auto *D : Result.getLookupResult())
3433 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3440 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3441 llvm::SmallVectorImpl<char> &LookupTable) {
3442 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3443 !ConstDC->HasLazyExternalLexicalLookups &&
3444 "must call buildLookups first");
3446 // FIXME: We need to build the lookups table, which is logically const.
3447 DeclContext *DC = const_cast<DeclContext*>(ConstDC);
3448 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3450 // Create the on-disk hash table representation.
3451 llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
3453 ASTDeclContextNameLookupTrait Trait(*this);
3455 // The first step is to collect the declaration names which we need to
3456 // serialize into the name lookup table, and to collect them in a stable
3458 SmallVector<DeclarationName, 16> Names;
3460 // We also build up small sets of the constructor and conversion function
3461 // names which are visible.
3462 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3464 for (auto &Lookup : *DC->buildLookup()) {
3465 auto &Name = Lookup.first;
3466 auto &Result = Lookup.second;
3468 // If there are no local declarations in our lookup result, we don't
3469 // need to write an entry for the name at all unless we're rewriting
3470 // the decl context. If we can't write out a lookup set without
3471 // performing more deserialization, just skip this entry.
3472 if (isLookupResultExternal(Result, DC) && !isRewritten(cast<Decl>(DC)) &&
3473 isLookupResultEntirelyExternal(Result, DC))
3476 // We also skip empty results. If any of the results could be external and
3477 // the currently available results are empty, then all of the results are
3478 // external and we skip it above. So the only way we get here with an empty
3479 // results is when no results could have been external *and* we have
3480 // external results.
3482 // FIXME: While we might want to start emitting on-disk entries for negative
3483 // lookups into a decl context as an optimization, today we *have* to skip
3484 // them because there are names with empty lookup results in decl contexts
3485 // which we can't emit in any stable ordering: we lookup constructors and
3486 // conversion functions in the enclosing namespace scope creating empty
3487 // results for them. This in almost certainly a bug in Clang's name lookup,
3488 // but that is likely to be hard or impossible to fix and so we tolerate it
3489 // here by omitting lookups with empty results.
3490 if (Lookup.second.getLookupResult().empty())
3493 switch (Lookup.first.getNameKind()) {
3495 Names.push_back(Lookup.first);
3498 case DeclarationName::CXXConstructorName:
3499 assert(isa<CXXRecordDecl>(DC) &&
3500 "Cannot have a constructor name outside of a class!");
3501 ConstructorNameSet.insert(Name);
3504 case DeclarationName::CXXConversionFunctionName:
3505 assert(isa<CXXRecordDecl>(DC) &&
3506 "Cannot have a conversion function name outside of a class!");
3507 ConversionNameSet.insert(Name);
3512 // Sort the names into a stable order.
3513 std::sort(Names.begin(), Names.end());
3515 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3516 // We need to establish an ordering of constructor and conversion function
3517 // names, and they don't have an intrinsic ordering.
3519 // First we try the easy case by forming the current context's constructor
3520 // name and adding that name first. This is a very useful optimization to
3521 // avoid walking the lexical declarations in many cases, and it also
3522 // handles the only case where a constructor name can come from some other
3523 // lexical context -- when that name is an implicit constructor merged from
3524 // another declaration in the redecl chain. Any non-implicit constructor or
3525 // conversion function which doesn't occur in all the lexical contexts
3526 // would be an ODR violation.
3527 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3528 Context->getCanonicalType(Context->getRecordType(D)));
3529 if (ConstructorNameSet.erase(ImplicitCtorName))
3530 Names.push_back(ImplicitCtorName);
3532 // If we still have constructors or conversion functions, we walk all the
3533 // names in the decl and add the constructors and conversion functions
3534 // which are visible in the order they lexically occur within the context.
3535 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3536 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3537 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3538 auto Name = ChildND->getDeclName();
3539 switch (Name.getNameKind()) {
3543 case DeclarationName::CXXConstructorName:
3544 if (ConstructorNameSet.erase(Name))
3545 Names.push_back(Name);
3548 case DeclarationName::CXXConversionFunctionName:
3549 if (ConversionNameSet.erase(Name))
3550 Names.push_back(Name);
3554 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3558 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3559 "constructors by walking all the "
3560 "lexical members of the context.");
3561 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3562 "conversion functions by walking all "
3563 "the lexical members of the context.");
3566 // Next we need to do a lookup with each name into this decl context to fully
3567 // populate any results from external sources. We don't actually use the
3568 // results of these lookups because we only want to use the results after all
3569 // results have been loaded and the pointers into them will be stable.
3570 for (auto &Name : Names)
3573 // Now we need to insert the results for each name into the hash table. For
3574 // constructor names and conversion function names, we actually need to merge
3575 // all of the results for them into one list of results each and insert
3577 SmallVector<NamedDecl *, 8> ConstructorDecls;
3578 SmallVector<NamedDecl *, 8> ConversionDecls;
3580 // Now loop over the names, either inserting them or appending for the two
3582 for (auto &Name : Names) {
3583 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3585 switch (Name.getNameKind()) {
3587 Generator.insert(Name, Result, Trait);
3590 case DeclarationName::CXXConstructorName:
3591 ConstructorDecls.append(Result.begin(), Result.end());
3594 case DeclarationName::CXXConversionFunctionName:
3595 ConversionDecls.append(Result.begin(), Result.end());
3600 // Handle our two special cases if we ended up having any. We arbitrarily use
3601 // the first declaration's name here because the name itself isn't part of
3602 // the key, only the kind of name is used.
3603 if (!ConstructorDecls.empty())
3604 Generator.insert(ConstructorDecls.front()->getDeclName(),
3605 DeclContext::lookup_result(ConstructorDecls), Trait);
3606 if (!ConversionDecls.empty())
3607 Generator.insert(ConversionDecls.front()->getDeclName(),
3608 DeclContext::lookup_result(ConversionDecls), Trait);
3610 // Create the on-disk hash table in a buffer.
3611 llvm::raw_svector_ostream Out(LookupTable);
3612 // Make sure that no bucket is at offset 0
3613 using namespace llvm::support;
3614 endian::Writer<little>(Out).write<uint32_t>(0);
3615 return Generator.Emit(Out, Trait);
3618 /// \brief Write the block containing all of the declaration IDs
3619 /// visible from the given DeclContext.
3621 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3622 /// bitstream, or 0 if no block was written.
3623 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3625 if (DC->getPrimaryContext() != DC)
3628 // Skip contexts which don't support name lookup.
3629 if (!DC->isLookupContext())
3632 // If not in C++, we perform name lookup for the translation unit via the
3633 // IdentifierInfo chains, don't bother to build a visible-declarations table.
3634 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3637 // Serialize the contents of the mapping used for lookup. Note that,
3638 // although we have two very different code paths, the serialized
3639 // representation is the same for both cases: a declaration name,
3640 // followed by a size, followed by references to the visible
3641 // declarations that have that name.
3642 uint64_t Offset = Stream.GetCurrentBitNo();
3643 StoredDeclsMap *Map = DC->buildLookup();
3644 if (!Map || Map->empty())
3647 // Create the on-disk hash table in a buffer.
3648 SmallString<4096> LookupTable;
3649 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3651 // Write the lookup table
3653 Record.push_back(DECL_CONTEXT_VISIBLE);
3654 Record.push_back(BucketOffset);
3655 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3657 ++NumVisibleDeclContexts;
3661 /// \brief Write an UPDATE_VISIBLE block for the given context.
3663 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3664 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3665 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3666 /// enumeration members (in C++11).
3667 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3668 StoredDeclsMap *Map = DC->getLookupPtr();
3669 if (!Map || Map->empty())
3672 // Create the on-disk hash table in a buffer.
3673 SmallString<4096> LookupTable;
3674 uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3676 // Write the lookup table
3678 Record.push_back(UPDATE_VISIBLE);
3679 Record.push_back(getDeclID(cast<Decl>(DC)));
3680 Record.push_back(BucketOffset);
3681 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3684 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3685 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3687 Record.push_back(Opts.fp_contract);
3688 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3691 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3692 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3693 if (!SemaRef.Context.getLangOpts().OpenCL)
3696 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3698 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3699 #include "clang/Basic/OpenCLExtensions.def"
3700 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3703 void ASTWriter::WriteRedeclarations() {
3704 RecordData LocalRedeclChains;
3705 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3707 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3708 Decl *First = Redeclarations[I];
3709 assert(First->isFirstDecl() && "Not the first declaration?");
3711 Decl *MostRecent = First->getMostRecentDecl();
3713 // If we only have a single declaration, there is no point in storing
3714 // a redeclaration chain.
3715 if (First == MostRecent)
3718 unsigned Offset = LocalRedeclChains.size();
3720 LocalRedeclChains.push_back(0); // Placeholder for the size.
3722 // Collect the set of local redeclarations of this declaration.
3723 for (Decl *Prev = MostRecent; Prev != First;
3724 Prev = Prev->getPreviousDecl()) {
3725 if (!Prev->isFromASTFile()) {
3726 AddDeclRef(Prev, LocalRedeclChains);
3731 LocalRedeclChains[Offset] = Size;
3733 // Reverse the set of local redeclarations, so that we store them in
3734 // order (since we found them in reverse order).
3735 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3737 // Add the mapping from the first ID from the AST to the set of local
3739 LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3740 LocalRedeclsMap.push_back(Info);
3742 assert(N == Redeclarations.size() &&
3743 "Deserialized a declaration we shouldn't have");
3746 if (LocalRedeclChains.empty())
3749 // Sort the local redeclarations map by the first declaration ID,
3750 // since the reader will be performing binary searches on this information.
3751 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3753 // Emit the local redeclarations map.
3754 using namespace llvm;
3755 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3756 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3759 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3762 Record.push_back(LOCAL_REDECLARATIONS_MAP);
3763 Record.push_back(LocalRedeclsMap.size());
3764 Stream.EmitRecordWithBlob(AbbrevID, Record,
3765 reinterpret_cast<char*>(LocalRedeclsMap.data()),
3766 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3768 // Emit the redeclaration chains.
3769 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3772 void ASTWriter::WriteObjCCategories() {
3773 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3774 RecordData Categories;
3776 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3778 unsigned StartIndex = Categories.size();
3780 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3782 // Allocate space for the size.
3783 Categories.push_back(0);
3785 // Add the categories.
3786 for (ObjCInterfaceDecl::known_categories_iterator
3787 Cat = Class->known_categories_begin(),
3788 CatEnd = Class->known_categories_end();
3789 Cat != CatEnd; ++Cat, ++Size) {
3790 assert(getDeclID(*Cat) != 0 && "Bogus category");
3791 AddDeclRef(*Cat, Categories);
3795 Categories[StartIndex] = Size;
3797 // Record this interface -> category map.
3798 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3799 CategoriesMap.push_back(CatInfo);
3802 // Sort the categories map by the definition ID, since the reader will be
3803 // performing binary searches on this information.
3804 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3806 // Emit the categories map.
3807 using namespace llvm;
3808 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3809 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3812 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3815 Record.push_back(OBJC_CATEGORIES_MAP);
3816 Record.push_back(CategoriesMap.size());
3817 Stream.EmitRecordWithBlob(AbbrevID, Record,
3818 reinterpret_cast<char*>(CategoriesMap.data()),
3819 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3821 // Emit the category lists.
3822 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3825 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3826 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3832 for (auto LPTMapEntry : LPTMap) {
3833 const FunctionDecl *FD = LPTMapEntry.first;
3834 LateParsedTemplate *LPT = LPTMapEntry.second;
3835 AddDeclRef(FD, Record);
3836 AddDeclRef(LPT->D, Record);
3837 Record.push_back(LPT->Toks.size());
3839 for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
3840 TokEnd = LPT->Toks.end();
3841 TokIt != TokEnd; ++TokIt) {
3842 AddToken(*TokIt, Record);
3845 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3848 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
3849 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3851 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3852 AddSourceLocation(PragmaLoc, Record);
3853 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3856 //===----------------------------------------------------------------------===//
3857 // General Serialization Routines
3858 //===----------------------------------------------------------------------===//
3860 /// \brief Write a record containing the given attributes.
3861 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3862 RecordDataImpl &Record) {
3863 Record.push_back(Attrs.size());
3864 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3865 e = Attrs.end(); i != e; ++i){
3867 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3868 AddSourceRange(A->getRange(), Record);
3870 #include "clang/Serialization/AttrPCHWrite.inc"
3875 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3876 AddSourceLocation(Tok.getLocation(), Record);
3877 Record.push_back(Tok.getLength());
3879 // FIXME: When reading literal tokens, reconstruct the literal pointer
3881 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3882 // FIXME: Should translate token kind to a stable encoding.
3883 Record.push_back(Tok.getKind());
3884 // FIXME: Should translate token flags to a stable encoding.
3885 Record.push_back(Tok.getFlags());
3888 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3889 Record.push_back(Str.size());
3890 Record.insert(Record.end(), Str.begin(), Str.end());
3893 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
3894 assert(Context && "should have context when outputting path");
3897 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
3899 // Remove a prefix to make the path relative, if relevant.
3900 const char *PathBegin = Path.data();
3901 const char *PathPtr =
3902 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
3903 if (PathPtr != PathBegin) {
3904 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
3911 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
3912 SmallString<128> FilePath(Path);
3913 PreparePathForOutput(FilePath);
3914 AddString(FilePath, Record);
3917 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
3919 SmallString<128> FilePath(Path);
3920 PreparePathForOutput(FilePath);
3921 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
3924 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3925 RecordDataImpl &Record) {
3926 Record.push_back(Version.getMajor());
3927 if (Optional<unsigned> Minor = Version.getMinor())
3928 Record.push_back(*Minor + 1);
3930 Record.push_back(0);
3931 if (Optional<unsigned> Subminor = Version.getSubminor())
3932 Record.push_back(*Subminor + 1);
3934 Record.push_back(0);
3937 /// \brief Note that the identifier II occurs at the given offset
3938 /// within the identifier table.
3939 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3940 IdentID ID = IdentifierIDs[II];
3941 // Only store offsets new to this AST file. Other identifier names are looked
3942 // up earlier in the chain and thus don't need an offset.
3943 if (ID >= FirstIdentID)
3944 IdentifierOffsets[ID - FirstIdentID] = Offset;
3947 /// \brief Note that the selector Sel occurs at the given offset
3948 /// within the method pool/selector table.
3949 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3950 unsigned ID = SelectorIDs[Sel];
3951 assert(ID && "Unknown selector");
3952 // Don't record offsets for selectors that are also available in a different
3954 if (ID < FirstSelectorID)
3956 SelectorOffsets[ID - FirstSelectorID] = Offset;
3959 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3960 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
3961 WritingModule(nullptr), WritingAST(false),
3962 DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false),
3963 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3964 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3965 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3966 FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3967 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3968 NextSubmoduleID(FirstSubmoduleID),
3969 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3970 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
3971 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
3972 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
3973 TypeExtQualAbbrev(0),
3974 TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
3975 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
3976 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
3977 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
3978 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
3979 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
3980 ExprImplicitCastAbbrev(0) {}
3982 ASTWriter::~ASTWriter() {
3983 llvm::DeleteContainerSeconds(FileDeclIDs);
3986 const LangOptions &ASTWriter::getLangOpts() const {
3987 assert(WritingAST && "can't determine lang opts when not writing AST");
3988 return Context->getLangOpts();
3991 void ASTWriter::WriteAST(Sema &SemaRef,
3992 const std::string &OutputFile,
3993 Module *WritingModule, StringRef isysroot,
3997 ASTHasCompilerErrors = hasErrors;
3999 // Emit the file header.
4000 Stream.Emit((unsigned)'C', 8);
4001 Stream.Emit((unsigned)'P', 8);
4002 Stream.Emit((unsigned)'C', 8);
4003 Stream.Emit((unsigned)'H', 8);
4005 WriteBlockInfoBlock();
4007 Context = &SemaRef.Context;
4009 this->WritingModule = WritingModule;
4010 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4013 this->WritingModule = nullptr;
4014 this->BaseDirectory.clear();
4019 template<typename Vector>
4020 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4021 ASTWriter::RecordData &Record) {
4022 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4024 Writer.AddDeclRef(*I, Record);
4028 void ASTWriter::WriteASTCore(Sema &SemaRef,
4030 const std::string &OutputFile,
4031 Module *WritingModule) {
4032 using namespace llvm;
4034 bool isModule = WritingModule != nullptr;
4036 // Make sure that the AST reader knows to finalize itself.
4038 Chain->finalizeForWriting();
4040 ASTContext &Context = SemaRef.Context;
4041 Preprocessor &PP = SemaRef.PP;
4043 // Set up predefined declaration IDs.
4044 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
4045 if (Context.ObjCIdDecl)
4046 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
4047 if (Context.ObjCSelDecl)
4048 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
4049 if (Context.ObjCClassDecl)
4050 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
4051 if (Context.ObjCProtocolClassDecl)
4052 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
4053 if (Context.Int128Decl)
4054 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
4055 if (Context.UInt128Decl)
4056 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
4057 if (Context.ObjCInstanceTypeDecl)
4058 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
4059 if (Context.BuiltinVaListDecl)
4060 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
4061 if (Context.ExternCContext)
4062 DeclIDs[Context.ExternCContext] = PREDEF_DECL_EXTERN_C_CONTEXT_ID;
4064 // Build a record containing all of the tentative definitions in this file, in
4065 // TentativeDefinitions order. Generally, this record will be empty for
4067 RecordData TentativeDefinitions;
4068 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4070 // Build a record containing all of the file scoped decls in this file.
4071 RecordData UnusedFileScopedDecls;
4073 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4074 UnusedFileScopedDecls);
4076 // Build a record containing all of the delegating constructors we still need
4078 RecordData DelegatingCtorDecls;
4080 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4082 // Write the set of weak, undeclared identifiers. We always write the
4083 // entire table, since later PCH files in a PCH chain are only interested in
4084 // the results at the end of the chain.
4085 RecordData WeakUndeclaredIdentifiers;
4086 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4087 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4088 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4089 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4090 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4091 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4092 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4095 // Build a record containing all of the ext_vector declarations.
4096 RecordData ExtVectorDecls;
4097 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4099 // Build a record containing all of the VTable uses information.
4100 RecordData VTableUses;
4101 if (!SemaRef.VTableUses.empty()) {
4102 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4103 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4104 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4105 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4109 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4110 RecordData UnusedLocalTypedefNameCandidates;
4111 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4112 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4114 // Build a record containing all of pending implicit instantiations.
4115 RecordData PendingInstantiations;
4116 for (std::deque<Sema::PendingImplicitInstantiation>::iterator
4117 I = SemaRef.PendingInstantiations.begin(),
4118 N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
4119 AddDeclRef(I->first, PendingInstantiations);
4120 AddSourceLocation(I->second, PendingInstantiations);
4122 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4123 "There are local ones at end of translation unit!");
4125 // Build a record containing some declaration references.
4126 RecordData SemaDeclRefs;
4127 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4128 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4129 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4132 RecordData CUDASpecialDeclRefs;
4133 if (Context.getcudaConfigureCallDecl()) {
4134 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4137 // Build a record containing all of the known namespaces.
4138 RecordData KnownNamespaces;
4139 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4140 I = SemaRef.KnownNamespaces.begin(),
4141 IEnd = SemaRef.KnownNamespaces.end();
4144 AddDeclRef(I->first, KnownNamespaces);
4147 // Build a record of all used, undefined objects that require definitions.
4148 RecordData UndefinedButUsed;
4150 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4151 SemaRef.getUndefinedButUsed(Undefined);
4152 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4153 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
4154 AddDeclRef(I->first, UndefinedButUsed);
4155 AddSourceLocation(I->second, UndefinedButUsed);
4158 // Build a record containing all delete-expressions that we would like to
4159 // analyze later in AST.
4160 RecordData DeleteExprsToAnalyze;
4162 for (const auto &DeleteExprsInfo :
4163 SemaRef.getMismatchingDeleteExpressions()) {
4164 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4165 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4166 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4167 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4168 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4172 // Write the control block
4173 WriteControlBlock(PP, Context, isysroot, OutputFile);
4175 // Write the remaining AST contents.
4177 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4179 // This is so that older clang versions, before the introduction
4180 // of the control block, can read and reject the newer PCH format.
4182 Record.push_back(VERSION_MAJOR);
4183 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4185 // Create a lexical update block containing all of the declarations in the
4186 // translation unit that do not come from other AST files.
4187 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4188 SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
4189 for (const auto *I : TU->noload_decls()) {
4190 if (!I->isFromASTFile())
4191 NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
4194 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4195 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4196 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4197 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4199 Record.push_back(TU_UPDATE_LEXICAL);
4200 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4201 bytes(NewGlobalDecls));
4203 // And a visible updates block for the translation unit.
4204 Abv = new llvm::BitCodeAbbrev();
4205 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4206 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4207 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4208 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4209 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4210 WriteDeclContextVisibleUpdate(TU);
4212 // If we have any extern "C" names, write out a visible update for them.
4213 if (Context.ExternCContext)
4214 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4216 // If the translation unit has an anonymous namespace, and we don't already
4217 // have an update block for it, write it as an update block.
4218 // FIXME: Why do we not do this if there's already an update block?
4219 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4220 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4222 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4225 // Add update records for all mangling numbers and static local numbers.
4226 // These aren't really update records, but this is a convenient way of
4227 // tagging this rare extra data onto the declarations.
4228 for (const auto &Number : Context.MangleNumbers)
4229 if (!Number.first->isFromASTFile())
4230 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4232 for (const auto &Number : Context.StaticLocalNumbers)
4233 if (!Number.first->isFromASTFile())
4234 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4237 // Make sure visible decls, added to DeclContexts previously loaded from
4238 // an AST file, are registered for serialization.
4239 for (SmallVectorImpl<const Decl *>::iterator
4240 I = UpdatingVisibleDecls.begin(),
4241 E = UpdatingVisibleDecls.end(); I != E; ++I) {
4245 // Make sure all decls associated with an identifier are registered for
4247 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4248 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4249 IDEnd = PP.getIdentifierTable().end();
4250 ID != IDEnd; ++ID) {
4251 const IdentifierInfo *II = ID->second;
4252 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4255 // Sort the identifiers to visit based on their name.
4256 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4257 for (const IdentifierInfo *II : IIs) {
4258 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4259 DEnd = SemaRef.IdResolver.end();
4265 // Form the record of special types.
4266 RecordData SpecialTypes;
4267 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4268 AddTypeRef(Context.getFILEType(), SpecialTypes);
4269 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4270 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4271 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4272 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4273 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4274 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4277 // Write the mapping information describing our module dependencies and how
4278 // each of those modules were mapped into our own offset/ID space, so that
4279 // the reader can build the appropriate mapping to its own offset/ID space.
4280 // The map consists solely of a blob with the following format:
4281 // *(module-name-len:i16 module-name:len*i8
4282 // source-location-offset:i32
4283 // identifier-id:i32
4284 // preprocessed-entity-id:i32
4285 // macro-definition-id:i32
4288 // declaration-id:i32
4289 // c++-base-specifiers-id:i32
4292 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4293 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4294 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4295 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4296 SmallString<2048> Buffer;
4298 llvm::raw_svector_ostream Out(Buffer);
4299 for (ModuleFile *M : Chain->ModuleMgr) {
4300 using namespace llvm::support;
4301 endian::Writer<little> LE(Out);
4302 StringRef FileName = M->FileName;
4303 LE.write<uint16_t>(FileName.size());
4304 Out.write(FileName.data(), FileName.size());
4306 // Note: if a base ID was uint max, it would not be possible to load
4307 // another module after it or have more than one entity inside it.
4308 uint32_t None = std::numeric_limits<uint32_t>::max();
4310 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4311 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4313 LE.write<uint32_t>(BaseID);
4315 LE.write<uint32_t>(None);
4318 // These values should be unique within a chain, since they will be read
4319 // as keys into ContinuousRangeMaps.
4320 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4321 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4322 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4323 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4324 M->NumPreprocessedEntities);
4325 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4326 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4327 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4328 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4332 Record.push_back(MODULE_OFFSET_MAP);
4333 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4334 Buffer.data(), Buffer.size());
4337 RecordData DeclUpdatesOffsetsRecord;
4339 // Keep writing types, declarations, and declaration update records
4340 // until we've emitted all of them.
4341 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4344 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4345 E = DeclsToRewrite.end();
4347 DeclTypesToEmit.push(const_cast<Decl*>(*I));
4349 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4350 while (!DeclTypesToEmit.empty()) {
4351 DeclOrType DOT = DeclTypesToEmit.front();
4352 DeclTypesToEmit.pop();
4354 WriteType(DOT.getType());
4356 WriteDecl(Context, DOT.getDecl());
4358 } while (!DeclUpdates.empty());
4361 DoneWritingDeclsAndTypes = true;
4363 // These things can only be done once we've written out decls and types.
4364 WriteTypeDeclOffsets();
4365 if (!DeclUpdatesOffsetsRecord.empty())
4366 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4367 WriteCXXBaseSpecifiersOffsets();
4368 WriteCXXCtorInitializersOffsets();
4369 WriteFileDeclIDsMap();
4370 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4373 WritePreprocessor(PP, isModule);
4374 WriteHeaderSearch(PP.getHeaderSearchInfo());
4375 WriteSelectors(SemaRef);
4376 WriteReferencedSelectorsPool(SemaRef);
4377 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4378 WriteFPPragmaOptions(SemaRef.getFPOptions());
4379 WriteOpenCLExtensions(SemaRef);
4380 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4382 // If we're emitting a module, write out the submodule information.
4384 WriteSubmodules(WritingModule);
4386 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4388 // Write the record containing external, unnamed definitions.
4389 if (!EagerlyDeserializedDecls.empty())
4390 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4392 // Write the record containing tentative definitions.
4393 if (!TentativeDefinitions.empty())
4394 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4396 // Write the record containing unused file scoped decls.
4397 if (!UnusedFileScopedDecls.empty())
4398 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4400 // Write the record containing weak undeclared identifiers.
4401 if (!WeakUndeclaredIdentifiers.empty())
4402 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4403 WeakUndeclaredIdentifiers);
4405 // Write the record containing ext_vector type names.
4406 if (!ExtVectorDecls.empty())
4407 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4409 // Write the record containing VTable uses information.
4410 if (!VTableUses.empty())
4411 Stream.EmitRecord(VTABLE_USES, VTableUses);
4413 // Write the record containing potentially unused local typedefs.
4414 if (!UnusedLocalTypedefNameCandidates.empty())
4415 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4416 UnusedLocalTypedefNameCandidates);
4418 // Write the record containing pending implicit instantiations.
4419 if (!PendingInstantiations.empty())
4420 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4422 // Write the record containing declaration references of Sema.
4423 if (!SemaDeclRefs.empty())
4424 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4426 // Write the record containing CUDA-specific declaration references.
4427 if (!CUDASpecialDeclRefs.empty())
4428 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4430 // Write the delegating constructors.
4431 if (!DelegatingCtorDecls.empty())
4432 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4434 // Write the known namespaces.
4435 if (!KnownNamespaces.empty())
4436 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4438 // Write the undefined internal functions and variables, and inline functions.
4439 if (!UndefinedButUsed.empty())
4440 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4442 if (!DeleteExprsToAnalyze.empty())
4443 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4445 // Write the visible updates to DeclContexts.
4446 for (auto *DC : UpdatedDeclContexts)
4447 WriteDeclContextVisibleUpdate(DC);
4449 if (!WritingModule) {
4450 // Write the submodules that were imported, if any.
4454 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4456 llvm::SmallVector<ModuleInfo, 64> Imports;
4457 for (const auto *I : Context.local_imports()) {
4458 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4459 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4460 I->getImportedModule()));
4463 if (!Imports.empty()) {
4464 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4467 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4468 return A.ID == B.ID;
4471 // Sort and deduplicate module IDs.
4472 std::sort(Imports.begin(), Imports.end(), Cmp);
4473 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4476 RecordData ImportedModules;
4477 for (const auto &Import : Imports) {
4478 ImportedModules.push_back(Import.ID);
4479 // FIXME: If the module has macros imported then later has declarations
4480 // imported, this location won't be the right one as a location for the
4481 // declaration imports.
4482 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4485 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4489 WriteDeclReplacementsBlock();
4490 WriteRedeclarations();
4491 WriteObjCCategories();
4492 WriteLateParsedTemplates(SemaRef);
4494 WriteOptimizePragmaOptions(SemaRef);
4496 // Some simple statistics
4498 Record.push_back(NumStatements);
4499 Record.push_back(NumMacros);
4500 Record.push_back(NumLexicalDeclContexts);
4501 Record.push_back(NumVisibleDeclContexts);
4502 Stream.EmitRecord(STATISTICS, Record);
4506 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4507 if (DeclUpdates.empty())
4510 DeclUpdateMap LocalUpdates;
4511 LocalUpdates.swap(DeclUpdates);
4513 for (auto &DeclUpdate : LocalUpdates) {
4514 const Decl *D = DeclUpdate.first;
4516 continue; // The decl will be written completely,no need to store updates.
4518 bool HasUpdatedBody = false;
4520 for (auto &Update : DeclUpdate.second) {
4521 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4523 Record.push_back(Kind);
4525 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4526 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4527 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4528 assert(Update.getDecl() && "no decl to add?");
4529 Record.push_back(GetDeclRef(Update.getDecl()));
4532 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4533 // An updated body is emitted last, so that the reader doesn't need
4534 // to skip over the lazy body to reach statements for other records.
4536 HasUpdatedBody = true;
4539 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4540 AddSourceLocation(Update.getLoc(), Record);
4543 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4544 auto *RD = cast<CXXRecordDecl>(D);
4545 UpdatedDeclContexts.insert(RD->getPrimaryContext());
4546 AddCXXDefinitionData(RD, Record);
4547 Record.push_back(WriteDeclContextLexicalBlock(
4548 *Context, const_cast<CXXRecordDecl *>(RD)));
4550 // This state is sometimes updated by template instantiation, when we
4551 // switch from the specialization referring to the template declaration
4552 // to it referring to the template definition.
4553 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4554 Record.push_back(MSInfo->getTemplateSpecializationKind());
4555 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4557 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4558 Record.push_back(Spec->getTemplateSpecializationKind());
4559 AddSourceLocation(Spec->getPointOfInstantiation(), Record);
4561 // The instantiation might have been resolved to a partial
4562 // specialization. If so, record which one.
4563 auto From = Spec->getInstantiatedFrom();
4564 if (auto PartialSpec =
4565 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4566 Record.push_back(true);
4567 AddDeclRef(PartialSpec, Record);
4568 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4571 Record.push_back(false);
4574 Record.push_back(RD->getTagKind());
4575 AddSourceLocation(RD->getLocation(), Record);
4576 AddSourceLocation(RD->getLocStart(), Record);
4577 AddSourceLocation(RD->getRBraceLoc(), Record);
4579 // Instantiation may change attributes; write them all out afresh.
4580 Record.push_back(D->hasAttrs());
4582 WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
4583 D->getAttrs().size()), Record);
4585 // FIXME: Ensure we don't get here for explicit instantiations.
4589 case UPD_CXX_RESOLVED_DTOR_DELETE:
4590 AddDeclRef(Update.getDecl(), Record);
4593 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4596 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4600 case UPD_CXX_DEDUCED_RETURN_TYPE:
4601 Record.push_back(GetOrCreateTypeID(Update.getType()));
4604 case UPD_DECL_MARKED_USED:
4607 case UPD_MANGLING_NUMBER:
4608 case UPD_STATIC_LOCAL_NUMBER:
4609 Record.push_back(Update.getNumber());
4612 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4613 AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
4617 case UPD_DECL_EXPORTED:
4618 Record.push_back(getSubmoduleID(Update.getModule()));
4623 if (HasUpdatedBody) {
4624 const FunctionDecl *Def = cast<FunctionDecl>(D);
4625 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4626 Record.push_back(Def->isInlined());
4627 AddSourceLocation(Def->getInnerLocStart(), Record);
4628 AddFunctionDefinition(Def, Record);
4631 OffsetsRecord.push_back(GetDeclRef(D));
4632 OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4634 Stream.EmitRecord(DECL_UPDATES, Record);
4636 FlushPendingAfterDecl();
4640 void ASTWriter::WriteDeclReplacementsBlock() {
4641 if (ReplacedDecls.empty())
4645 for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4646 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4647 Record.push_back(I->ID);
4648 Record.push_back(I->Offset);
4649 Record.push_back(I->Loc);
4651 Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4654 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4655 Record.push_back(Loc.getRawEncoding());
4658 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4659 AddSourceLocation(Range.getBegin(), Record);
4660 AddSourceLocation(Range.getEnd(), Record);
4663 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4664 Record.push_back(Value.getBitWidth());
4665 const uint64_t *Words = Value.getRawData();
4666 Record.append(Words, Words + Value.getNumWords());
4669 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4670 Record.push_back(Value.isUnsigned());
4671 AddAPInt(Value, Record);
4674 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4675 AddAPInt(Value.bitcastToAPInt(), Record);
4678 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4679 Record.push_back(getIdentifierRef(II));
4682 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4686 IdentID &ID = IdentifierIDs[II];
4692 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4693 // Don't emit builtin macros like __LINE__ to the AST file unless they
4694 // have been redefined by the header (in which case they are not
4696 if (!MI || MI->isBuiltinMacro())
4699 MacroID &ID = MacroIDs[MI];
4702 MacroInfoToEmitData Info = { Name, MI, ID };
4703 MacroInfosToEmit.push_back(Info);
4708 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4709 if (!MI || MI->isBuiltinMacro())
4712 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4713 return MacroIDs[MI];
4716 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4717 return IdentMacroDirectivesOffsetMap.lookup(Name);
4720 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4721 Record.push_back(getSelectorRef(SelRef));
4724 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4725 if (Sel.getAsOpaquePtr() == nullptr) {
4729 SelectorID SID = SelectorIDs[Sel];
4730 if (SID == 0 && Chain) {
4731 // This might trigger a ReadSelector callback, which will set the ID for
4733 Chain->LoadSelector(Sel);
4734 SID = SelectorIDs[Sel];
4737 SID = NextSelectorID++;
4738 SelectorIDs[Sel] = SID;
4743 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4744 AddDeclRef(Temp->getDestructor(), Record);
4747 void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4748 RecordDataImpl &Record) {
4749 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4750 CXXCtorInitializersToWrite.push_back(
4751 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4752 Record.push_back(NextCXXCtorInitializersID++);
4755 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4756 CXXBaseSpecifier const *BasesEnd,
4757 RecordDataImpl &Record) {
4758 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4759 CXXBaseSpecifiersToWrite.push_back(
4760 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4762 Record.push_back(NextCXXBaseSpecifiersID++);
4765 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4766 const TemplateArgumentLocInfo &Arg,
4767 RecordDataImpl &Record) {
4769 case TemplateArgument::Expression:
4770 AddStmt(Arg.getAsExpr());
4772 case TemplateArgument::Type:
4773 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4775 case TemplateArgument::Template:
4776 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4777 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4779 case TemplateArgument::TemplateExpansion:
4780 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4781 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4782 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4784 case TemplateArgument::Null:
4785 case TemplateArgument::Integral:
4786 case TemplateArgument::Declaration:
4787 case TemplateArgument::NullPtr:
4788 case TemplateArgument::Pack:
4789 // FIXME: Is this right?
4794 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4795 RecordDataImpl &Record) {
4796 AddTemplateArgument(Arg.getArgument(), Record);
4798 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4799 bool InfoHasSameExpr
4800 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4801 Record.push_back(InfoHasSameExpr);
4802 if (InfoHasSameExpr)
4803 return; // Avoid storing the same expr twice.
4805 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4809 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4810 RecordDataImpl &Record) {
4812 AddTypeRef(QualType(), Record);
4816 AddTypeLoc(TInfo->getTypeLoc(), Record);
4819 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4820 AddTypeRef(TL.getType(), Record);
4822 TypeLocWriter TLW(*this, Record);
4823 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4827 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4828 Record.push_back(GetOrCreateTypeID(T));
4831 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
4833 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4836 assert(!T.getLocalFastQualifiers());
4838 TypeIdx &Idx = TypeIdxs[T];
4839 if (Idx.getIndex() == 0) {
4840 if (DoneWritingDeclsAndTypes) {
4841 assert(0 && "New type seen after serializing all the types to emit!");
4845 // We haven't seen this type before. Assign it a new ID and put it
4846 // into the queue of types to emit.
4847 Idx = TypeIdx(NextTypeID++);
4848 DeclTypesToEmit.push(T);
4854 TypeID ASTWriter::getTypeID(QualType T) const {
4856 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4859 assert(!T.getLocalFastQualifiers());
4861 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4862 assert(I != TypeIdxs.end() && "Type not emitted!");
4867 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4868 Record.push_back(GetDeclRef(D));
4871 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4872 assert(WritingAST && "Cannot request a declaration ID before AST writing");
4878 // If D comes from an AST file, its declaration ID is already known and
4880 if (D->isFromASTFile())
4881 return D->getGlobalID();
4883 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4884 DeclID &ID = DeclIDs[D];
4886 if (DoneWritingDeclsAndTypes) {
4887 assert(0 && "New decl seen after serializing all the decls to emit!");
4891 // We haven't seen this declaration before. Give it a new ID and
4892 // enqueue it in the list of declarations to emit.
4894 DeclTypesToEmit.push(const_cast<Decl *>(D));
4900 DeclID ASTWriter::getDeclID(const Decl *D) {
4904 // If D comes from an AST file, its declaration ID is already known and
4906 if (D->isFromASTFile())
4907 return D->getGlobalID();
4909 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4913 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
4917 SourceLocation Loc = D->getLocation();
4918 if (Loc.isInvalid())
4921 // We only keep track of the file-level declarations of each file.
4922 if (!D->getLexicalDeclContext()->isFileContext())
4924 // FIXME: ParmVarDecls that are part of a function type of a parameter of
4925 // a function/objc method, should not have TU as lexical context.
4926 if (isa<ParmVarDecl>(D))
4929 SourceManager &SM = Context->getSourceManager();
4930 SourceLocation FileLoc = SM.getFileLoc(Loc);
4931 assert(SM.isLocalSourceLocation(FileLoc));
4934 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
4935 if (FID.isInvalid())
4937 assert(SM.getSLocEntry(FID).isFile());
4939 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
4941 Info = new DeclIDInFileInfo();
4943 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
4944 LocDeclIDsTy &Decls = Info->DeclIDs;
4946 if (Decls.empty() || Decls.back().first <= Offset) {
4947 Decls.push_back(LocDecl);
4951 LocDeclIDsTy::iterator I =
4952 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
4954 Decls.insert(I, LocDecl);
4957 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
4958 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
4959 Record.push_back(Name.getNameKind());
4960 switch (Name.getNameKind()) {
4961 case DeclarationName::Identifier:
4962 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4965 case DeclarationName::ObjCZeroArgSelector:
4966 case DeclarationName::ObjCOneArgSelector:
4967 case DeclarationName::ObjCMultiArgSelector:
4968 AddSelectorRef(Name.getObjCSelector(), Record);
4971 case DeclarationName::CXXConstructorName:
4972 case DeclarationName::CXXDestructorName:
4973 case DeclarationName::CXXConversionFunctionName:
4974 AddTypeRef(Name.getCXXNameType(), Record);
4977 case DeclarationName::CXXOperatorName:
4978 Record.push_back(Name.getCXXOverloadedOperator());
4981 case DeclarationName::CXXLiteralOperatorName:
4982 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4985 case DeclarationName::CXXUsingDirective:
4986 // No extra data to emit
4991 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
4992 assert(needsAnonymousDeclarationNumber(D) &&
4993 "expected an anonymous declaration");
4995 // Number the anonymous declarations within this context, if we've not
4997 auto It = AnonymousDeclarationNumbers.find(D);
4998 if (It == AnonymousDeclarationNumbers.end()) {
4999 auto *DC = D->getLexicalDeclContext();
5000 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5001 AnonymousDeclarationNumbers[ND] = Number;
5004 It = AnonymousDeclarationNumbers.find(D);
5005 assert(It != AnonymousDeclarationNumbers.end() &&
5006 "declaration not found within its lexical context");
5012 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5013 DeclarationName Name, RecordDataImpl &Record) {
5014 switch (Name.getNameKind()) {
5015 case DeclarationName::CXXConstructorName:
5016 case DeclarationName::CXXDestructorName:
5017 case DeclarationName::CXXConversionFunctionName:
5018 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5021 case DeclarationName::CXXOperatorName:
5023 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5026 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5030 case DeclarationName::CXXLiteralOperatorName:
5032 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5036 case DeclarationName::Identifier:
5037 case DeclarationName::ObjCZeroArgSelector:
5038 case DeclarationName::ObjCOneArgSelector:
5039 case DeclarationName::ObjCMultiArgSelector:
5040 case DeclarationName::CXXUsingDirective:
5045 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5046 RecordDataImpl &Record) {
5047 AddDeclarationName(NameInfo.getName(), Record);
5048 AddSourceLocation(NameInfo.getLoc(), Record);
5049 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5052 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
5053 RecordDataImpl &Record) {
5054 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
5055 Record.push_back(Info.NumTemplParamLists);
5056 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5057 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5060 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
5061 RecordDataImpl &Record) {
5062 // Nested name specifiers usually aren't too long. I think that 8 would
5063 // typically accommodate the vast majority.
5064 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5066 // Push each of the NNS's onto a stack for serialization in reverse order.
5068 NestedNames.push_back(NNS);
5069 NNS = NNS->getPrefix();
5072 Record.push_back(NestedNames.size());
5073 while(!NestedNames.empty()) {
5074 NNS = NestedNames.pop_back_val();
5075 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5076 Record.push_back(Kind);
5078 case NestedNameSpecifier::Identifier:
5079 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5082 case NestedNameSpecifier::Namespace:
5083 AddDeclRef(NNS->getAsNamespace(), Record);
5086 case NestedNameSpecifier::NamespaceAlias:
5087 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5090 case NestedNameSpecifier::TypeSpec:
5091 case NestedNameSpecifier::TypeSpecWithTemplate:
5092 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5093 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5096 case NestedNameSpecifier::Global:
5097 // Don't need to write an associated value.
5100 case NestedNameSpecifier::Super:
5101 AddDeclRef(NNS->getAsRecordDecl(), Record);
5107 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5108 RecordDataImpl &Record) {
5109 // Nested name specifiers usually aren't too long. I think that 8 would
5110 // typically accommodate the vast majority.
5111 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5113 // Push each of the nested-name-specifiers's onto a stack for
5114 // serialization in reverse order.
5116 NestedNames.push_back(NNS);
5117 NNS = NNS.getPrefix();
5120 Record.push_back(NestedNames.size());
5121 while(!NestedNames.empty()) {
5122 NNS = NestedNames.pop_back_val();
5123 NestedNameSpecifier::SpecifierKind Kind
5124 = NNS.getNestedNameSpecifier()->getKind();
5125 Record.push_back(Kind);
5127 case NestedNameSpecifier::Identifier:
5128 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5129 AddSourceRange(NNS.getLocalSourceRange(), Record);
5132 case NestedNameSpecifier::Namespace:
5133 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5134 AddSourceRange(NNS.getLocalSourceRange(), Record);
5137 case NestedNameSpecifier::NamespaceAlias:
5138 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5139 AddSourceRange(NNS.getLocalSourceRange(), Record);
5142 case NestedNameSpecifier::TypeSpec:
5143 case NestedNameSpecifier::TypeSpecWithTemplate:
5144 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5145 AddTypeLoc(NNS.getTypeLoc(), Record);
5146 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5149 case NestedNameSpecifier::Global:
5150 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5153 case NestedNameSpecifier::Super:
5154 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
5155 AddSourceRange(NNS.getLocalSourceRange(), Record);
5161 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
5162 TemplateName::NameKind Kind = Name.getKind();
5163 Record.push_back(Kind);
5165 case TemplateName::Template:
5166 AddDeclRef(Name.getAsTemplateDecl(), Record);
5169 case TemplateName::OverloadedTemplate: {
5170 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5171 Record.push_back(OvT->size());
5172 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
5174 AddDeclRef(*I, Record);
5178 case TemplateName::QualifiedTemplate: {
5179 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5180 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5181 Record.push_back(QualT->hasTemplateKeyword());
5182 AddDeclRef(QualT->getTemplateDecl(), Record);
5186 case TemplateName::DependentTemplate: {
5187 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5188 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5189 Record.push_back(DepT->isIdentifier());
5190 if (DepT->isIdentifier())
5191 AddIdentifierRef(DepT->getIdentifier(), Record);
5193 Record.push_back(DepT->getOperator());
5197 case TemplateName::SubstTemplateTemplateParm: {
5198 SubstTemplateTemplateParmStorage *subst
5199 = Name.getAsSubstTemplateTemplateParm();
5200 AddDeclRef(subst->getParameter(), Record);
5201 AddTemplateName(subst->getReplacement(), Record);
5205 case TemplateName::SubstTemplateTemplateParmPack: {
5206 SubstTemplateTemplateParmPackStorage *SubstPack
5207 = Name.getAsSubstTemplateTemplateParmPack();
5208 AddDeclRef(SubstPack->getParameterPack(), Record);
5209 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5215 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
5216 RecordDataImpl &Record) {
5217 Record.push_back(Arg.getKind());
5218 switch (Arg.getKind()) {
5219 case TemplateArgument::Null:
5221 case TemplateArgument::Type:
5222 AddTypeRef(Arg.getAsType(), Record);
5224 case TemplateArgument::Declaration:
5225 AddDeclRef(Arg.getAsDecl(), Record);
5226 AddTypeRef(Arg.getParamTypeForDecl(), Record);
5228 case TemplateArgument::NullPtr:
5229 AddTypeRef(Arg.getNullPtrType(), Record);
5231 case TemplateArgument::Integral:
5232 AddAPSInt(Arg.getAsIntegral(), Record);
5233 AddTypeRef(Arg.getIntegralType(), Record);
5235 case TemplateArgument::Template:
5236 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5238 case TemplateArgument::TemplateExpansion:
5239 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5240 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5241 Record.push_back(*NumExpansions + 1);
5243 Record.push_back(0);
5245 case TemplateArgument::Expression:
5246 AddStmt(Arg.getAsExpr());
5248 case TemplateArgument::Pack:
5249 Record.push_back(Arg.pack_size());
5250 for (const auto &P : Arg.pack_elements())
5251 AddTemplateArgument(P, Record);
5257 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
5258 RecordDataImpl &Record) {
5259 assert(TemplateParams && "No TemplateParams!");
5260 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5261 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5262 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5263 Record.push_back(TemplateParams->size());
5264 for (TemplateParameterList::const_iterator
5265 P = TemplateParams->begin(), PEnd = TemplateParams->end();
5267 AddDeclRef(*P, Record);
5270 /// \brief Emit a template argument list.
5272 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
5273 RecordDataImpl &Record) {
5274 assert(TemplateArgs && "No TemplateArgs!");
5275 Record.push_back(TemplateArgs->size());
5276 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5277 AddTemplateArgument(TemplateArgs->get(i), Record);
5281 ASTWriter::AddASTTemplateArgumentListInfo
5282 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5283 assert(ASTTemplArgList && "No ASTTemplArgList!");
5284 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5285 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5286 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5287 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5288 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5289 AddTemplateArgumentLoc(TemplArgs[i], Record);
5293 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
5294 Record.push_back(Set.size());
5295 for (ASTUnresolvedSet::const_iterator
5296 I = Set.begin(), E = Set.end(); I != E; ++I) {
5297 AddDeclRef(I.getDecl(), Record);
5298 Record.push_back(I.getAccess());
5302 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
5303 RecordDataImpl &Record) {
5304 Record.push_back(Base.isVirtual());
5305 Record.push_back(Base.isBaseOfClass());
5306 Record.push_back(Base.getAccessSpecifierAsWritten());
5307 Record.push_back(Base.getInheritConstructors());
5308 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
5309 AddSourceRange(Base.getSourceRange(), Record);
5310 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5315 void ASTWriter::FlushCXXBaseSpecifiers() {
5317 unsigned N = CXXBaseSpecifiersToWrite.size();
5318 for (unsigned I = 0; I != N; ++I) {
5321 // Record the offset of this base-specifier set.
5322 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5323 if (Index == CXXBaseSpecifiersOffsets.size())
5324 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5326 if (Index > CXXBaseSpecifiersOffsets.size())
5327 CXXBaseSpecifiersOffsets.resize(Index + 1);
5328 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5331 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5332 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5333 Record.push_back(BEnd - B);
5334 for (; B != BEnd; ++B)
5335 AddCXXBaseSpecifier(*B, Record);
5336 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5338 // Flush any expressions that were written as part of the base specifiers.
5342 assert(N == CXXBaseSpecifiersToWrite.size() &&
5343 "added more base specifiers while writing base specifiers");
5344 CXXBaseSpecifiersToWrite.clear();
5347 void ASTWriter::AddCXXCtorInitializers(
5348 const CXXCtorInitializer * const *CtorInitializers,
5349 unsigned NumCtorInitializers,
5350 RecordDataImpl &Record) {
5351 Record.push_back(NumCtorInitializers);
5352 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5353 const CXXCtorInitializer *Init = CtorInitializers[i];
5355 if (Init->isBaseInitializer()) {
5356 Record.push_back(CTOR_INITIALIZER_BASE);
5357 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5358 Record.push_back(Init->isBaseVirtual());
5359 } else if (Init->isDelegatingInitializer()) {
5360 Record.push_back(CTOR_INITIALIZER_DELEGATING);
5361 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5362 } else if (Init->isMemberInitializer()){
5363 Record.push_back(CTOR_INITIALIZER_MEMBER);
5364 AddDeclRef(Init->getMember(), Record);
5366 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5367 AddDeclRef(Init->getIndirectMember(), Record);
5370 AddSourceLocation(Init->getMemberLocation(), Record);
5371 AddStmt(Init->getInit());
5372 AddSourceLocation(Init->getLParenLoc(), Record);
5373 AddSourceLocation(Init->getRParenLoc(), Record);
5374 Record.push_back(Init->isWritten());
5375 if (Init->isWritten()) {
5376 Record.push_back(Init->getSourceOrder());
5378 Record.push_back(Init->getNumArrayIndices());
5379 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5380 AddDeclRef(Init->getArrayIndex(i), Record);
5385 void ASTWriter::FlushCXXCtorInitializers() {
5388 unsigned N = CXXCtorInitializersToWrite.size();
5389 (void)N; // Silence unused warning in non-assert builds.
5390 for (auto &Init : CXXCtorInitializersToWrite) {
5393 // Record the offset of this mem-initializer list.
5394 unsigned Index = Init.ID - 1;
5395 if (Index == CXXCtorInitializersOffsets.size())
5396 CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5398 if (Index > CXXCtorInitializersOffsets.size())
5399 CXXCtorInitializersOffsets.resize(Index + 1);
5400 CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5403 AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5404 Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5406 // Flush any expressions that were written as part of the initializers.
5410 assert(N == CXXCtorInitializersToWrite.size() &&
5411 "added more ctor initializers while writing ctor initializers");
5412 CXXCtorInitializersToWrite.clear();
5415 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
5416 auto &Data = D->data();
5417 Record.push_back(Data.IsLambda);
5418 Record.push_back(Data.UserDeclaredConstructor);
5419 Record.push_back(Data.UserDeclaredSpecialMembers);
5420 Record.push_back(Data.Aggregate);
5421 Record.push_back(Data.PlainOldData);
5422 Record.push_back(Data.Empty);
5423 Record.push_back(Data.Polymorphic);
5424 Record.push_back(Data.Abstract);
5425 Record.push_back(Data.IsStandardLayout);
5426 Record.push_back(Data.HasNoNonEmptyBases);
5427 Record.push_back(Data.HasPrivateFields);
5428 Record.push_back(Data.HasProtectedFields);
5429 Record.push_back(Data.HasPublicFields);
5430 Record.push_back(Data.HasMutableFields);
5431 Record.push_back(Data.HasVariantMembers);
5432 Record.push_back(Data.HasOnlyCMembers);
5433 Record.push_back(Data.HasInClassInitializer);
5434 Record.push_back(Data.HasUninitializedReferenceMember);
5435 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5436 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5437 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5438 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5439 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5440 Record.push_back(Data.DefaultedDestructorIsDeleted);
5441 Record.push_back(Data.HasTrivialSpecialMembers);
5442 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
5443 Record.push_back(Data.HasIrrelevantDestructor);
5444 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5445 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5446 Record.push_back(Data.HasConstexprDefaultConstructor);
5447 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5448 Record.push_back(Data.ComputedVisibleConversions);
5449 Record.push_back(Data.UserProvidedDefaultConstructor);
5450 Record.push_back(Data.DeclaredSpecialMembers);
5451 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5452 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5453 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5454 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5455 // IsLambda bit is already saved.
5457 Record.push_back(Data.NumBases);
5458 if (Data.NumBases > 0)
5459 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5462 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5463 Record.push_back(Data.NumVBases);
5464 if (Data.NumVBases > 0)
5465 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5468 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5469 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5470 // Data.Definition is the owning decl, no need to write it.
5471 AddDeclRef(D->getFirstFriend(), Record);
5473 // Add lambda-specific data.
5474 if (Data.IsLambda) {
5475 auto &Lambda = D->getLambdaData();
5476 Record.push_back(Lambda.Dependent);
5477 Record.push_back(Lambda.IsGenericLambda);
5478 Record.push_back(Lambda.CaptureDefault);
5479 Record.push_back(Lambda.NumCaptures);
5480 Record.push_back(Lambda.NumExplicitCaptures);
5481 Record.push_back(Lambda.ManglingNumber);
5482 AddDeclRef(Lambda.ContextDecl, Record);
5483 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5484 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5485 const LambdaCapture &Capture = Lambda.Captures[I];
5486 AddSourceLocation(Capture.getLocation(), Record);
5487 Record.push_back(Capture.isImplicit());
5488 Record.push_back(Capture.getCaptureKind());
5489 switch (Capture.getCaptureKind()) {
5496 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5497 AddDeclRef(Var, Record);
5498 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5507 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5508 assert(Reader && "Cannot remove chain");
5509 assert((!Chain || Chain == Reader) && "Cannot replace chain");
5510 assert(FirstDeclID == NextDeclID &&
5511 FirstTypeID == NextTypeID &&
5512 FirstIdentID == NextIdentID &&
5513 FirstMacroID == NextMacroID &&
5514 FirstSubmoduleID == NextSubmoduleID &&
5515 FirstSelectorID == NextSelectorID &&
5516 "Setting chain after writing has started.");
5520 // Note, this will get called multiple times, once one the reader starts up
5521 // and again each time it's done reading a PCH or module.
5522 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5523 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5524 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5525 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5526 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5527 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5528 NextDeclID = FirstDeclID;
5529 NextTypeID = FirstTypeID;
5530 NextIdentID = FirstIdentID;
5531 NextMacroID = FirstMacroID;
5532 NextSelectorID = FirstSelectorID;
5533 NextSubmoduleID = FirstSubmoduleID;
5536 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5537 // Always keep the highest ID. See \p TypeRead() for more information.
5538 IdentID &StoredID = IdentifierIDs[II];
5543 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5544 // Always keep the highest ID. See \p TypeRead() for more information.
5545 MacroID &StoredID = MacroIDs[MI];
5550 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5551 // Always take the highest-numbered type index. This copes with an interesting
5552 // case for chained AST writing where we schedule writing the type and then,
5553 // later, deserialize the type from another AST. In this case, we want to
5554 // keep the higher-numbered entry so that we can properly write it out to
5556 TypeIdx &StoredIdx = TypeIdxs[T];
5557 if (Idx.getIndex() >= StoredIdx.getIndex())
5561 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5562 // Always keep the highest ID. See \p TypeRead() for more information.
5563 SelectorID &StoredID = SelectorIDs[S];
5568 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5569 MacroDefinitionRecord *MD) {
5570 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5571 MacroDefinitions[MD] = ID;
5574 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5575 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5576 SubmoduleIDs[Mod] = ID;
5579 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5580 assert(D->isCompleteDefinition());
5581 assert(!WritingAST && "Already writing the AST!");
5582 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5583 // We are interested when a PCH decl is modified.
5584 if (RD->isFromASTFile()) {
5585 // A forward reference was mutated into a definition. Rewrite it.
5586 // FIXME: This happens during template instantiation, should we
5587 // have created a new definition decl instead ?
5588 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5589 "completed a tag from another module but not by instantiation?");
5590 DeclUpdates[RD].push_back(
5591 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5596 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5597 // TU and namespaces are handled elsewhere.
5598 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5601 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5602 return; // Not a source decl added to a DeclContext from PCH.
5604 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5605 assert(!WritingAST && "Already writing the AST!");
5606 UpdatedDeclContexts.insert(DC);
5607 UpdatingVisibleDecls.push_back(D);
5610 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5611 assert(D->isImplicit());
5612 if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5613 return; // Not a source member added to a class from PCH.
5614 if (!isa<CXXMethodDecl>(D))
5615 return; // We are interested in lazily declared implicit methods.
5617 // A decl coming from PCH was modified.
5618 assert(RD->isCompleteDefinition());
5619 assert(!WritingAST && "Already writing the AST!");
5620 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5623 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5624 const ClassTemplateSpecializationDecl *D) {
5625 // The specializations set is kept in the canonical template.
5626 TD = TD->getCanonicalDecl();
5627 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5628 return; // Not a source specialization added to a template from PCH.
5630 assert(!WritingAST && "Already writing the AST!");
5631 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5635 void ASTWriter::AddedCXXTemplateSpecialization(
5636 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5637 // The specializations set is kept in the canonical template.
5638 TD = TD->getCanonicalDecl();
5639 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5640 return; // Not a source specialization added to a template from PCH.
5642 assert(!WritingAST && "Already writing the AST!");
5643 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5647 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5648 const FunctionDecl *D) {
5649 // The specializations set is kept in the canonical template.
5650 TD = TD->getCanonicalDecl();
5651 if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5652 return; // Not a source specialization added to a template from PCH.
5654 assert(!WritingAST && "Already writing the AST!");
5655 DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5659 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5660 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5662 Chain->forEachFormerlyCanonicalImportedDecl(FD, [&](const Decl *D) {
5663 // If we don't already know the exception specification for this redecl
5664 // chain, add an update record for it.
5665 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5667 ->castAs<FunctionProtoType>()
5668 ->getExceptionSpecType()))
5669 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5673 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5674 assert(!WritingAST && "Already writing the AST!");
5676 Chain->forEachFormerlyCanonicalImportedDecl(FD, [&](const Decl *D) {
5677 DeclUpdates[D].push_back(
5678 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5682 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5683 const FunctionDecl *Delete) {
5684 assert(!WritingAST && "Already writing the AST!");
5685 assert(Delete && "Not given an operator delete");
5687 Chain->forEachFormerlyCanonicalImportedDecl(DD, [&](const Decl *D) {
5688 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5692 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5693 assert(!WritingAST && "Already writing the AST!");
5694 if (!D->isFromASTFile())
5695 return; // Declaration not imported from PCH.
5697 // Implicit function decl from a PCH was defined.
5698 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5701 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5702 assert(!WritingAST && "Already writing the AST!");
5703 if (!D->isFromASTFile())
5706 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5709 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5710 assert(!WritingAST && "Already writing the AST!");
5711 if (!D->isFromASTFile())
5714 // Since the actual instantiation is delayed, this really means that we need
5715 // to update the instantiation location.
5716 DeclUpdates[D].push_back(
5717 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5718 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5721 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5722 const ObjCInterfaceDecl *IFD) {
5723 assert(!WritingAST && "Already writing the AST!");
5724 if (!IFD->isFromASTFile())
5725 return; // Declaration not imported from PCH.
5727 assert(IFD->getDefinition() && "Category on a class without a definition?");
5728 ObjCClassesWithCategories.insert(
5729 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5733 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5734 const ObjCPropertyDecl *OrigProp,
5735 const ObjCCategoryDecl *ClassExt) {
5736 const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5740 assert(!WritingAST && "Already writing the AST!");
5741 if (!D->isFromASTFile())
5742 return; // Declaration not imported from PCH.
5747 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5748 assert(!WritingAST && "Already writing the AST!");
5749 if (!D->isFromASTFile())
5752 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5755 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5756 assert(!WritingAST && "Already writing the AST!");
5757 if (!D->isFromASTFile())
5760 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5763 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5764 assert(!WritingAST && "Already writing the AST!");
5765 assert(D->isHidden() && "expected a hidden declaration");
5766 if (!D->isFromASTFile())
5769 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));