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 "ASTReaderInternals.h"
17 #include "MultiOnDiskHashTable.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclContextInternals.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclarationName.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/LambdaCapture.h"
32 #include "clang/AST/NestedNameSpecifier.h"
33 #include "clang/AST/RawCommentList.h"
34 #include "clang/AST/TemplateName.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLocVisitor.h"
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/DiagnosticOptions.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/FileSystemOptions.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/MemoryBufferCache.h"
46 #include "clang/Basic/Module.h"
47 #include "clang/Basic/ObjCRuntime.h"
48 #include "clang/Basic/OpenCLOptions.h"
49 #include "clang/Basic/SourceLocation.h"
50 #include "clang/Basic/SourceManager.h"
51 #include "clang/Basic/SourceManagerInternals.h"
52 #include "clang/Basic/Specifiers.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TargetOptions.h"
55 #include "clang/Basic/Version.h"
56 #include "clang/Basic/VersionTuple.h"
57 #include "clang/Lex/HeaderSearch.h"
58 #include "clang/Lex/HeaderSearchOptions.h"
59 #include "clang/Lex/MacroInfo.h"
60 #include "clang/Lex/ModuleMap.h"
61 #include "clang/Lex/PreprocessingRecord.h"
62 #include "clang/Lex/Preprocessor.h"
63 #include "clang/Lex/PreprocessorOptions.h"
64 #include "clang/Lex/Token.h"
65 #include "clang/Sema/IdentifierResolver.h"
66 #include "clang/Sema/ObjCMethodList.h"
67 #include "clang/Sema/Sema.h"
68 #include "clang/Sema/Weak.h"
69 #include "clang/Serialization/ASTReader.h"
70 #include "clang/Serialization/Module.h"
71 #include "clang/Serialization/ModuleFileExtension.h"
72 #include "clang/Serialization/SerializationDiagnostic.h"
73 #include "llvm/ADT/APFloat.h"
74 #include "llvm/ADT/APInt.h"
75 #include "llvm/ADT/APSInt.h"
76 #include "llvm/ADT/ArrayRef.h"
77 #include "llvm/ADT/DenseMap.h"
78 #include "llvm/ADT/Hashing.h"
79 #include "llvm/ADT/Optional.h"
80 #include "llvm/ADT/PointerIntPair.h"
81 #include "llvm/ADT/STLExtras.h"
82 #include "llvm/ADT/SmallSet.h"
83 #include "llvm/ADT/SmallString.h"
84 #include "llvm/ADT/SmallVector.h"
85 #include "llvm/ADT/StringExtras.h"
86 #include "llvm/ADT/StringMap.h"
87 #include "llvm/ADT/StringRef.h"
88 #include "llvm/Bitcode/BitCodes.h"
89 #include "llvm/Bitcode/BitstreamWriter.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/Compression.h"
92 #include "llvm/Support/Endian.h"
93 #include "llvm/Support/EndianStream.h"
94 #include "llvm/Support/Error.h"
95 #include "llvm/Support/ErrorHandling.h"
96 #include "llvm/Support/MemoryBuffer.h"
97 #include "llvm/Support/OnDiskHashTable.h"
98 #include "llvm/Support/Path.h"
99 #include "llvm/Support/SHA1.h"
100 #include "llvm/Support/raw_ostream.h"
115 using namespace clang;
116 using namespace clang::serialization;
118 template <typename T, typename Allocator>
119 static StringRef bytes(const std::vector<T, Allocator> &v) {
120 if (v.empty()) return StringRef();
121 return StringRef(reinterpret_cast<const char*>(&v[0]),
122 sizeof(T) * v.size());
125 template <typename T>
126 static StringRef bytes(const SmallVectorImpl<T> &v) {
127 return StringRef(reinterpret_cast<const char*>(v.data()),
128 sizeof(T) * v.size());
131 //===----------------------------------------------------------------------===//
132 // Type serialization
133 //===----------------------------------------------------------------------===//
137 class ASTTypeWriter {
139 ASTRecordWriter Record;
141 /// \brief Type code that corresponds to the record generated.
142 TypeCode Code = static_cast<TypeCode>(0);
144 /// \brief Abbreviation to use for the record, if any.
145 unsigned AbbrevToUse = 0;
148 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
149 : Writer(Writer), Record(Writer, Record) {}
152 return Record.Emit(Code, AbbrevToUse);
155 void Visit(QualType T) {
156 if (T.hasLocalNonFastQualifiers()) {
157 Qualifiers Qs = T.getLocalQualifiers();
158 Record.AddTypeRef(T.getLocalUnqualifiedType());
159 Record.push_back(Qs.getAsOpaqueValue());
160 Code = TYPE_EXT_QUAL;
161 AbbrevToUse = Writer.TypeExtQualAbbrev;
163 switch (T->getTypeClass()) {
164 // For all of the concrete, non-dependent types, call the
165 // appropriate visitor function.
166 #define TYPE(Class, Base) \
167 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
168 #define ABSTRACT_TYPE(Class, Base)
169 #include "clang/AST/TypeNodes.def"
174 void VisitArrayType(const ArrayType *T);
175 void VisitFunctionType(const FunctionType *T);
176 void VisitTagType(const TagType *T);
178 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
179 #define ABSTRACT_TYPE(Class, Base)
180 #include "clang/AST/TypeNodes.def"
185 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
186 llvm_unreachable("Built-in types are never serialized");
189 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
190 Record.AddTypeRef(T->getElementType());
194 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
195 Record.AddTypeRef(T->getPointeeType());
199 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
200 Record.AddTypeRef(T->getOriginalType());
204 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
205 Record.AddTypeRef(T->getOriginalType());
206 Record.AddTypeRef(T->getAdjustedType());
207 Code = TYPE_ADJUSTED;
210 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
211 Record.AddTypeRef(T->getPointeeType());
212 Code = TYPE_BLOCK_POINTER;
215 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
216 Record.AddTypeRef(T->getPointeeTypeAsWritten());
217 Record.push_back(T->isSpelledAsLValue());
218 Code = TYPE_LVALUE_REFERENCE;
221 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
222 Record.AddTypeRef(T->getPointeeTypeAsWritten());
223 Code = TYPE_RVALUE_REFERENCE;
226 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
227 Record.AddTypeRef(T->getPointeeType());
228 Record.AddTypeRef(QualType(T->getClass(), 0));
229 Code = TYPE_MEMBER_POINTER;
232 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
233 Record.AddTypeRef(T->getElementType());
234 Record.push_back(T->getSizeModifier()); // FIXME: stable values
235 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
238 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
240 Record.AddAPInt(T->getSize());
241 Code = TYPE_CONSTANT_ARRAY;
244 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
246 Code = TYPE_INCOMPLETE_ARRAY;
249 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
251 Record.AddSourceLocation(T->getLBracketLoc());
252 Record.AddSourceLocation(T->getRBracketLoc());
253 Record.AddStmt(T->getSizeExpr());
254 Code = TYPE_VARIABLE_ARRAY;
257 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
258 Record.AddTypeRef(T->getElementType());
259 Record.push_back(T->getNumElements());
260 Record.push_back(T->getVectorKind());
264 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
266 Code = TYPE_EXT_VECTOR;
269 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
270 Record.AddTypeRef(T->getReturnType());
271 FunctionType::ExtInfo C = T->getExtInfo();
272 Record.push_back(C.getNoReturn());
273 Record.push_back(C.getHasRegParm());
274 Record.push_back(C.getRegParm());
275 // FIXME: need to stabilize encoding of calling convention...
276 Record.push_back(C.getCC());
277 Record.push_back(C.getProducesResult());
278 Record.push_back(C.getNoCallerSavedRegs());
280 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
284 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
285 VisitFunctionType(T);
286 Code = TYPE_FUNCTION_NO_PROTO;
289 static void addExceptionSpec(const FunctionProtoType *T,
290 ASTRecordWriter &Record) {
291 Record.push_back(T->getExceptionSpecType());
292 if (T->getExceptionSpecType() == EST_Dynamic) {
293 Record.push_back(T->getNumExceptions());
294 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
295 Record.AddTypeRef(T->getExceptionType(I));
296 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
297 Record.AddStmt(T->getNoexceptExpr());
298 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
299 Record.AddDeclRef(T->getExceptionSpecDecl());
300 Record.AddDeclRef(T->getExceptionSpecTemplate());
301 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
302 Record.AddDeclRef(T->getExceptionSpecDecl());
306 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
307 VisitFunctionType(T);
309 Record.push_back(T->isVariadic());
310 Record.push_back(T->hasTrailingReturn());
311 Record.push_back(T->getTypeQuals());
312 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
313 addExceptionSpec(T, Record);
315 Record.push_back(T->getNumParams());
316 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
317 Record.AddTypeRef(T->getParamType(I));
319 if (T->hasExtParameterInfos()) {
320 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
321 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
324 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
325 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
326 T->hasExtParameterInfos())
329 Code = TYPE_FUNCTION_PROTO;
332 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
333 Record.AddDeclRef(T->getDecl());
334 Code = TYPE_UNRESOLVED_USING;
337 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
338 Record.AddDeclRef(T->getDecl());
339 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
340 Record.AddTypeRef(T->getCanonicalTypeInternal());
344 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
345 Record.AddStmt(T->getUnderlyingExpr());
346 Code = TYPE_TYPEOF_EXPR;
349 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
350 Record.AddTypeRef(T->getUnderlyingType());
354 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
355 Record.AddTypeRef(T->getUnderlyingType());
356 Record.AddStmt(T->getUnderlyingExpr());
357 Code = TYPE_DECLTYPE;
360 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
361 Record.AddTypeRef(T->getBaseType());
362 Record.AddTypeRef(T->getUnderlyingType());
363 Record.push_back(T->getUTTKind());
364 Code = TYPE_UNARY_TRANSFORM;
367 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
368 Record.AddTypeRef(T->getDeducedType());
369 Record.push_back((unsigned)T->getKeyword());
370 if (T->getDeducedType().isNull())
371 Record.push_back(T->isDependentType());
375 void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
376 const DeducedTemplateSpecializationType *T) {
377 Record.AddTemplateName(T->getTemplateName());
378 Record.AddTypeRef(T->getDeducedType());
379 if (T->getDeducedType().isNull())
380 Record.push_back(T->isDependentType());
381 Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
384 void ASTTypeWriter::VisitTagType(const TagType *T) {
385 Record.push_back(T->isDependentType());
386 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
387 assert(!T->isBeingDefined() &&
388 "Cannot serialize in the middle of a type definition");
391 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
396 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
401 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
402 Record.AddTypeRef(T->getModifiedType());
403 Record.AddTypeRef(T->getEquivalentType());
404 Record.push_back(T->getAttrKind());
405 Code = TYPE_ATTRIBUTED;
409 ASTTypeWriter::VisitSubstTemplateTypeParmType(
410 const SubstTemplateTypeParmType *T) {
411 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
412 Record.AddTypeRef(T->getReplacementType());
413 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
417 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
418 const SubstTemplateTypeParmPackType *T) {
419 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
420 Record.AddTemplateArgument(T->getArgumentPack());
421 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
425 ASTTypeWriter::VisitTemplateSpecializationType(
426 const TemplateSpecializationType *T) {
427 Record.push_back(T->isDependentType());
428 Record.AddTemplateName(T->getTemplateName());
429 Record.push_back(T->getNumArgs());
430 for (const auto &ArgI : *T)
431 Record.AddTemplateArgument(ArgI);
432 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
433 : T->isCanonicalUnqualified()
435 : T->getCanonicalTypeInternal());
436 Code = TYPE_TEMPLATE_SPECIALIZATION;
440 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
442 Record.AddStmt(T->getSizeExpr());
443 Record.AddSourceRange(T->getBracketsRange());
444 Code = TYPE_DEPENDENT_SIZED_ARRAY;
448 ASTTypeWriter::VisitDependentSizedExtVectorType(
449 const DependentSizedExtVectorType *T) {
450 Record.AddTypeRef(T->getElementType());
451 Record.AddStmt(T->getSizeExpr());
452 Record.AddSourceLocation(T->getAttributeLoc());
453 Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
457 ASTTypeWriter::VisitDependentAddressSpaceType(
458 const DependentAddressSpaceType *T) {
459 Record.AddTypeRef(T->getPointeeType());
460 Record.AddStmt(T->getAddrSpaceExpr());
461 Record.AddSourceLocation(T->getAttributeLoc());
462 Code = TYPE_DEPENDENT_ADDRESS_SPACE;
466 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
467 Record.push_back(T->getDepth());
468 Record.push_back(T->getIndex());
469 Record.push_back(T->isParameterPack());
470 Record.AddDeclRef(T->getDecl());
471 Code = TYPE_TEMPLATE_TYPE_PARM;
475 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
476 Record.push_back(T->getKeyword());
477 Record.AddNestedNameSpecifier(T->getQualifier());
478 Record.AddIdentifierRef(T->getIdentifier());
480 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
481 Code = TYPE_DEPENDENT_NAME;
485 ASTTypeWriter::VisitDependentTemplateSpecializationType(
486 const DependentTemplateSpecializationType *T) {
487 Record.push_back(T->getKeyword());
488 Record.AddNestedNameSpecifier(T->getQualifier());
489 Record.AddIdentifierRef(T->getIdentifier());
490 Record.push_back(T->getNumArgs());
491 for (const auto &I : *T)
492 Record.AddTemplateArgument(I);
493 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
496 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
497 Record.AddTypeRef(T->getPattern());
498 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
499 Record.push_back(*NumExpansions + 1);
502 Code = TYPE_PACK_EXPANSION;
505 void ASTTypeWriter::VisitParenType(const ParenType *T) {
506 Record.AddTypeRef(T->getInnerType());
510 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
511 Record.push_back(T->getKeyword());
512 Record.AddNestedNameSpecifier(T->getQualifier());
513 Record.AddTypeRef(T->getNamedType());
514 Code = TYPE_ELABORATED;
517 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
518 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
519 Record.AddTypeRef(T->getInjectedSpecializationType());
520 Code = TYPE_INJECTED_CLASS_NAME;
523 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
524 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
525 Code = TYPE_OBJC_INTERFACE;
528 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
529 Record.AddDeclRef(T->getDecl());
530 Record.push_back(T->getNumProtocols());
531 for (const auto *I : T->quals())
532 Record.AddDeclRef(I);
533 Code = TYPE_OBJC_TYPE_PARAM;
536 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
537 Record.AddTypeRef(T->getBaseType());
538 Record.push_back(T->getTypeArgsAsWritten().size());
539 for (auto TypeArg : T->getTypeArgsAsWritten())
540 Record.AddTypeRef(TypeArg);
541 Record.push_back(T->getNumProtocols());
542 for (const auto *I : T->quals())
543 Record.AddDeclRef(I);
544 Record.push_back(T->isKindOfTypeAsWritten());
545 Code = TYPE_OBJC_OBJECT;
549 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
550 Record.AddTypeRef(T->getPointeeType());
551 Code = TYPE_OBJC_OBJECT_POINTER;
555 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
556 Record.AddTypeRef(T->getValueType());
561 ASTTypeWriter::VisitPipeType(const PipeType *T) {
562 Record.AddTypeRef(T->getElementType());
563 Record.push_back(T->isReadOnly());
569 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
570 ASTRecordWriter &Record;
573 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
575 #define ABSTRACT_TYPELOC(CLASS, PARENT)
576 #define TYPELOC(CLASS, PARENT) \
577 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
578 #include "clang/AST/TypeLocNodes.def"
580 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
581 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
586 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
590 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
591 Record.AddSourceLocation(TL.getBuiltinLoc());
592 if (TL.needsExtraLocalData()) {
593 Record.push_back(TL.getWrittenTypeSpec());
594 Record.push_back(TL.getWrittenSignSpec());
595 Record.push_back(TL.getWrittenWidthSpec());
596 Record.push_back(TL.hasModeAttr());
600 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
601 Record.AddSourceLocation(TL.getNameLoc());
604 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
605 Record.AddSourceLocation(TL.getStarLoc());
608 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
612 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
616 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
617 Record.AddSourceLocation(TL.getCaretLoc());
620 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
621 Record.AddSourceLocation(TL.getAmpLoc());
624 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
625 Record.AddSourceLocation(TL.getAmpAmpLoc());
628 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
629 Record.AddSourceLocation(TL.getStarLoc());
630 Record.AddTypeSourceInfo(TL.getClassTInfo());
633 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
634 Record.AddSourceLocation(TL.getLBracketLoc());
635 Record.AddSourceLocation(TL.getRBracketLoc());
636 Record.push_back(TL.getSizeExpr() ? 1 : 0);
637 if (TL.getSizeExpr())
638 Record.AddStmt(TL.getSizeExpr());
641 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
642 VisitArrayTypeLoc(TL);
645 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
646 VisitArrayTypeLoc(TL);
649 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
650 VisitArrayTypeLoc(TL);
653 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
654 DependentSizedArrayTypeLoc TL) {
655 VisitArrayTypeLoc(TL);
658 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
659 DependentAddressSpaceTypeLoc TL) {
660 Record.AddSourceLocation(TL.getAttrNameLoc());
661 SourceRange range = TL.getAttrOperandParensRange();
662 Record.AddSourceLocation(range.getBegin());
663 Record.AddSourceLocation(range.getEnd());
664 Record.AddStmt(TL.getAttrExprOperand());
667 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
668 DependentSizedExtVectorTypeLoc TL) {
669 Record.AddSourceLocation(TL.getNameLoc());
672 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
673 Record.AddSourceLocation(TL.getNameLoc());
676 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
677 Record.AddSourceLocation(TL.getNameLoc());
680 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
681 Record.AddSourceLocation(TL.getLocalRangeBegin());
682 Record.AddSourceLocation(TL.getLParenLoc());
683 Record.AddSourceLocation(TL.getRParenLoc());
684 Record.AddSourceRange(TL.getExceptionSpecRange());
685 Record.AddSourceLocation(TL.getLocalRangeEnd());
686 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
687 Record.AddDeclRef(TL.getParam(i));
690 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
691 VisitFunctionTypeLoc(TL);
694 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
695 VisitFunctionTypeLoc(TL);
698 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
699 Record.AddSourceLocation(TL.getNameLoc());
702 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
703 Record.AddSourceLocation(TL.getNameLoc());
706 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
707 if (TL.getNumProtocols()) {
708 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
709 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
711 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
712 Record.AddSourceLocation(TL.getProtocolLoc(i));
715 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
716 Record.AddSourceLocation(TL.getTypeofLoc());
717 Record.AddSourceLocation(TL.getLParenLoc());
718 Record.AddSourceLocation(TL.getRParenLoc());
721 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
722 Record.AddSourceLocation(TL.getTypeofLoc());
723 Record.AddSourceLocation(TL.getLParenLoc());
724 Record.AddSourceLocation(TL.getRParenLoc());
725 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
728 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
729 Record.AddSourceLocation(TL.getNameLoc());
732 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
733 Record.AddSourceLocation(TL.getKWLoc());
734 Record.AddSourceLocation(TL.getLParenLoc());
735 Record.AddSourceLocation(TL.getRParenLoc());
736 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
739 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
740 Record.AddSourceLocation(TL.getNameLoc());
743 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
744 DeducedTemplateSpecializationTypeLoc TL) {
745 Record.AddSourceLocation(TL.getTemplateNameLoc());
748 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
749 Record.AddSourceLocation(TL.getNameLoc());
752 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
753 Record.AddSourceLocation(TL.getNameLoc());
756 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
757 Record.AddSourceLocation(TL.getAttrNameLoc());
758 if (TL.hasAttrOperand()) {
759 SourceRange range = TL.getAttrOperandParensRange();
760 Record.AddSourceLocation(range.getBegin());
761 Record.AddSourceLocation(range.getEnd());
763 if (TL.hasAttrExprOperand()) {
764 Expr *operand = TL.getAttrExprOperand();
765 Record.push_back(operand ? 1 : 0);
766 if (operand) Record.AddStmt(operand);
767 } else if (TL.hasAttrEnumOperand()) {
768 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
772 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
773 Record.AddSourceLocation(TL.getNameLoc());
776 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
777 SubstTemplateTypeParmTypeLoc TL) {
778 Record.AddSourceLocation(TL.getNameLoc());
781 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
782 SubstTemplateTypeParmPackTypeLoc TL) {
783 Record.AddSourceLocation(TL.getNameLoc());
786 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
787 TemplateSpecializationTypeLoc TL) {
788 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
789 Record.AddSourceLocation(TL.getTemplateNameLoc());
790 Record.AddSourceLocation(TL.getLAngleLoc());
791 Record.AddSourceLocation(TL.getRAngleLoc());
792 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
793 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
794 TL.getArgLoc(i).getLocInfo());
797 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
798 Record.AddSourceLocation(TL.getLParenLoc());
799 Record.AddSourceLocation(TL.getRParenLoc());
802 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
803 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
804 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
807 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
808 Record.AddSourceLocation(TL.getNameLoc());
811 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
812 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
813 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
814 Record.AddSourceLocation(TL.getNameLoc());
817 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
818 DependentTemplateSpecializationTypeLoc TL) {
819 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
820 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
821 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
822 Record.AddSourceLocation(TL.getTemplateNameLoc());
823 Record.AddSourceLocation(TL.getLAngleLoc());
824 Record.AddSourceLocation(TL.getRAngleLoc());
825 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
826 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
827 TL.getArgLoc(I).getLocInfo());
830 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
831 Record.AddSourceLocation(TL.getEllipsisLoc());
834 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
835 Record.AddSourceLocation(TL.getNameLoc());
838 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
839 Record.push_back(TL.hasBaseTypeAsWritten());
840 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
841 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
842 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
843 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
844 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
845 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
846 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
847 Record.AddSourceLocation(TL.getProtocolLoc(i));
850 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
851 Record.AddSourceLocation(TL.getStarLoc());
854 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
855 Record.AddSourceLocation(TL.getKWLoc());
856 Record.AddSourceLocation(TL.getLParenLoc());
857 Record.AddSourceLocation(TL.getRParenLoc());
860 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
861 Record.AddSourceLocation(TL.getKWLoc());
864 void ASTWriter::WriteTypeAbbrevs() {
865 using namespace llvm;
867 std::shared_ptr<BitCodeAbbrev> Abv;
869 // Abbreviation for TYPE_EXT_QUAL
870 Abv = std::make_shared<BitCodeAbbrev>();
871 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
872 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
873 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
874 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
876 // Abbreviation for TYPE_FUNCTION_PROTO
877 Abv = std::make_shared<BitCodeAbbrev>();
878 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
880 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
881 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
882 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
883 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
884 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
885 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
886 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
888 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
889 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
890 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
891 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
892 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
893 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
894 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
895 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
896 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
899 //===----------------------------------------------------------------------===//
900 // ASTWriter Implementation
901 //===----------------------------------------------------------------------===//
903 static void EmitBlockID(unsigned ID, const char *Name,
904 llvm::BitstreamWriter &Stream,
905 ASTWriter::RecordDataImpl &Record) {
907 Record.push_back(ID);
908 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
910 // Emit the block name if present.
911 if (!Name || Name[0] == 0)
915 Record.push_back(*Name++);
916 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
919 static void EmitRecordID(unsigned ID, const char *Name,
920 llvm::BitstreamWriter &Stream,
921 ASTWriter::RecordDataImpl &Record) {
923 Record.push_back(ID);
925 Record.push_back(*Name++);
926 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
929 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
930 ASTWriter::RecordDataImpl &Record) {
931 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
933 RECORD(STMT_NULL_PTR);
934 RECORD(STMT_REF_PTR);
936 RECORD(STMT_COMPOUND);
938 RECORD(STMT_DEFAULT);
940 RECORD(STMT_ATTRIBUTED);
947 RECORD(STMT_INDIRECT_GOTO);
948 RECORD(STMT_CONTINUE);
954 RECORD(EXPR_PREDEFINED);
955 RECORD(EXPR_DECL_REF);
956 RECORD(EXPR_INTEGER_LITERAL);
957 RECORD(EXPR_FLOATING_LITERAL);
958 RECORD(EXPR_IMAGINARY_LITERAL);
959 RECORD(EXPR_STRING_LITERAL);
960 RECORD(EXPR_CHARACTER_LITERAL);
962 RECORD(EXPR_PAREN_LIST);
963 RECORD(EXPR_UNARY_OPERATOR);
964 RECORD(EXPR_SIZEOF_ALIGN_OF);
965 RECORD(EXPR_ARRAY_SUBSCRIPT);
968 RECORD(EXPR_BINARY_OPERATOR);
969 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
970 RECORD(EXPR_CONDITIONAL_OPERATOR);
971 RECORD(EXPR_IMPLICIT_CAST);
972 RECORD(EXPR_CSTYLE_CAST);
973 RECORD(EXPR_COMPOUND_LITERAL);
974 RECORD(EXPR_EXT_VECTOR_ELEMENT);
975 RECORD(EXPR_INIT_LIST);
976 RECORD(EXPR_DESIGNATED_INIT);
977 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
978 RECORD(EXPR_IMPLICIT_VALUE_INIT);
979 RECORD(EXPR_NO_INIT);
981 RECORD(EXPR_ADDR_LABEL);
984 RECORD(EXPR_GNU_NULL);
985 RECORD(EXPR_SHUFFLE_VECTOR);
987 RECORD(EXPR_GENERIC_SELECTION);
988 RECORD(EXPR_OBJC_STRING_LITERAL);
989 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
990 RECORD(EXPR_OBJC_ARRAY_LITERAL);
991 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
992 RECORD(EXPR_OBJC_ENCODE);
993 RECORD(EXPR_OBJC_SELECTOR_EXPR);
994 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
995 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
996 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
997 RECORD(EXPR_OBJC_KVC_REF_EXPR);
998 RECORD(EXPR_OBJC_MESSAGE_EXPR);
999 RECORD(STMT_OBJC_FOR_COLLECTION);
1000 RECORD(STMT_OBJC_CATCH);
1001 RECORD(STMT_OBJC_FINALLY);
1002 RECORD(STMT_OBJC_AT_TRY);
1003 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
1004 RECORD(STMT_OBJC_AT_THROW);
1005 RECORD(EXPR_OBJC_BOOL_LITERAL);
1006 RECORD(STMT_CXX_CATCH);
1007 RECORD(STMT_CXX_TRY);
1008 RECORD(STMT_CXX_FOR_RANGE);
1009 RECORD(EXPR_CXX_OPERATOR_CALL);
1010 RECORD(EXPR_CXX_MEMBER_CALL);
1011 RECORD(EXPR_CXX_CONSTRUCT);
1012 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
1013 RECORD(EXPR_CXX_STATIC_CAST);
1014 RECORD(EXPR_CXX_DYNAMIC_CAST);
1015 RECORD(EXPR_CXX_REINTERPRET_CAST);
1016 RECORD(EXPR_CXX_CONST_CAST);
1017 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
1018 RECORD(EXPR_USER_DEFINED_LITERAL);
1019 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
1020 RECORD(EXPR_CXX_BOOL_LITERAL);
1021 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
1022 RECORD(EXPR_CXX_TYPEID_EXPR);
1023 RECORD(EXPR_CXX_TYPEID_TYPE);
1024 RECORD(EXPR_CXX_THIS);
1025 RECORD(EXPR_CXX_THROW);
1026 RECORD(EXPR_CXX_DEFAULT_ARG);
1027 RECORD(EXPR_CXX_DEFAULT_INIT);
1028 RECORD(EXPR_CXX_BIND_TEMPORARY);
1029 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
1030 RECORD(EXPR_CXX_NEW);
1031 RECORD(EXPR_CXX_DELETE);
1032 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
1033 RECORD(EXPR_EXPR_WITH_CLEANUPS);
1034 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
1035 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
1036 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
1037 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
1038 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
1039 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
1040 RECORD(EXPR_CXX_NOEXCEPT);
1041 RECORD(EXPR_OPAQUE_VALUE);
1042 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1043 RECORD(EXPR_TYPE_TRAIT);
1044 RECORD(EXPR_ARRAY_TYPE_TRAIT);
1045 RECORD(EXPR_PACK_EXPANSION);
1046 RECORD(EXPR_SIZEOF_PACK);
1047 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
1048 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
1049 RECORD(EXPR_FUNCTION_PARM_PACK);
1050 RECORD(EXPR_MATERIALIZE_TEMPORARY);
1051 RECORD(EXPR_CUDA_KERNEL_CALL);
1052 RECORD(EXPR_CXX_UUIDOF_EXPR);
1053 RECORD(EXPR_CXX_UUIDOF_TYPE);
1054 RECORD(EXPR_LAMBDA);
1058 void ASTWriter::WriteBlockInfoBlock() {
1060 Stream.EnterBlockInfoBlock();
1062 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1063 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1066 BLOCK(CONTROL_BLOCK);
1068 RECORD(MODULE_NAME);
1069 RECORD(MODULE_DIRECTORY);
1070 RECORD(MODULE_MAP_FILE);
1072 RECORD(ORIGINAL_FILE);
1073 RECORD(ORIGINAL_PCH_DIR);
1074 RECORD(ORIGINAL_FILE_ID);
1075 RECORD(INPUT_FILE_OFFSETS);
1077 BLOCK(OPTIONS_BLOCK);
1078 RECORD(LANGUAGE_OPTIONS);
1079 RECORD(TARGET_OPTIONS);
1080 RECORD(FILE_SYSTEM_OPTIONS);
1081 RECORD(HEADER_SEARCH_OPTIONS);
1082 RECORD(PREPROCESSOR_OPTIONS);
1084 BLOCK(INPUT_FILES_BLOCK);
1087 // AST Top-Level Block.
1089 RECORD(TYPE_OFFSET);
1090 RECORD(DECL_OFFSET);
1091 RECORD(IDENTIFIER_OFFSET);
1092 RECORD(IDENTIFIER_TABLE);
1093 RECORD(EAGERLY_DESERIALIZED_DECLS);
1094 RECORD(MODULAR_CODEGEN_DECLS);
1095 RECORD(SPECIAL_TYPES);
1097 RECORD(TENTATIVE_DEFINITIONS);
1098 RECORD(SELECTOR_OFFSETS);
1099 RECORD(METHOD_POOL);
1100 RECORD(PP_COUNTER_VALUE);
1101 RECORD(SOURCE_LOCATION_OFFSETS);
1102 RECORD(SOURCE_LOCATION_PRELOADS);
1103 RECORD(EXT_VECTOR_DECLS);
1104 RECORD(UNUSED_FILESCOPED_DECLS);
1105 RECORD(PPD_ENTITIES_OFFSETS);
1106 RECORD(VTABLE_USES);
1107 RECORD(REFERENCED_SELECTOR_POOL);
1108 RECORD(TU_UPDATE_LEXICAL);
1109 RECORD(SEMA_DECL_REFS);
1110 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1111 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1112 RECORD(UPDATE_VISIBLE);
1113 RECORD(DECL_UPDATE_OFFSETS);
1114 RECORD(DECL_UPDATES);
1115 RECORD(CUDA_SPECIAL_DECL_REFS);
1116 RECORD(HEADER_SEARCH_TABLE);
1117 RECORD(FP_PRAGMA_OPTIONS);
1118 RECORD(OPENCL_EXTENSIONS);
1119 RECORD(OPENCL_EXTENSION_TYPES);
1120 RECORD(OPENCL_EXTENSION_DECLS);
1121 RECORD(DELEGATING_CTORS);
1122 RECORD(KNOWN_NAMESPACES);
1123 RECORD(MODULE_OFFSET_MAP);
1124 RECORD(SOURCE_MANAGER_LINE_TABLE);
1125 RECORD(OBJC_CATEGORIES_MAP);
1126 RECORD(FILE_SORTED_DECLS);
1127 RECORD(IMPORTED_MODULES);
1128 RECORD(OBJC_CATEGORIES);
1129 RECORD(MACRO_OFFSET);
1130 RECORD(INTERESTING_IDENTIFIERS);
1131 RECORD(UNDEFINED_BUT_USED);
1132 RECORD(LATE_PARSED_TEMPLATE);
1133 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1134 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1135 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1136 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1137 RECORD(DELETE_EXPRS_TO_ANALYZE);
1138 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1139 RECORD(PP_CONDITIONAL_STACK);
1141 // SourceManager Block.
1142 BLOCK(SOURCE_MANAGER_BLOCK);
1143 RECORD(SM_SLOC_FILE_ENTRY);
1144 RECORD(SM_SLOC_BUFFER_ENTRY);
1145 RECORD(SM_SLOC_BUFFER_BLOB);
1146 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1147 RECORD(SM_SLOC_EXPANSION_ENTRY);
1149 // Preprocessor Block.
1150 BLOCK(PREPROCESSOR_BLOCK);
1151 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1152 RECORD(PP_MACRO_FUNCTION_LIKE);
1153 RECORD(PP_MACRO_OBJECT_LIKE);
1154 RECORD(PP_MODULE_MACRO);
1158 BLOCK(SUBMODULE_BLOCK);
1159 RECORD(SUBMODULE_METADATA);
1160 RECORD(SUBMODULE_DEFINITION);
1161 RECORD(SUBMODULE_UMBRELLA_HEADER);
1162 RECORD(SUBMODULE_HEADER);
1163 RECORD(SUBMODULE_TOPHEADER);
1164 RECORD(SUBMODULE_UMBRELLA_DIR);
1165 RECORD(SUBMODULE_IMPORTS);
1166 RECORD(SUBMODULE_EXPORTS);
1167 RECORD(SUBMODULE_REQUIRES);
1168 RECORD(SUBMODULE_EXCLUDED_HEADER);
1169 RECORD(SUBMODULE_LINK_LIBRARY);
1170 RECORD(SUBMODULE_CONFIG_MACRO);
1171 RECORD(SUBMODULE_CONFLICT);
1172 RECORD(SUBMODULE_PRIVATE_HEADER);
1173 RECORD(SUBMODULE_TEXTUAL_HEADER);
1174 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1175 RECORD(SUBMODULE_INITIALIZERS);
1176 RECORD(SUBMODULE_EXPORT_AS);
1179 BLOCK(COMMENTS_BLOCK);
1180 RECORD(COMMENTS_RAW_COMMENT);
1182 // Decls and Types block.
1183 BLOCK(DECLTYPES_BLOCK);
1184 RECORD(TYPE_EXT_QUAL);
1185 RECORD(TYPE_COMPLEX);
1186 RECORD(TYPE_POINTER);
1187 RECORD(TYPE_BLOCK_POINTER);
1188 RECORD(TYPE_LVALUE_REFERENCE);
1189 RECORD(TYPE_RVALUE_REFERENCE);
1190 RECORD(TYPE_MEMBER_POINTER);
1191 RECORD(TYPE_CONSTANT_ARRAY);
1192 RECORD(TYPE_INCOMPLETE_ARRAY);
1193 RECORD(TYPE_VARIABLE_ARRAY);
1194 RECORD(TYPE_VECTOR);
1195 RECORD(TYPE_EXT_VECTOR);
1196 RECORD(TYPE_FUNCTION_NO_PROTO);
1197 RECORD(TYPE_FUNCTION_PROTO);
1198 RECORD(TYPE_TYPEDEF);
1199 RECORD(TYPE_TYPEOF_EXPR);
1200 RECORD(TYPE_TYPEOF);
1201 RECORD(TYPE_RECORD);
1203 RECORD(TYPE_OBJC_INTERFACE);
1204 RECORD(TYPE_OBJC_OBJECT_POINTER);
1205 RECORD(TYPE_DECLTYPE);
1206 RECORD(TYPE_ELABORATED);
1207 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1208 RECORD(TYPE_UNRESOLVED_USING);
1209 RECORD(TYPE_INJECTED_CLASS_NAME);
1210 RECORD(TYPE_OBJC_OBJECT);
1211 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1212 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1213 RECORD(TYPE_DEPENDENT_NAME);
1214 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1215 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1217 RECORD(TYPE_PACK_EXPANSION);
1218 RECORD(TYPE_ATTRIBUTED);
1219 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1221 RECORD(TYPE_UNARY_TRANSFORM);
1222 RECORD(TYPE_ATOMIC);
1223 RECORD(TYPE_DECAYED);
1224 RECORD(TYPE_ADJUSTED);
1225 RECORD(TYPE_OBJC_TYPE_PARAM);
1226 RECORD(LOCAL_REDECLARATIONS);
1227 RECORD(DECL_TYPEDEF);
1228 RECORD(DECL_TYPEALIAS);
1230 RECORD(DECL_RECORD);
1231 RECORD(DECL_ENUM_CONSTANT);
1232 RECORD(DECL_FUNCTION);
1233 RECORD(DECL_OBJC_METHOD);
1234 RECORD(DECL_OBJC_INTERFACE);
1235 RECORD(DECL_OBJC_PROTOCOL);
1236 RECORD(DECL_OBJC_IVAR);
1237 RECORD(DECL_OBJC_AT_DEFS_FIELD);
1238 RECORD(DECL_OBJC_CATEGORY);
1239 RECORD(DECL_OBJC_CATEGORY_IMPL);
1240 RECORD(DECL_OBJC_IMPLEMENTATION);
1241 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1242 RECORD(DECL_OBJC_PROPERTY);
1243 RECORD(DECL_OBJC_PROPERTY_IMPL);
1245 RECORD(DECL_MS_PROPERTY);
1247 RECORD(DECL_IMPLICIT_PARAM);
1248 RECORD(DECL_PARM_VAR);
1249 RECORD(DECL_FILE_SCOPE_ASM);
1251 RECORD(DECL_CONTEXT_LEXICAL);
1252 RECORD(DECL_CONTEXT_VISIBLE);
1253 RECORD(DECL_NAMESPACE);
1254 RECORD(DECL_NAMESPACE_ALIAS);
1256 RECORD(DECL_USING_SHADOW);
1257 RECORD(DECL_USING_DIRECTIVE);
1258 RECORD(DECL_UNRESOLVED_USING_VALUE);
1259 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1260 RECORD(DECL_LINKAGE_SPEC);
1261 RECORD(DECL_CXX_RECORD);
1262 RECORD(DECL_CXX_METHOD);
1263 RECORD(DECL_CXX_CONSTRUCTOR);
1264 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
1265 RECORD(DECL_CXX_DESTRUCTOR);
1266 RECORD(DECL_CXX_CONVERSION);
1267 RECORD(DECL_ACCESS_SPEC);
1268 RECORD(DECL_FRIEND);
1269 RECORD(DECL_FRIEND_TEMPLATE);
1270 RECORD(DECL_CLASS_TEMPLATE);
1271 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1272 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1273 RECORD(DECL_VAR_TEMPLATE);
1274 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1275 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1276 RECORD(DECL_FUNCTION_TEMPLATE);
1277 RECORD(DECL_TEMPLATE_TYPE_PARM);
1278 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1279 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1280 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1281 RECORD(DECL_STATIC_ASSERT);
1282 RECORD(DECL_CXX_BASE_SPECIFIERS);
1283 RECORD(DECL_CXX_CTOR_INITIALIZERS);
1284 RECORD(DECL_INDIRECTFIELD);
1285 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1286 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1287 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1288 RECORD(DECL_IMPORT);
1289 RECORD(DECL_OMP_THREADPRIVATE);
1291 RECORD(DECL_OBJC_TYPE_PARAM);
1292 RECORD(DECL_OMP_CAPTUREDEXPR);
1293 RECORD(DECL_PRAGMA_COMMENT);
1294 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1295 RECORD(DECL_OMP_DECLARE_REDUCTION);
1297 // Statements and Exprs can occur in the Decls and Types block.
1298 AddStmtsExprs(Stream, Record);
1300 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1301 RECORD(PPD_MACRO_EXPANSION);
1302 RECORD(PPD_MACRO_DEFINITION);
1303 RECORD(PPD_INCLUSION_DIRECTIVE);
1305 // Decls and Types block.
1306 BLOCK(EXTENSION_BLOCK);
1307 RECORD(EXTENSION_METADATA);
1309 BLOCK(UNHASHED_CONTROL_BLOCK);
1311 RECORD(DIAGNOSTIC_OPTIONS);
1312 RECORD(DIAG_PRAGMA_MAPPINGS);
1319 /// \brief Prepares a path for being written to an AST file by converting it
1320 /// to an absolute path and removing nested './'s.
1322 /// \return \c true if the path was changed.
1323 static bool cleanPathForOutput(FileManager &FileMgr,
1324 SmallVectorImpl<char> &Path) {
1325 bool Changed = FileMgr.makeAbsolutePath(Path);
1326 return Changed | llvm::sys::path::remove_dots(Path);
1329 /// \brief Adjusts the given filename to only write out the portion of the
1330 /// filename that is not part of the system root directory.
1332 /// \param Filename the file name to adjust.
1334 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1335 /// the returned filename will be adjusted by this root directory.
1337 /// \returns either the original filename (if it needs no adjustment) or the
1338 /// adjusted filename (which points into the @p Filename parameter).
1340 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1341 assert(Filename && "No file name to adjust?");
1343 if (BaseDir.empty())
1346 // Verify that the filename and the system root have the same prefix.
1348 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1349 if (Filename[Pos] != BaseDir[Pos])
1350 return Filename; // Prefixes don't match.
1352 // We hit the end of the filename before we hit the end of the system root.
1356 // If there's not a path separator at the end of the base directory nor
1357 // immediately after it, then this isn't within the base directory.
1358 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1359 if (!llvm::sys::path::is_separator(BaseDir.back()))
1362 // If the file name has a '/' at the current position, skip over the '/'.
1363 // We distinguish relative paths from absolute paths by the
1364 // absence of '/' at the beginning of relative paths.
1366 // FIXME: This is wrong. We distinguish them by asking if the path is
1367 // absolute, which isn't the same thing. And there might be multiple '/'s
1368 // in a row. Use a better mechanism to indicate whether we have emitted an
1369 // absolute or relative path.
1373 return Filename + Pos;
1376 ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1377 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1379 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1380 auto Hash = Hasher.result();
1382 // Convert to an array [5*i32].
1383 ASTFileSignature Signature;
1384 auto LShift = [&](unsigned char Val, unsigned Shift) {
1385 return (uint32_t)Val << Shift;
1387 for (int I = 0; I != 5; ++I)
1388 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1389 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1394 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1395 ASTContext &Context) {
1396 // Flush first to prepare the PCM hash (signature).
1397 Stream.FlushToWord();
1398 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1400 // Enter the block and prepare to write records.
1402 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1404 // For implicit modules, write the hash of the PCM as its signature.
1405 ASTFileSignature Signature;
1406 if (WritingModule &&
1407 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1408 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1409 Record.append(Signature.begin(), Signature.end());
1410 Stream.EmitRecord(SIGNATURE, Record);
1414 // Diagnostic options.
1415 const auto &Diags = Context.getDiagnostics();
1416 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1417 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1418 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1419 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1420 #include "clang/Basic/DiagnosticOptions.def"
1421 Record.push_back(DiagOpts.Warnings.size());
1422 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1423 AddString(DiagOpts.Warnings[I], Record);
1424 Record.push_back(DiagOpts.Remarks.size());
1425 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1426 AddString(DiagOpts.Remarks[I], Record);
1427 // Note: we don't serialize the log or serialization file names, because they
1428 // are generally transient files and will almost always be overridden.
1429 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1431 // Write out the diagnostic/pragma mappings.
1432 WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1434 // Leave the options block.
1439 /// \brief Write the control block.
1440 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1442 const std::string &OutputFile) {
1443 using namespace llvm;
1445 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1449 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1450 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1451 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1452 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1453 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1454 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1455 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1456 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1457 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1458 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1459 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1460 assert((!WritingModule || isysroot.empty()) &&
1461 "writing module as a relocatable PCH?");
1463 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1464 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1465 !isysroot.empty(), IncludeTimestamps,
1466 ASTHasCompilerErrors};
1467 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1468 getClangFullRepositoryVersion());
1471 if (WritingModule) {
1473 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1474 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1475 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1476 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1477 RecordData::value_type Record[] = {MODULE_NAME};
1478 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1481 if (WritingModule && WritingModule->Directory) {
1482 SmallString<128> BaseDir(WritingModule->Directory->getName());
1483 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1485 // If the home of the module is the current working directory, then we
1486 // want to pick up the cwd of the build process loading the module, not
1487 // our cwd, when we load this module.
1488 if (!PP.getHeaderSearchInfo()
1489 .getHeaderSearchOpts()
1490 .ModuleMapFileHomeIsCwd ||
1491 WritingModule->Directory->getName() != StringRef(".")) {
1492 // Module directory.
1493 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1494 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1496 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1498 RecordData::value_type Record[] = {MODULE_DIRECTORY};
1499 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1502 // Write out all other paths relative to the base directory if possible.
1503 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1504 } else if (!isysroot.empty()) {
1505 // Write out paths relative to the sysroot if possible.
1506 BaseDirectory = isysroot;
1510 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1513 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1514 AddPath(WritingModule->PresumedModuleMapFile.empty()
1515 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1516 : StringRef(WritingModule->PresumedModuleMapFile),
1519 // Additional module map files.
1520 if (auto *AdditionalModMaps =
1521 Map.getAdditionalModuleMapFiles(WritingModule)) {
1522 Record.push_back(AdditionalModMaps->size());
1523 for (const FileEntry *F : *AdditionalModMaps)
1524 AddPath(F->getName(), Record);
1526 Record.push_back(0);
1529 Stream.EmitRecord(MODULE_MAP_FILE, Record);
1534 serialization::ModuleManager &Mgr = Chain->getModuleManager();
1537 for (ModuleFile &M : Mgr) {
1538 // Skip modules that weren't directly imported.
1539 if (!M.isDirectlyImported())
1542 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1543 AddSourceLocation(M.ImportLoc, Record);
1545 // If we have calculated signature, there is no need to store
1546 // the size or timestamp.
1547 Record.push_back(M.Signature ? 0 : M.File->getSize());
1548 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1550 for (auto I : M.Signature)
1551 Record.push_back(I);
1553 AddString(M.ModuleName, Record);
1554 AddPath(M.FileName, Record);
1556 Stream.EmitRecord(IMPORTS, Record);
1559 // Write the options block.
1560 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1562 // Language options.
1564 const LangOptions &LangOpts = Context.getLangOpts();
1565 #define LANGOPT(Name, Bits, Default, Description) \
1566 Record.push_back(LangOpts.Name);
1567 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1568 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1569 #include "clang/Basic/LangOptions.def"
1570 #define SANITIZER(NAME, ID) \
1571 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1572 #include "clang/Basic/Sanitizers.def"
1574 Record.push_back(LangOpts.ModuleFeatures.size());
1575 for (StringRef Feature : LangOpts.ModuleFeatures)
1576 AddString(Feature, Record);
1578 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1579 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1581 AddString(LangOpts.CurrentModule, Record);
1584 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1585 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1586 AddString(I, Record);
1588 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1590 // OpenMP offloading options.
1591 Record.push_back(LangOpts.OMPTargetTriples.size());
1592 for (auto &T : LangOpts.OMPTargetTriples)
1593 AddString(T.getTriple(), Record);
1595 AddString(LangOpts.OMPHostIRFile, Record);
1597 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1601 const TargetInfo &Target = Context.getTargetInfo();
1602 const TargetOptions &TargetOpts = Target.getTargetOpts();
1603 AddString(TargetOpts.Triple, Record);
1604 AddString(TargetOpts.CPU, Record);
1605 AddString(TargetOpts.ABI, Record);
1606 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1607 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1608 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1610 Record.push_back(TargetOpts.Features.size());
1611 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1612 AddString(TargetOpts.Features[I], Record);
1614 Stream.EmitRecord(TARGET_OPTIONS, Record);
1616 // File system options.
1618 const FileSystemOptions &FSOpts =
1619 Context.getSourceManager().getFileManager().getFileSystemOpts();
1620 AddString(FSOpts.WorkingDir, Record);
1621 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1623 // Header search options.
1625 const HeaderSearchOptions &HSOpts
1626 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1627 AddString(HSOpts.Sysroot, Record);
1630 Record.push_back(HSOpts.UserEntries.size());
1631 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1632 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1633 AddString(Entry.Path, Record);
1634 Record.push_back(static_cast<unsigned>(Entry.Group));
1635 Record.push_back(Entry.IsFramework);
1636 Record.push_back(Entry.IgnoreSysRoot);
1639 // System header prefixes.
1640 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1641 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1642 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1643 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1646 AddString(HSOpts.ResourceDir, Record);
1647 AddString(HSOpts.ModuleCachePath, Record);
1648 AddString(HSOpts.ModuleUserBuildPath, Record);
1649 Record.push_back(HSOpts.DisableModuleHash);
1650 Record.push_back(HSOpts.ImplicitModuleMaps);
1651 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1652 Record.push_back(HSOpts.UseBuiltinIncludes);
1653 Record.push_back(HSOpts.UseStandardSystemIncludes);
1654 Record.push_back(HSOpts.UseStandardCXXIncludes);
1655 Record.push_back(HSOpts.UseLibcxx);
1656 // Write out the specific module cache path that contains the module files.
1657 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1658 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1660 // Preprocessor options.
1662 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1664 // Macro definitions.
1665 Record.push_back(PPOpts.Macros.size());
1666 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1667 AddString(PPOpts.Macros[I].first, Record);
1668 Record.push_back(PPOpts.Macros[I].second);
1672 Record.push_back(PPOpts.Includes.size());
1673 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1674 AddString(PPOpts.Includes[I], Record);
1677 Record.push_back(PPOpts.MacroIncludes.size());
1678 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1679 AddString(PPOpts.MacroIncludes[I], Record);
1681 Record.push_back(PPOpts.UsePredefines);
1682 // Detailed record is important since it is used for the module cache hash.
1683 Record.push_back(PPOpts.DetailedRecord);
1684 AddString(PPOpts.ImplicitPCHInclude, Record);
1685 AddString(PPOpts.ImplicitPTHInclude, Record);
1686 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1687 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1689 // Leave the options block.
1692 // Original file name and file ID
1693 SourceManager &SM = Context.getSourceManager();
1694 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1695 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1696 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1697 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1698 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1699 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1702 Record.push_back(ORIGINAL_FILE);
1703 Record.push_back(SM.getMainFileID().getOpaqueValue());
1704 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1708 Record.push_back(SM.getMainFileID().getOpaqueValue());
1709 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1711 // Original PCH directory
1712 if (!OutputFile.empty() && OutputFile != "-") {
1713 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1714 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1716 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1718 SmallString<128> OutputPath(OutputFile);
1720 SM.getFileManager().makeAbsolutePath(OutputPath);
1721 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1723 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1724 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1727 WriteInputFiles(Context.SourceMgr,
1728 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1729 PP.getLangOpts().Modules);
1735 /// \brief An input file.
1736 struct InputFileEntry {
1737 const FileEntry *File;
1740 bool BufferOverridden;
1741 bool IsTopLevelModuleMap;
1746 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1747 HeaderSearchOptions &HSOpts,
1749 using namespace llvm;
1751 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1753 // Create input-file abbreviation.
1754 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1755 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1756 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1757 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1758 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1759 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1760 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1761 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1762 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1763 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1765 // Get all ContentCache objects for files, sorted by whether the file is a
1766 // system one or not. System files go at the back, users files at the front.
1767 std::deque<InputFileEntry> SortedFiles;
1768 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1769 // Get this source location entry.
1770 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1771 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1773 // We only care about file entries that were not overridden.
1774 if (!SLoc->isFile())
1776 const SrcMgr::FileInfo &File = SLoc->getFile();
1777 const SrcMgr::ContentCache *Cache = File.getContentCache();
1778 if (!Cache->OrigEntry)
1781 InputFileEntry Entry;
1782 Entry.File = Cache->OrigEntry;
1783 Entry.IsSystemFile = Cache->IsSystemFile;
1784 Entry.IsTransient = Cache->IsTransient;
1785 Entry.BufferOverridden = Cache->BufferOverridden;
1786 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1787 File.getIncludeLoc().isInvalid();
1788 if (Cache->IsSystemFile)
1789 SortedFiles.push_back(Entry);
1791 SortedFiles.push_front(Entry);
1794 unsigned UserFilesNum = 0;
1795 // Write out all of the input files.
1796 std::vector<uint64_t> InputFileOffsets;
1797 for (const auto &Entry : SortedFiles) {
1798 uint32_t &InputFileID = InputFileIDs[Entry.File];
1799 if (InputFileID != 0)
1800 continue; // already recorded this file.
1802 // Record this entry's offset.
1803 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1805 InputFileID = InputFileOffsets.size();
1807 if (!Entry.IsSystemFile)
1810 // Emit size/modification time for this file.
1811 // And whether this file was overridden.
1812 RecordData::value_type Record[] = {
1814 InputFileOffsets.size(),
1815 (uint64_t)Entry.File->getSize(),
1816 (uint64_t)getTimestampForOutput(Entry.File),
1817 Entry.BufferOverridden,
1819 Entry.IsTopLevelModuleMap};
1821 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1826 // Create input file offsets abbreviation.
1827 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1828 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1829 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1830 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1832 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1833 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1835 // Write input file offsets.
1836 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1837 InputFileOffsets.size(), UserFilesNum};
1838 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1841 //===----------------------------------------------------------------------===//
1842 // Source Manager Serialization
1843 //===----------------------------------------------------------------------===//
1845 /// \brief Create an abbreviation for the SLocEntry that refers to a
1847 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1848 using namespace llvm;
1850 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1851 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1856 // FileEntry fields.
1857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1858 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1861 return Stream.EmitAbbrev(std::move(Abbrev));
1864 /// \brief Create an abbreviation for the SLocEntry that refers to a
1866 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1867 using namespace llvm;
1869 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1870 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1876 return Stream.EmitAbbrev(std::move(Abbrev));
1879 /// \brief Create an abbreviation for the SLocEntry that refers to a
1881 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1883 using namespace llvm;
1885 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1886 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1887 : SM_SLOC_BUFFER_BLOB));
1889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1891 return Stream.EmitAbbrev(std::move(Abbrev));
1894 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1896 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1897 using namespace llvm;
1899 auto Abbrev = std::make_shared<BitCodeAbbrev>();
1900 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1901 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1905 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1906 return Stream.EmitAbbrev(std::move(Abbrev));
1911 // Trait used for the on-disk hash table of header search information.
1912 class HeaderFileInfoTrait {
1915 // Keep track of the framework names we've used during serialization.
1916 SmallVector<char, 128> FrameworkStringData;
1917 llvm::StringMap<unsigned> FrameworkNameOffset;
1920 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1927 using key_type_ref = const key_type &;
1929 using UnresolvedModule =
1930 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1933 const HeaderFileInfo &HFI;
1934 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1935 UnresolvedModule Unresolved;
1937 using data_type_ref = const data_type &;
1939 using hash_value_type = unsigned;
1940 using offset_type = unsigned;
1942 hash_value_type ComputeHash(key_type_ref key) {
1943 // The hash is based only on size/time of the file, so that the reader can
1944 // match even when symlinking or excess path elements ("foo/../", "../")
1945 // change the form of the name. However, complete path is still the key.
1946 return llvm::hash_combine(key.Size, key.ModTime);
1949 std::pair<unsigned, unsigned>
1950 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1951 using namespace llvm::support;
1953 endian::Writer<little> LE(Out);
1954 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1955 LE.write<uint16_t>(KeyLen);
1956 unsigned DataLen = 1 + 2 + 4 + 4;
1957 for (auto ModInfo : Data.KnownHeaders)
1958 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1960 if (Data.Unresolved.getPointer())
1962 LE.write<uint8_t>(DataLen);
1963 return std::make_pair(KeyLen, DataLen);
1966 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1967 using namespace llvm::support;
1969 endian::Writer<little> LE(Out);
1970 LE.write<uint64_t>(key.Size);
1972 LE.write<uint64_t>(key.ModTime);
1974 Out.write(key.Filename.data(), KeyLen);
1977 void EmitData(raw_ostream &Out, key_type_ref key,
1978 data_type_ref Data, unsigned DataLen) {
1979 using namespace llvm::support;
1981 endian::Writer<little> LE(Out);
1982 uint64_t Start = Out.tell(); (void)Start;
1984 unsigned char Flags = (Data.HFI.isImport << 5)
1985 | (Data.HFI.isPragmaOnce << 4)
1986 | (Data.HFI.DirInfo << 1)
1987 | Data.HFI.IndexHeaderMapHeader;
1988 LE.write<uint8_t>(Flags);
1989 LE.write<uint16_t>(Data.HFI.NumIncludes);
1991 if (!Data.HFI.ControllingMacro)
1992 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1994 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1996 unsigned Offset = 0;
1997 if (!Data.HFI.Framework.empty()) {
1998 // If this header refers into a framework, save the framework name.
1999 llvm::StringMap<unsigned>::iterator Pos
2000 = FrameworkNameOffset.find(Data.HFI.Framework);
2001 if (Pos == FrameworkNameOffset.end()) {
2002 Offset = FrameworkStringData.size() + 1;
2003 FrameworkStringData.append(Data.HFI.Framework.begin(),
2004 Data.HFI.Framework.end());
2005 FrameworkStringData.push_back(0);
2007 FrameworkNameOffset[Data.HFI.Framework] = Offset;
2009 Offset = Pos->second;
2011 LE.write<uint32_t>(Offset);
2013 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2014 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2015 uint32_t Value = (ModID << 2) | (unsigned)Role;
2016 assert((Value >> 2) == ModID && "overflow in header module info");
2017 LE.write<uint32_t>(Value);
2021 // FIXME: If the header is excluded, we should write out some
2022 // record of that fact.
2023 for (auto ModInfo : Data.KnownHeaders)
2024 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2025 if (Data.Unresolved.getPointer())
2026 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2028 assert(Out.tell() - Start == DataLen && "Wrong data length");
2031 const char *strings_begin() const { return FrameworkStringData.begin(); }
2032 const char *strings_end() const { return FrameworkStringData.end(); }
2037 /// \brief Write the header search block for the list of files that
2039 /// \param HS The header search structure to save.
2040 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2041 HeaderFileInfoTrait GeneratorTrait(*this);
2042 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2043 SmallVector<const char *, 4> SavedStrings;
2044 unsigned NumHeaderSearchEntries = 0;
2046 // Find all unresolved headers for the current module. We generally will
2047 // have resolved them before we get here, but not necessarily: we might be
2048 // compiling a preprocessed module, where there is no requirement for the
2049 // original files to exist any more.
2050 const HeaderFileInfo Empty; // So we can take a reference.
2051 if (WritingModule) {
2052 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2053 while (!Worklist.empty()) {
2054 Module *M = Worklist.pop_back_val();
2055 if (!M->isAvailable())
2058 // Map to disk files where possible, to pick up any missing stat
2059 // information. This also means we don't need to check the unresolved
2060 // headers list when emitting resolved headers in the first loop below.
2061 // FIXME: It'd be preferable to avoid doing this if we were given
2062 // sufficient stat information in the module map.
2063 HS.getModuleMap().resolveHeaderDirectives(M);
2065 // If the file didn't exist, we can still create a module if we were given
2066 // enough information in the module map.
2067 for (auto U : M->MissingHeaders) {
2068 // Check that we were given enough information to build a module
2069 // without this file existing on disk.
2070 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2071 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2072 << WritingModule->getFullModuleName() << U.Size.hasValue()
2077 // Form the effective relative pathname for the file.
2078 SmallString<128> Filename(M->Directory->getName());
2079 llvm::sys::path::append(Filename, U.FileName);
2080 PreparePathForOutput(Filename);
2082 StringRef FilenameDup = strdup(Filename.c_str());
2083 SavedStrings.push_back(FilenameDup.data());
2085 HeaderFileInfoTrait::key_type Key = {
2086 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2088 HeaderFileInfoTrait::data_type Data = {
2089 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2091 // FIXME: Deal with cases where there are multiple unresolved header
2092 // directives in different submodules for the same header.
2093 Generator.insert(Key, Data, GeneratorTrait);
2094 ++NumHeaderSearchEntries;
2097 Worklist.append(M->submodule_begin(), M->submodule_end());
2101 SmallVector<const FileEntry *, 16> FilesByUID;
2102 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2104 if (FilesByUID.size() > HS.header_file_size())
2105 FilesByUID.resize(HS.header_file_size());
2107 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2108 const FileEntry *File = FilesByUID[UID];
2112 // Get the file info. This will load info from the external source if
2113 // necessary. Skip emitting this file if we have no information on it
2114 // as a header file (in which case HFI will be null) or if it hasn't
2115 // changed since it was loaded. Also skip it if it's for a modular header
2116 // from a different module; in that case, we rely on the module(s)
2117 // containing the header to provide this information.
2118 const HeaderFileInfo *HFI =
2119 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2120 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2123 // Massage the file path into an appropriate form.
2124 StringRef Filename = File->getName();
2125 SmallString<128> FilenameTmp(Filename);
2126 if (PreparePathForOutput(FilenameTmp)) {
2127 // If we performed any translation on the file name at all, we need to
2128 // save this string, since the generator will refer to it later.
2129 Filename = StringRef(strdup(FilenameTmp.c_str()));
2130 SavedStrings.push_back(Filename.data());
2133 HeaderFileInfoTrait::key_type Key = {
2134 Filename, File->getSize(), getTimestampForOutput(File)
2136 HeaderFileInfoTrait::data_type Data = {
2137 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2139 Generator.insert(Key, Data, GeneratorTrait);
2140 ++NumHeaderSearchEntries;
2143 // Create the on-disk hash table in a buffer.
2144 SmallString<4096> TableData;
2145 uint32_t BucketOffset;
2147 using namespace llvm::support;
2149 llvm::raw_svector_ostream Out(TableData);
2150 // Make sure that no bucket is at offset 0
2151 endian::Writer<little>(Out).write<uint32_t>(0);
2152 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2155 // Create a blob abbreviation
2156 using namespace llvm;
2158 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2159 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2160 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2161 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2162 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2164 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2166 // Write the header search table
2167 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2168 NumHeaderSearchEntries, TableData.size()};
2169 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2170 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2172 // Free all of the strings we had to duplicate.
2173 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2174 free(const_cast<char *>(SavedStrings[I]));
2177 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2178 unsigned SLocBufferBlobCompressedAbbrv,
2179 unsigned SLocBufferBlobAbbrv) {
2180 using RecordDataType = ASTWriter::RecordData::value_type;
2182 // Compress the buffer if possible. We expect that almost all PCM
2183 // consumers will not want its contents.
2184 SmallString<0> CompressedBuffer;
2185 if (llvm::zlib::isAvailable()) {
2186 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2188 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2190 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2194 llvm::consumeError(std::move(E));
2197 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2198 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2201 /// \brief Writes the block containing the serialized form of the
2204 /// TODO: We should probably use an on-disk hash table (stored in a
2205 /// blob), indexed based on the file name, so that we only create
2206 /// entries for files that we actually need. In the common case (no
2207 /// errors), we probably won't have to create file entries for any of
2208 /// the files in the AST.
2209 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2210 const Preprocessor &PP) {
2213 // Enter the source manager block.
2214 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2216 // Abbreviations for the various kinds of source-location entries.
2217 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2218 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2219 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2220 unsigned SLocBufferBlobCompressedAbbrv =
2221 CreateSLocBufferBlobAbbrev(Stream, true);
2222 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2224 // Write out the source location entry table. We skip the first
2225 // entry, which is always the same dummy entry.
2226 std::vector<uint32_t> SLocEntryOffsets;
2227 RecordData PreloadSLocs;
2228 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2229 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2231 // Get this source location entry.
2232 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2233 FileID FID = FileID::get(I);
2234 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2236 // Record the offset of this source-location entry.
2237 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2239 // Figure out which record code to use.
2241 if (SLoc->isFile()) {
2242 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2243 if (Cache->OrigEntry) {
2244 Code = SM_SLOC_FILE_ENTRY;
2246 Code = SM_SLOC_BUFFER_ENTRY;
2248 Code = SM_SLOC_EXPANSION_ENTRY;
2250 Record.push_back(Code);
2252 // Starting offset of this entry within this module, so skip the dummy.
2253 Record.push_back(SLoc->getOffset() - 2);
2254 if (SLoc->isFile()) {
2255 const SrcMgr::FileInfo &File = SLoc->getFile();
2256 AddSourceLocation(File.getIncludeLoc(), Record);
2257 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2258 Record.push_back(File.hasLineDirectives());
2260 const SrcMgr::ContentCache *Content = File.getContentCache();
2261 bool EmitBlob = false;
2262 if (Content->OrigEntry) {
2263 assert(Content->OrigEntry == Content->ContentsEntry &&
2264 "Writing to AST an overridden file is not supported");
2266 // The source location entry is a file. Emit input file ID.
2267 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2268 Record.push_back(InputFileIDs[Content->OrigEntry]);
2270 Record.push_back(File.NumCreatedFIDs);
2272 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2273 if (FDI != FileDeclIDs.end()) {
2274 Record.push_back(FDI->second->FirstDeclIndex);
2275 Record.push_back(FDI->second->DeclIDs.size());
2277 Record.push_back(0);
2278 Record.push_back(0);
2281 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2283 if (Content->BufferOverridden || Content->IsTransient)
2286 // The source location entry is a buffer. The blob associated
2287 // with this entry contains the contents of the buffer.
2289 // We add one to the size so that we capture the trailing NULL
2290 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2291 // the reader side).
2292 const llvm::MemoryBuffer *Buffer
2293 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2294 StringRef Name = Buffer->getBufferIdentifier();
2295 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2296 StringRef(Name.data(), Name.size() + 1));
2299 if (Name == "<built-in>")
2300 PreloadSLocs.push_back(SLocEntryOffsets.size());
2304 // Include the implicit terminating null character in the on-disk buffer
2305 // if we're writing it uncompressed.
2306 const llvm::MemoryBuffer *Buffer =
2307 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2308 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2309 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2310 SLocBufferBlobAbbrv);
2313 // The source location entry is a macro expansion.
2314 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2315 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2316 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2317 AddSourceLocation(Expansion.isMacroArgExpansion()
2319 : Expansion.getExpansionLocEnd(),
2322 // Compute the token length for this macro expansion.
2323 unsigned NextOffset = SourceMgr.getNextLocalOffset();
2325 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2326 Record.push_back(NextOffset - SLoc->getOffset() - 1);
2327 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2333 if (SLocEntryOffsets.empty())
2336 // Write the source-location offsets table into the AST block. This
2337 // table is used for lazily loading source-location information.
2338 using namespace llvm;
2340 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2341 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2344 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2345 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2347 RecordData::value_type Record[] = {
2348 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2349 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2350 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2351 bytes(SLocEntryOffsets));
2353 // Write the source location entry preloads array, telling the AST
2354 // reader which source locations entries it should load eagerly.
2355 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2357 // Write the line table. It depends on remapping working, so it must come
2358 // after the source location offsets.
2359 if (SourceMgr.hasLineTable()) {
2360 LineTableInfo &LineTable = SourceMgr.getLineTable();
2364 // Emit the needed file names.
2365 llvm::DenseMap<int, int> FilenameMap;
2366 FilenameMap[-1] = -1; // For unspecified filenames.
2367 for (const auto &L : LineTable) {
2370 for (auto &LE : L.second) {
2371 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2372 FilenameMap.size() - 1)).second)
2373 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2376 Record.push_back(0);
2378 // Emit the line entries
2379 for (const auto &L : LineTable) {
2380 // Only emit entries for local files.
2385 Record.push_back(L.first.ID);
2387 // Emit the line entries
2388 Record.push_back(L.second.size());
2389 for (const auto &LE : L.second) {
2390 Record.push_back(LE.FileOffset);
2391 Record.push_back(LE.LineNo);
2392 Record.push_back(FilenameMap[LE.FilenameID]);
2393 Record.push_back((unsigned)LE.FileKind);
2394 Record.push_back(LE.IncludeOffset);
2398 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2402 //===----------------------------------------------------------------------===//
2403 // Preprocessor Serialization
2404 //===----------------------------------------------------------------------===//
2406 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2407 const Preprocessor &PP) {
2408 if (MacroInfo *MI = MD->getMacroInfo())
2409 if (MI->isBuiltinMacro())
2413 SourceLocation Loc = MD->getLocation();
2414 if (Loc.isInvalid())
2416 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2423 /// \brief Writes the block containing the serialized form of the
2425 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2426 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2428 WritePreprocessorDetail(*PPRec);
2431 RecordData ModuleMacroRecord;
2433 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2434 if (PP.getCounterValue() != 0) {
2435 RecordData::value_type Record[] = {PP.getCounterValue()};
2436 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2439 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2441 auto SkipInfo = PP.getPreambleSkipInfo();
2442 if (SkipInfo.hasValue()) {
2443 Record.push_back(true);
2444 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2445 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2446 Record.push_back(SkipInfo->FoundNonSkipPortion);
2447 Record.push_back(SkipInfo->FoundElse);
2448 AddSourceLocation(SkipInfo->ElseLoc, Record);
2450 Record.push_back(false);
2452 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2453 AddSourceLocation(Cond.IfLoc, Record);
2454 Record.push_back(Cond.WasSkipping);
2455 Record.push_back(Cond.FoundNonSkip);
2456 Record.push_back(Cond.FoundElse);
2458 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2462 // Enter the preprocessor block.
2463 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2465 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2466 // FIXME: Include a location for the use, and say which one was used.
2467 if (PP.SawDateOrTime())
2468 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2470 // Loop over all the macro directives that are live at the end of the file,
2471 // emitting each to the PP section.
2473 // Construct the list of identifiers with macro directives that need to be
2475 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2476 for (auto &Id : PP.getIdentifierTable())
2477 if (Id.second->hadMacroDefinition() &&
2478 (!Id.second->isFromAST() ||
2479 Id.second->hasChangedSinceDeserialization()))
2480 MacroIdentifiers.push_back(Id.second);
2481 // Sort the set of macro definitions that need to be serialized by the
2482 // name of the macro, to provide a stable ordering.
2483 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2484 llvm::less_ptr<IdentifierInfo>());
2486 // Emit the macro directives as a list and associate the offset with the
2487 // identifier they belong to.
2488 for (const IdentifierInfo *Name : MacroIdentifiers) {
2489 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2490 auto StartOffset = Stream.GetCurrentBitNo();
2492 // Emit the macro directives in reverse source order.
2493 for (; MD; MD = MD->getPrevious()) {
2494 // Once we hit an ignored macro, we're done: the rest of the chain
2495 // will all be ignored macros.
2496 if (shouldIgnoreMacro(MD, IsModule, PP))
2499 AddSourceLocation(MD->getLocation(), Record);
2500 Record.push_back(MD->getKind());
2501 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2502 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2503 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2504 Record.push_back(VisMD->isPublic());
2508 // Write out any exported module macros.
2509 bool EmittedModuleMacros = false;
2510 // We write out exported module macros for PCH as well.
2511 auto Leafs = PP.getLeafModuleMacros(Name);
2512 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2513 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2514 while (!Worklist.empty()) {
2515 auto *Macro = Worklist.pop_back_val();
2517 // Emit a record indicating this submodule exports this macro.
2518 ModuleMacroRecord.push_back(
2519 getSubmoduleID(Macro->getOwningModule()));
2520 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2521 for (auto *M : Macro->overrides())
2522 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2524 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2525 ModuleMacroRecord.clear();
2527 // Enqueue overridden macros once we've visited all their ancestors.
2528 for (auto *M : Macro->overrides())
2529 if (++Visits[M] == M->getNumOverridingMacros())
2530 Worklist.push_back(M);
2532 EmittedModuleMacros = true;
2535 if (Record.empty() && !EmittedModuleMacros)
2538 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2539 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2543 /// \brief Offsets of each of the macros into the bitstream, indexed by
2544 /// the local macro ID
2546 /// For each identifier that is associated with a macro, this map
2547 /// provides the offset into the bitstream where that macro is
2549 std::vector<uint32_t> MacroOffsets;
2551 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2552 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2553 MacroInfo *MI = MacroInfosToEmit[I].MI;
2554 MacroID ID = MacroInfosToEmit[I].ID;
2556 if (ID < FirstMacroID) {
2557 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2561 // Record the local offset of this macro.
2562 unsigned Index = ID - FirstMacroID;
2563 if (Index == MacroOffsets.size())
2564 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2566 if (Index > MacroOffsets.size())
2567 MacroOffsets.resize(Index + 1);
2569 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2572 AddIdentifierRef(Name, Record);
2573 AddSourceLocation(MI->getDefinitionLoc(), Record);
2574 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2575 Record.push_back(MI->isUsed());
2576 Record.push_back(MI->isUsedForHeaderGuard());
2578 if (MI->isObjectLike()) {
2579 Code = PP_MACRO_OBJECT_LIKE;
2581 Code = PP_MACRO_FUNCTION_LIKE;
2583 Record.push_back(MI->isC99Varargs());
2584 Record.push_back(MI->isGNUVarargs());
2585 Record.push_back(MI->hasCommaPasting());
2586 Record.push_back(MI->getNumParams());
2587 for (const IdentifierInfo *Param : MI->params())
2588 AddIdentifierRef(Param, Record);
2591 // If we have a detailed preprocessing record, record the macro definition
2592 // ID that corresponds to this macro.
2594 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2596 Stream.EmitRecord(Code, Record);
2599 // Emit the tokens array.
2600 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2601 // Note that we know that the preprocessor does not have any annotation
2602 // tokens in it because they are created by the parser, and thus can't
2603 // be in a macro definition.
2604 const Token &Tok = MI->getReplacementToken(TokNo);
2605 AddToken(Tok, Record);
2606 Stream.EmitRecord(PP_TOKEN, Record);
2614 // Write the offsets table for macro IDs.
2615 using namespace llvm;
2617 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2618 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2623 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2625 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2626 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2627 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2631 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2632 if (PPRec.local_begin() == PPRec.local_end())
2635 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2637 // Enter the preprocessor block.
2638 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2640 // If the preprocessor has a preprocessing record, emit it.
2641 unsigned NumPreprocessingRecords = 0;
2642 using namespace llvm;
2644 // Set up the abbreviation for
2645 unsigned InclusionAbbrev = 0;
2647 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2648 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2654 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2657 unsigned FirstPreprocessorEntityID
2658 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2659 + NUM_PREDEF_PP_ENTITY_IDS;
2660 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2662 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2663 EEnd = PPRec.local_end();
2665 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2668 PreprocessedEntityOffsets.push_back(
2669 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2671 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2672 // Record this macro definition's ID.
2673 MacroDefinitions[MD] = NextPreprocessorEntityID;
2675 AddIdentifierRef(MD->getName(), Record);
2676 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2680 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2681 Record.push_back(ME->isBuiltinMacro());
2682 if (ME->isBuiltinMacro())
2683 AddIdentifierRef(ME->getName(), Record);
2685 Record.push_back(MacroDefinitions[ME->getDefinition()]);
2686 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2690 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2691 Record.push_back(PPD_INCLUSION_DIRECTIVE);
2692 Record.push_back(ID->getFileName().size());
2693 Record.push_back(ID->wasInQuotes());
2694 Record.push_back(static_cast<unsigned>(ID->getKind()));
2695 Record.push_back(ID->importedModule());
2696 SmallString<64> Buffer;
2697 Buffer += ID->getFileName();
2698 // Check that the FileEntry is not null because it was not resolved and
2699 // we create a PCH even with compiler errors.
2701 Buffer += ID->getFile()->getName();
2702 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2706 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2710 // Write the offsets table for the preprocessing record.
2711 if (NumPreprocessingRecords > 0) {
2712 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2714 // Write the offsets table for identifier IDs.
2715 using namespace llvm;
2717 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2718 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2721 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2723 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2724 FirstPreprocessorEntityID -
2725 NUM_PREDEF_PP_ENTITY_IDS};
2726 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2727 bytes(PreprocessedEntityOffsets));
2731 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2735 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2736 if (Known != SubmoduleIDs.end())
2737 return Known->second;
2739 auto *Top = Mod->getTopLevelModule();
2740 if (Top != WritingModule &&
2741 (getLangOpts().CompilingPCH ||
2742 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2745 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2748 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2749 // FIXME: This can easily happen, if we have a reference to a submodule that
2750 // did not result in us loading a module file for that submodule. For
2751 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2752 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2753 assert((ID || !Mod) &&
2754 "asked for module ID for non-local, non-imported module");
2758 /// \brief Compute the number of modules within the given tree (including the
2760 static unsigned getNumberOfModules(Module *Mod) {
2761 unsigned ChildModules = 0;
2762 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2763 Sub != SubEnd; ++Sub)
2764 ChildModules += getNumberOfModules(*Sub);
2766 return ChildModules + 1;
2769 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2770 // Enter the submodule description block.
2771 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2773 // Write the abbreviations needed for the submodules block.
2774 using namespace llvm;
2776 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2777 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2780 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2781 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2782 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2783 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2787 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2788 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2790 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2792 Abbrev = std::make_shared<BitCodeAbbrev>();
2793 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2795 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2797 Abbrev = std::make_shared<BitCodeAbbrev>();
2798 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2800 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2802 Abbrev = std::make_shared<BitCodeAbbrev>();
2803 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2805 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2807 Abbrev = std::make_shared<BitCodeAbbrev>();
2808 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2810 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2812 Abbrev = std::make_shared<BitCodeAbbrev>();
2813 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2816 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2818 Abbrev = std::make_shared<BitCodeAbbrev>();
2819 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2821 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2823 Abbrev = std::make_shared<BitCodeAbbrev>();
2824 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2826 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2828 Abbrev = std::make_shared<BitCodeAbbrev>();
2829 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2831 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2833 Abbrev = std::make_shared<BitCodeAbbrev>();
2834 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2836 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2838 Abbrev = std::make_shared<BitCodeAbbrev>();
2839 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2842 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2844 Abbrev = std::make_shared<BitCodeAbbrev>();
2845 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2847 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2849 Abbrev = std::make_shared<BitCodeAbbrev>();
2850 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2853 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2855 Abbrev = std::make_shared<BitCodeAbbrev>();
2856 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2858 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2860 // Write the submodule metadata block.
2861 RecordData::value_type Record[] = {
2862 getNumberOfModules(WritingModule),
2863 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2864 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2866 // Write all of the submodules.
2867 std::queue<Module *> Q;
2868 Q.push(WritingModule);
2869 while (!Q.empty()) {
2870 Module *Mod = Q.front();
2872 unsigned ID = getSubmoduleID(Mod);
2874 uint64_t ParentID = 0;
2876 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2877 ParentID = SubmoduleIDs[Mod->Parent];
2880 // Emit the definition of the block.
2882 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2885 (RecordData::value_type)Mod->Kind,
2890 Mod->InferSubmodules,
2891 Mod->InferExplicitSubmodules,
2892 Mod->InferExportWildcard,
2893 Mod->ConfigMacrosExhaustive};
2894 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2897 // Emit the requirements.
2898 for (const auto &R : Mod->Requirements) {
2899 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2900 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2903 // Emit the umbrella header, if there is one.
2904 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2905 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2906 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2907 UmbrellaHeader.NameAsWritten);
2908 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2909 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2910 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2911 UmbrellaDir.NameAsWritten);
2914 // Emit the headers.
2916 unsigned RecordKind;
2918 Module::HeaderKind HeaderKind;
2920 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2921 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2922 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2923 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2924 Module::HK_PrivateTextual},
2925 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2927 for (auto &HL : HeaderLists) {
2928 RecordData::value_type Record[] = {HL.RecordKind};
2929 for (auto &H : Mod->Headers[HL.HeaderKind])
2930 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2933 // Emit the top headers.
2935 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2936 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2937 for (auto *H : TopHeaders)
2938 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2941 // Emit the imports.
2942 if (!Mod->Imports.empty()) {
2944 for (auto *I : Mod->Imports)
2945 Record.push_back(getSubmoduleID(I));
2946 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2949 // Emit the exports.
2950 if (!Mod->Exports.empty()) {
2952 for (const auto &E : Mod->Exports) {
2953 // FIXME: This may fail; we don't require that all exported modules
2954 // are local or imported.
2955 Record.push_back(getSubmoduleID(E.getPointer()));
2956 Record.push_back(E.getInt());
2958 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2961 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2962 // Might be unnecessary as use declarations are only used to build the
2965 // Emit the link libraries.
2966 for (const auto &LL : Mod->LinkLibraries) {
2967 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2969 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2972 // Emit the conflicts.
2973 for (const auto &C : Mod->Conflicts) {
2974 // FIXME: This may fail; we don't require that all conflicting modules
2975 // are local or imported.
2976 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2977 getSubmoduleID(C.Other)};
2978 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2981 // Emit the configuration macros.
2982 for (const auto &CM : Mod->ConfigMacros) {
2983 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2984 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2987 // Emit the initializers, if any.
2989 for (Decl *D : Context->getModuleInitializers(Mod))
2990 Inits.push_back(GetDeclRef(D));
2992 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2994 // Emit the name of the re-exported module, if any.
2995 if (!Mod->ExportAsModule.empty()) {
2996 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2997 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3000 // Queue up the submodules of this module.
3001 for (auto *M : Mod->submodules())
3007 assert((NextSubmoduleID - FirstSubmoduleID ==
3008 getNumberOfModules(WritingModule)) &&
3009 "Wrong # of submodules; found a reference to a non-local, "
3010 "non-imported submodule?");
3013 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3015 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3017 unsigned CurrID = 0;
3020 auto EncodeDiagStateFlags =
3021 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3022 unsigned Result = (unsigned)DS->ExtBehavior;
3024 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3025 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3026 (unsigned)DS->SuppressSystemWarnings})
3027 Result = (Result << 1) | Val;
3031 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3032 Record.push_back(Flags);
3034 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3035 bool IncludeNonPragmaStates) {
3036 // Ensure that the diagnostic state wasn't modified since it was created.
3037 // We will not correctly round-trip this information otherwise.
3038 assert(Flags == EncodeDiagStateFlags(State) &&
3039 "diag state flags vary in single AST file");
3041 unsigned &DiagStateID = DiagStateIDMap[State];
3042 Record.push_back(DiagStateID);
3044 if (DiagStateID == 0) {
3045 DiagStateID = ++CurrID;
3047 // Add a placeholder for the number of mappings.
3048 auto SizeIdx = Record.size();
3049 Record.emplace_back();
3050 for (const auto &I : *State) {
3051 if (I.second.isPragma() || IncludeNonPragmaStates) {
3052 Record.push_back(I.first);
3053 Record.push_back(I.second.serialize());
3056 // Update the placeholder.
3057 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3061 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3063 // Reserve a spot for the number of locations with state transitions.
3064 auto NumLocationsIdx = Record.size();
3065 Record.emplace_back();
3067 // Emit the state transitions.
3068 unsigned NumLocations = 0;
3069 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3070 if (!FileIDAndFile.first.isValid() ||
3071 !FileIDAndFile.second.HasLocalTransitions)
3074 AddSourceLocation(Diag.SourceMgr->getLocForStartOfFile(FileIDAndFile.first),
3076 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3077 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3078 Record.push_back(StatePoint.Offset);
3079 AddDiagState(StatePoint.State, false);
3083 // Backpatch the number of locations.
3084 Record[NumLocationsIdx] = NumLocations;
3086 // Emit CurDiagStateLoc. Do it last in order to match source order.
3088 // This also protects against a hypothetical corner case with simulating
3089 // -Werror settings for implicit modules in the ASTReader, where reading
3090 // CurDiagState out of context could change whether warning pragmas are
3091 // treated as errors.
3092 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3093 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3095 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3098 //===----------------------------------------------------------------------===//
3099 // Type Serialization
3100 //===----------------------------------------------------------------------===//
3102 /// \brief Write the representation of a type to the AST stream.
3103 void ASTWriter::WriteType(QualType T) {
3104 TypeIdx &IdxRef = TypeIdxs[T];
3105 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3106 IdxRef = TypeIdx(NextTypeID++);
3107 TypeIdx Idx = IdxRef;
3109 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3113 // Emit the type's representation.
3114 ASTTypeWriter W(*this, Record);
3116 uint64_t Offset = W.Emit();
3118 // Record the offset for this type.
3119 unsigned Index = Idx.getIndex() - FirstTypeID;
3120 if (TypeOffsets.size() == Index)
3121 TypeOffsets.push_back(Offset);
3122 else if (TypeOffsets.size() < Index) {
3123 TypeOffsets.resize(Index + 1);
3124 TypeOffsets[Index] = Offset;
3126 llvm_unreachable("Types emitted in wrong order");
3130 //===----------------------------------------------------------------------===//
3131 // Declaration Serialization
3132 //===----------------------------------------------------------------------===//
3134 /// \brief Write the block containing all of the declaration IDs
3135 /// lexically declared within the given DeclContext.
3137 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3138 /// bistream, or 0 if no block was written.
3139 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3141 if (DC->decls_empty())
3144 uint64_t Offset = Stream.GetCurrentBitNo();
3145 SmallVector<uint32_t, 128> KindDeclPairs;
3146 for (const auto *D : DC->decls()) {
3147 KindDeclPairs.push_back(D->getKind());
3148 KindDeclPairs.push_back(GetDeclRef(D));
3151 ++NumLexicalDeclContexts;
3152 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3153 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3154 bytes(KindDeclPairs));
3158 void ASTWriter::WriteTypeDeclOffsets() {
3159 using namespace llvm;
3161 // Write the type offsets array
3162 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3163 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3166 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3167 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3169 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3170 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3171 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3174 // Write the declaration offsets array
3175 Abbrev = std::make_shared<BitCodeAbbrev>();
3176 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3178 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3180 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3182 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3183 FirstDeclID - NUM_PREDEF_DECL_IDS};
3184 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3188 void ASTWriter::WriteFileDeclIDsMap() {
3189 using namespace llvm;
3191 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3192 FileDeclIDs.begin(), FileDeclIDs.end());
3193 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
3194 llvm::less_first());
3196 // Join the vectors of DeclIDs from all files.
3197 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3198 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3199 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3200 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3201 for (auto &LocDeclEntry : Info.DeclIDs)
3202 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3205 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3206 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3207 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3208 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3209 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3210 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3211 FileGroupedDeclIDs.size()};
3212 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3215 void ASTWriter::WriteComments() {
3216 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3217 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
3219 for (const auto *I : RawComments) {
3221 AddSourceRange(I->getSourceRange(), Record);
3222 Record.push_back(I->getKind());
3223 Record.push_back(I->isTrailingComment());
3224 Record.push_back(I->isAlmostTrailingComment());
3225 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3230 //===----------------------------------------------------------------------===//
3231 // Global Method Pool and Selector Serialization
3232 //===----------------------------------------------------------------------===//
3236 // Trait used for the on-disk hash table used in the method pool.
3237 class ASTMethodPoolTrait {
3241 using key_type = Selector;
3242 using key_type_ref = key_type;
3246 ObjCMethodList Instance, Factory;
3248 using data_type_ref = const data_type &;
3250 using hash_value_type = unsigned;
3251 using offset_type = unsigned;
3253 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3255 static hash_value_type ComputeHash(Selector Sel) {
3256 return serialization::ComputeHash(Sel);
3259 std::pair<unsigned, unsigned>
3260 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3261 data_type_ref Methods) {
3262 using namespace llvm::support;
3264 endian::Writer<little> LE(Out);
3265 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3266 LE.write<uint16_t>(KeyLen);
3267 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3268 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3269 Method = Method->getNext())
3270 if (Method->getMethod())
3272 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3273 Method = Method->getNext())
3274 if (Method->getMethod())
3276 LE.write<uint16_t>(DataLen);
3277 return std::make_pair(KeyLen, DataLen);
3280 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3281 using namespace llvm::support;
3283 endian::Writer<little> LE(Out);
3284 uint64_t Start = Out.tell();
3285 assert((Start >> 32) == 0 && "Selector key offset too large");
3286 Writer.SetSelectorOffset(Sel, Start);
3287 unsigned N = Sel.getNumArgs();
3288 LE.write<uint16_t>(N);
3291 for (unsigned I = 0; I != N; ++I)
3293 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3296 void EmitData(raw_ostream& Out, key_type_ref,
3297 data_type_ref Methods, unsigned DataLen) {
3298 using namespace llvm::support;
3300 endian::Writer<little> LE(Out);
3301 uint64_t Start = Out.tell(); (void)Start;
3302 LE.write<uint32_t>(Methods.ID);
3303 unsigned NumInstanceMethods = 0;
3304 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3305 Method = Method->getNext())
3306 if (Method->getMethod())
3307 ++NumInstanceMethods;
3309 unsigned NumFactoryMethods = 0;
3310 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3311 Method = Method->getNext())
3312 if (Method->getMethod())
3313 ++NumFactoryMethods;
3315 unsigned InstanceBits = Methods.Instance.getBits();
3316 assert(InstanceBits < 4);
3317 unsigned InstanceHasMoreThanOneDeclBit =
3318 Methods.Instance.hasMoreThanOneDecl();
3319 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3320 (InstanceHasMoreThanOneDeclBit << 2) |
3322 unsigned FactoryBits = Methods.Factory.getBits();
3323 assert(FactoryBits < 4);
3324 unsigned FactoryHasMoreThanOneDeclBit =
3325 Methods.Factory.hasMoreThanOneDecl();
3326 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3327 (FactoryHasMoreThanOneDeclBit << 2) |
3329 LE.write<uint16_t>(FullInstanceBits);
3330 LE.write<uint16_t>(FullFactoryBits);
3331 for (const ObjCMethodList *Method = &Methods.Instance; Method;
3332 Method = Method->getNext())
3333 if (Method->getMethod())
3334 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3335 for (const ObjCMethodList *Method = &Methods.Factory; Method;
3336 Method = Method->getNext())
3337 if (Method->getMethod())
3338 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3340 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3346 /// \brief Write ObjC data: selectors and the method pool.
3348 /// The method pool contains both instance and factory methods, stored
3349 /// in an on-disk hash table indexed by the selector. The hash table also
3350 /// contains an empty entry for every other selector known to Sema.
3351 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3352 using namespace llvm;
3354 // Do we have to do anything at all?
3355 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3357 unsigned NumTableEntries = 0;
3358 // Create and write out the blob that contains selectors and the method pool.
3360 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3361 ASTMethodPoolTrait Trait(*this);
3363 // Create the on-disk hash table representation. We walk through every
3364 // selector we've seen and look it up in the method pool.
3365 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3366 for (auto &SelectorAndID : SelectorIDs) {
3367 Selector S = SelectorAndID.first;
3368 SelectorID ID = SelectorAndID.second;
3369 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3370 ASTMethodPoolTrait::data_type Data = {
3375 if (F != SemaRef.MethodPool.end()) {
3376 Data.Instance = F->second.first;
3377 Data.Factory = F->second.second;
3379 // Only write this selector if it's not in an existing AST or something
3381 if (Chain && ID < FirstSelectorID) {
3382 // Selector already exists. Did it change?
3383 bool changed = false;
3384 for (ObjCMethodList *M = &Data.Instance;
3385 !changed && M && M->getMethod(); M = M->getNext()) {
3386 if (!M->getMethod()->isFromASTFile())
3389 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3391 if (!M->getMethod()->isFromASTFile())
3396 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3397 // A new method pool entry.
3400 Generator.insert(S, Data, Trait);
3403 // Create the on-disk hash table in a buffer.
3404 SmallString<4096> MethodPool;
3405 uint32_t BucketOffset;
3407 using namespace llvm::support;
3409 ASTMethodPoolTrait Trait(*this);
3410 llvm::raw_svector_ostream Out(MethodPool);
3411 // Make sure that no bucket is at offset 0
3412 endian::Writer<little>(Out).write<uint32_t>(0);
3413 BucketOffset = Generator.Emit(Out, Trait);
3416 // Create a blob abbreviation
3417 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3418 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3422 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3424 // Write the method pool
3426 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3428 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3431 // Create a blob abbreviation for the selector table offsets.
3432 Abbrev = std::make_shared<BitCodeAbbrev>();
3433 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3437 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3439 // Write the selector offsets table.
3441 RecordData::value_type Record[] = {
3442 SELECTOR_OFFSETS, SelectorOffsets.size(),
3443 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3444 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3445 bytes(SelectorOffsets));
3450 /// \brief Write the selectors referenced in @selector expression into AST file.
3451 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3452 using namespace llvm;
3454 if (SemaRef.ReferencedSelectors.empty())
3458 ASTRecordWriter Writer(*this, Record);
3460 // Note: this writes out all references even for a dependent AST. But it is
3461 // very tricky to fix, and given that @selector shouldn't really appear in
3462 // headers, probably not worth it. It's not a correctness issue.
3463 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3464 Selector Sel = SelectorAndLocation.first;
3465 SourceLocation Loc = SelectorAndLocation.second;
3466 Writer.AddSelectorRef(Sel);
3467 Writer.AddSourceLocation(Loc);
3469 Writer.Emit(REFERENCED_SELECTOR_POOL);
3472 //===----------------------------------------------------------------------===//
3473 // Identifier Table Serialization
3474 //===----------------------------------------------------------------------===//
3476 /// Determine the declaration that should be put into the name lookup table to
3477 /// represent the given declaration in this module. This is usually D itself,
3478 /// but if D was imported and merged into a local declaration, we want the most
3479 /// recent local declaration instead. The chosen declaration will be the most
3480 /// recent declaration in any module that imports this one.
3481 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3483 if (!LangOpts.Modules || !D->isFromASTFile())
3486 if (Decl *Redecl = D->getPreviousDecl()) {
3487 // For Redeclarable decls, a prior declaration might be local.
3488 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3489 // If we find a local decl, we're done.
3490 if (!Redecl->isFromASTFile()) {
3491 // Exception: in very rare cases (for injected-class-names), not all
3492 // redeclarations are in the same semantic context. Skip ones in a
3493 // different context. They don't go in this lookup table at all.
3494 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3495 D->getDeclContext()->getRedeclContext()))
3497 return cast<NamedDecl>(Redecl);
3500 // If we find a decl from a (chained-)PCH stop since we won't find a
3502 if (Redecl->getOwningModuleID() == 0)
3505 } else if (Decl *First = D->getCanonicalDecl()) {
3506 // For Mergeable decls, the first decl might be local.
3507 if (!First->isFromASTFile())
3508 return cast<NamedDecl>(First);
3511 // All declarations are imported. Our most recent declaration will also be
3512 // the most recent one in anyone who imports us.
3518 class ASTIdentifierTableTrait {
3521 IdentifierResolver &IdResolver;
3524 ASTWriter::RecordData *InterestingIdentifierOffsets;
3526 /// \brief Determines whether this is an "interesting" identifier that needs a
3527 /// full IdentifierInfo structure written into the hash table. Notably, this
3528 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3530 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3533 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3534 II->hasRevertedTokenIDToIdentifier() ||
3535 (NeedDecls && II->getFETokenInfo<void>()))
3542 using key_type = IdentifierInfo *;
3543 using key_type_ref = key_type;
3545 using data_type = IdentID;
3546 using data_type_ref = data_type;
3548 using hash_value_type = unsigned;
3549 using offset_type = unsigned;
3551 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3552 IdentifierResolver &IdResolver, bool IsModule,
3553 ASTWriter::RecordData *InterestingIdentifierOffsets)
3554 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3555 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3556 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3558 bool needDecls() const { return NeedDecls; }
3560 static hash_value_type ComputeHash(const IdentifierInfo* II) {
3561 return llvm::HashString(II->getName());
3564 bool isInterestingIdentifier(const IdentifierInfo *II) {
3565 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3566 return isInterestingIdentifier(II, MacroOffset);
3569 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3570 return isInterestingIdentifier(II, 0);
3573 std::pair<unsigned, unsigned>
3574 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3575 unsigned KeyLen = II->getLength() + 1;
3576 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3577 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3578 if (isInterestingIdentifier(II, MacroOffset)) {
3579 DataLen += 2; // 2 bytes for builtin ID
3580 DataLen += 2; // 2 bytes for flags
3582 DataLen += 4; // MacroDirectives offset.
3585 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3586 DEnd = IdResolver.end();
3592 using namespace llvm::support;
3594 endian::Writer<little> LE(Out);
3596 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3597 LE.write<uint16_t>(DataLen);
3598 // We emit the key length after the data length so that every
3599 // string is preceded by a 16-bit length. This matches the PTH
3600 // format for storing identifiers.
3601 LE.write<uint16_t>(KeyLen);
3602 return std::make_pair(KeyLen, DataLen);
3605 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3607 // Record the location of the key data. This is used when generating
3608 // the mapping from persistent IDs to strings.
3609 Writer.SetIdentifierOffset(II, Out.tell());
3611 // Emit the offset of the key/data length information to the interesting
3612 // identifiers table if necessary.
3613 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3614 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3616 Out.write(II->getNameStart(), KeyLen);
3619 void EmitData(raw_ostream& Out, IdentifierInfo* II,
3620 IdentID ID, unsigned) {
3621 using namespace llvm::support;
3623 endian::Writer<little> LE(Out);
3625 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3626 if (!isInterestingIdentifier(II, MacroOffset)) {
3627 LE.write<uint32_t>(ID << 1);
3631 LE.write<uint32_t>((ID << 1) | 0x01);
3632 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3633 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3634 LE.write<uint16_t>(Bits);
3636 bool HadMacroDefinition = MacroOffset != 0;
3637 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3638 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3639 Bits = (Bits << 1) | unsigned(II->isPoisoned());
3640 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3641 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3642 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3643 LE.write<uint16_t>(Bits);
3645 if (HadMacroDefinition)
3646 LE.write<uint32_t>(MacroOffset);
3649 // Emit the declaration IDs in reverse order, because the
3650 // IdentifierResolver provides the declarations as they would be
3651 // visible (e.g., the function "stat" would come before the struct
3652 // "stat"), but the ASTReader adds declarations to the end of the list
3653 // (so we need to see the struct "stat" before the function "stat").
3654 // Only emit declarations that aren't from a chained PCH, though.
3655 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3657 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3658 DEnd = Decls.rend();
3661 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3668 /// \brief Write the identifier table into the AST file.
3670 /// The identifier table consists of a blob containing string data
3671 /// (the actual identifiers themselves) and a separate "offsets" index
3672 /// that maps identifier IDs to locations within the blob.
3673 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3674 IdentifierResolver &IdResolver,
3676 using namespace llvm;
3678 RecordData InterestingIdents;
3680 // Create and write out the blob that contains the identifier
3683 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3684 ASTIdentifierTableTrait Trait(
3685 *this, PP, IdResolver, IsModule,
3686 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3688 // Look for any identifiers that were named while processing the
3689 // headers, but are otherwise not needed. We add these to the hash
3690 // table to enable checking of the predefines buffer in the case
3691 // where the user adds new macro definitions when building the AST
3693 SmallVector<const IdentifierInfo *, 128> IIs;
3694 for (const auto &ID : PP.getIdentifierTable())
3695 IIs.push_back(ID.second);
3696 // Sort the identifiers lexicographically before getting them references so
3697 // that their order is stable.
3698 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3699 for (const IdentifierInfo *II : IIs)
3700 if (Trait.isInterestingNonMacroIdentifier(II))
3701 getIdentifierRef(II);
3703 // Create the on-disk hash table representation. We only store offsets
3704 // for identifiers that appear here for the first time.
3705 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3706 for (auto IdentIDPair : IdentifierIDs) {
3707 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3708 IdentID ID = IdentIDPair.second;
3709 assert(II && "NULL identifier in identifier table");
3710 // Write out identifiers if either the ID is local or the identifier has
3711 // changed since it was loaded.
3712 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3713 || II->hasChangedSinceDeserialization() ||
3714 (Trait.needDecls() &&
3715 II->hasFETokenInfoChangedSinceDeserialization()))
3716 Generator.insert(II, ID, Trait);
3719 // Create the on-disk hash table in a buffer.
3720 SmallString<4096> IdentifierTable;
3721 uint32_t BucketOffset;
3723 using namespace llvm::support;
3725 llvm::raw_svector_ostream Out(IdentifierTable);
3726 // Make sure that no bucket is at offset 0
3727 endian::Writer<little>(Out).write<uint32_t>(0);
3728 BucketOffset = Generator.Emit(Out, Trait);
3731 // Create a blob abbreviation
3732 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3733 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3736 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3738 // Write the identifier table
3739 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3740 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3743 // Write the offsets table for identifier IDs.
3744 auto Abbrev = std::make_shared<BitCodeAbbrev>();
3745 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3749 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3752 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3753 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3756 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3757 IdentifierOffsets.size(),
3758 FirstIdentID - NUM_PREDEF_IDENT_IDS};
3759 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3760 bytes(IdentifierOffsets));
3762 // In C++, write the list of interesting identifiers (those that are
3763 // defined as macros, poisoned, or similar unusual things).
3764 if (!InterestingIdents.empty())
3765 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3768 //===----------------------------------------------------------------------===//
3769 // DeclContext's Name Lookup Table Serialization
3770 //===----------------------------------------------------------------------===//
3774 // Trait used for the on-disk hash table used in the method pool.
3775 class ASTDeclContextNameLookupTrait {
3777 llvm::SmallVector<DeclID, 64> DeclIDs;
3780 using key_type = DeclarationNameKey;
3781 using key_type_ref = key_type;
3783 /// A start and end index into DeclIDs, representing a sequence of decls.
3784 using data_type = std::pair<unsigned, unsigned>;
3785 using data_type_ref = const data_type &;
3787 using hash_value_type = unsigned;
3788 using offset_type = unsigned;
3790 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3792 template<typename Coll>
3793 data_type getData(const Coll &Decls) {
3794 unsigned Start = DeclIDs.size();
3795 for (NamedDecl *D : Decls) {
3797 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3799 return std::make_pair(Start, DeclIDs.size());
3802 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3803 unsigned Start = DeclIDs.size();
3804 for (auto ID : FromReader)
3805 DeclIDs.push_back(ID);
3806 return std::make_pair(Start, DeclIDs.size());
3809 static bool EqualKey(key_type_ref a, key_type_ref b) {
3813 hash_value_type ComputeHash(DeclarationNameKey Name) {
3814 return Name.getHash();
3817 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3818 assert(Writer.hasChain() &&
3819 "have reference to loaded module file but no chain?");
3821 using namespace llvm::support;
3823 endian::Writer<little>(Out)
3824 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3827 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3828 DeclarationNameKey Name,
3829 data_type_ref Lookup) {
3830 using namespace llvm::support;
3832 endian::Writer<little> LE(Out);
3833 unsigned KeyLen = 1;
3834 switch (Name.getKind()) {
3835 case DeclarationName::Identifier:
3836 case DeclarationName::ObjCZeroArgSelector:
3837 case DeclarationName::ObjCOneArgSelector:
3838 case DeclarationName::ObjCMultiArgSelector:
3839 case DeclarationName::CXXLiteralOperatorName:
3840 case DeclarationName::CXXDeductionGuideName:
3843 case DeclarationName::CXXOperatorName:
3846 case DeclarationName::CXXConstructorName:
3847 case DeclarationName::CXXDestructorName:
3848 case DeclarationName::CXXConversionFunctionName:
3849 case DeclarationName::CXXUsingDirective:
3852 LE.write<uint16_t>(KeyLen);
3854 // 4 bytes for each DeclID.
3855 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3856 assert(uint16_t(DataLen) == DataLen &&
3857 "too many decls for serialized lookup result");
3858 LE.write<uint16_t>(DataLen);
3860 return std::make_pair(KeyLen, DataLen);
3863 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3864 using namespace llvm::support;
3866 endian::Writer<little> LE(Out);
3867 LE.write<uint8_t>(Name.getKind());
3868 switch (Name.getKind()) {
3869 case DeclarationName::Identifier:
3870 case DeclarationName::CXXLiteralOperatorName:
3871 case DeclarationName::CXXDeductionGuideName:
3872 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3874 case DeclarationName::ObjCZeroArgSelector:
3875 case DeclarationName::ObjCOneArgSelector:
3876 case DeclarationName::ObjCMultiArgSelector:
3877 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3879 case DeclarationName::CXXOperatorName:
3880 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3881 "Invalid operator?");
3882 LE.write<uint8_t>(Name.getOperatorKind());
3884 case DeclarationName::CXXConstructorName:
3885 case DeclarationName::CXXDestructorName:
3886 case DeclarationName::CXXConversionFunctionName:
3887 case DeclarationName::CXXUsingDirective:
3891 llvm_unreachable("Invalid name kind?");
3894 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3896 using namespace llvm::support;
3898 endian::Writer<little> LE(Out);
3899 uint64_t Start = Out.tell(); (void)Start;
3900 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3901 LE.write<uint32_t>(DeclIDs[I]);
3902 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3908 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3910 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3913 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3915 for (auto *D : Result.getLookupResult())
3916 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3923 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3924 llvm::SmallVectorImpl<char> &LookupTable) {
3925 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3926 !ConstDC->HasLazyExternalLexicalLookups &&
3927 "must call buildLookups first");
3929 // FIXME: We need to build the lookups table, which is logically const.
3930 auto *DC = const_cast<DeclContext*>(ConstDC);
3931 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3933 // Create the on-disk hash table representation.
3934 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3935 ASTDeclContextNameLookupTrait> Generator;
3936 ASTDeclContextNameLookupTrait Trait(*this);
3938 // The first step is to collect the declaration names which we need to
3939 // serialize into the name lookup table, and to collect them in a stable
3941 SmallVector<DeclarationName, 16> Names;
3943 // We also build up small sets of the constructor and conversion function
3944 // names which are visible.
3945 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3947 for (auto &Lookup : *DC->buildLookup()) {
3948 auto &Name = Lookup.first;
3949 auto &Result = Lookup.second;
3951 // If there are no local declarations in our lookup result, we
3952 // don't need to write an entry for the name at all. If we can't
3953 // write out a lookup set without performing more deserialization,
3954 // just skip this entry.
3955 if (isLookupResultExternal(Result, DC) &&
3956 isLookupResultEntirelyExternal(Result, DC))
3959 // We also skip empty results. If any of the results could be external and
3960 // the currently available results are empty, then all of the results are
3961 // external and we skip it above. So the only way we get here with an empty
3962 // results is when no results could have been external *and* we have
3963 // external results.
3965 // FIXME: While we might want to start emitting on-disk entries for negative
3966 // lookups into a decl context as an optimization, today we *have* to skip
3967 // them because there are names with empty lookup results in decl contexts
3968 // which we can't emit in any stable ordering: we lookup constructors and
3969 // conversion functions in the enclosing namespace scope creating empty
3970 // results for them. This in almost certainly a bug in Clang's name lookup,
3971 // but that is likely to be hard or impossible to fix and so we tolerate it
3972 // here by omitting lookups with empty results.
3973 if (Lookup.second.getLookupResult().empty())
3976 switch (Lookup.first.getNameKind()) {
3978 Names.push_back(Lookup.first);
3981 case DeclarationName::CXXConstructorName:
3982 assert(isa<CXXRecordDecl>(DC) &&
3983 "Cannot have a constructor name outside of a class!");
3984 ConstructorNameSet.insert(Name);
3987 case DeclarationName::CXXConversionFunctionName:
3988 assert(isa<CXXRecordDecl>(DC) &&
3989 "Cannot have a conversion function name outside of a class!");
3990 ConversionNameSet.insert(Name);
3995 // Sort the names into a stable order.
3996 std::sort(Names.begin(), Names.end());
3998 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3999 // We need to establish an ordering of constructor and conversion function
4000 // names, and they don't have an intrinsic ordering.
4002 // First we try the easy case by forming the current context's constructor
4003 // name and adding that name first. This is a very useful optimization to
4004 // avoid walking the lexical declarations in many cases, and it also
4005 // handles the only case where a constructor name can come from some other
4006 // lexical context -- when that name is an implicit constructor merged from
4007 // another declaration in the redecl chain. Any non-implicit constructor or
4008 // conversion function which doesn't occur in all the lexical contexts
4009 // would be an ODR violation.
4010 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4011 Context->getCanonicalType(Context->getRecordType(D)));
4012 if (ConstructorNameSet.erase(ImplicitCtorName))
4013 Names.push_back(ImplicitCtorName);
4015 // If we still have constructors or conversion functions, we walk all the
4016 // names in the decl and add the constructors and conversion functions
4017 // which are visible in the order they lexically occur within the context.
4018 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4019 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4020 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4021 auto Name = ChildND->getDeclName();
4022 switch (Name.getNameKind()) {
4026 case DeclarationName::CXXConstructorName:
4027 if (ConstructorNameSet.erase(Name))
4028 Names.push_back(Name);
4031 case DeclarationName::CXXConversionFunctionName:
4032 if (ConversionNameSet.erase(Name))
4033 Names.push_back(Name);
4037 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4041 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4042 "constructors by walking all the "
4043 "lexical members of the context.");
4044 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4045 "conversion functions by walking all "
4046 "the lexical members of the context.");
4049 // Next we need to do a lookup with each name into this decl context to fully
4050 // populate any results from external sources. We don't actually use the
4051 // results of these lookups because we only want to use the results after all
4052 // results have been loaded and the pointers into them will be stable.
4053 for (auto &Name : Names)
4056 // Now we need to insert the results for each name into the hash table. For
4057 // constructor names and conversion function names, we actually need to merge
4058 // all of the results for them into one list of results each and insert
4060 SmallVector<NamedDecl *, 8> ConstructorDecls;
4061 SmallVector<NamedDecl *, 8> ConversionDecls;
4063 // Now loop over the names, either inserting them or appending for the two
4065 for (auto &Name : Names) {
4066 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4068 switch (Name.getNameKind()) {
4070 Generator.insert(Name, Trait.getData(Result), Trait);
4073 case DeclarationName::CXXConstructorName:
4074 ConstructorDecls.append(Result.begin(), Result.end());
4077 case DeclarationName::CXXConversionFunctionName:
4078 ConversionDecls.append(Result.begin(), Result.end());
4083 // Handle our two special cases if we ended up having any. We arbitrarily use
4084 // the first declaration's name here because the name itself isn't part of
4085 // the key, only the kind of name is used.
4086 if (!ConstructorDecls.empty())
4087 Generator.insert(ConstructorDecls.front()->getDeclName(),
4088 Trait.getData(ConstructorDecls), Trait);
4089 if (!ConversionDecls.empty())
4090 Generator.insert(ConversionDecls.front()->getDeclName(),
4091 Trait.getData(ConversionDecls), Trait);
4093 // Create the on-disk hash table. Also emit the existing imported and
4094 // merged table if there is one.
4095 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4096 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4099 /// \brief Write the block containing all of the declaration IDs
4100 /// visible from the given DeclContext.
4102 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4103 /// bitstream, or 0 if no block was written.
4104 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4106 // If we imported a key declaration of this namespace, write the visible
4107 // lookup results as an update record for it rather than including them
4108 // on this declaration. We will only look at key declarations on reload.
4109 if (isa<NamespaceDecl>(DC) && Chain &&
4110 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4111 // Only do this once, for the first local declaration of the namespace.
4112 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4113 Prev = Prev->getPreviousDecl())
4114 if (!Prev->isFromASTFile())
4117 // Note that we need to emit an update record for the primary context.
4118 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4120 // Make sure all visible decls are written. They will be recorded later. We
4121 // do this using a side data structure so we can sort the names into
4122 // a deterministic order.
4123 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4124 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4127 LookupResults.reserve(Map->size());
4128 for (auto &Entry : *Map)
4129 LookupResults.push_back(
4130 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4133 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
4134 for (auto &NameAndResult : LookupResults) {
4135 DeclarationName Name = NameAndResult.first;
4136 DeclContext::lookup_result Result = NameAndResult.second;
4137 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4138 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4139 // We have to work around a name lookup bug here where negative lookup
4140 // results for these names get cached in namespace lookup tables (these
4141 // names should never be looked up in a namespace).
4142 assert(Result.empty() && "Cannot have a constructor or conversion "
4143 "function name in a namespace!");
4147 for (NamedDecl *ND : Result)
4148 if (!ND->isFromASTFile())
4155 if (DC->getPrimaryContext() != DC)
4158 // Skip contexts which don't support name lookup.
4159 if (!DC->isLookupContext())
4162 // If not in C++, we perform name lookup for the translation unit via the
4163 // IdentifierInfo chains, don't bother to build a visible-declarations table.
4164 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4167 // Serialize the contents of the mapping used for lookup. Note that,
4168 // although we have two very different code paths, the serialized
4169 // representation is the same for both cases: a declaration name,
4170 // followed by a size, followed by references to the visible
4171 // declarations that have that name.
4172 uint64_t Offset = Stream.GetCurrentBitNo();
4173 StoredDeclsMap *Map = DC->buildLookup();
4174 if (!Map || Map->empty())
4177 // Create the on-disk hash table in a buffer.
4178 SmallString<4096> LookupTable;
4179 GenerateNameLookupTable(DC, LookupTable);
4181 // Write the lookup table
4182 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4183 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4185 ++NumVisibleDeclContexts;
4189 /// \brief Write an UPDATE_VISIBLE block for the given context.
4191 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4192 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4193 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4194 /// enumeration members (in C++11).
4195 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4196 StoredDeclsMap *Map = DC->getLookupPtr();
4197 if (!Map || Map->empty())
4200 // Create the on-disk hash table in a buffer.
4201 SmallString<4096> LookupTable;
4202 GenerateNameLookupTable(DC, LookupTable);
4204 // If we're updating a namespace, select a key declaration as the key for the
4205 // update record; those are the only ones that will be checked on reload.
4206 if (isa<NamespaceDecl>(DC))
4207 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4209 // Write the lookup table
4210 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4211 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4214 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4215 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4216 RecordData::value_type Record[] = {Opts.getInt()};
4217 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4220 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4221 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4222 if (!SemaRef.Context.getLangOpts().OpenCL)
4225 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4227 for (const auto &I:Opts.OptMap) {
4228 AddString(I.getKey(), Record);
4229 auto V = I.getValue();
4230 Record.push_back(V.Supported ? 1 : 0);
4231 Record.push_back(V.Enabled ? 1 : 0);
4232 Record.push_back(V.Avail);
4233 Record.push_back(V.Core);
4235 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4238 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4239 if (!SemaRef.Context.getLangOpts().OpenCL)
4243 for (const auto &I : SemaRef.OpenCLTypeExtMap) {
4245 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
4246 Record.push_back(I.second.size());
4247 for (auto Ext : I.second)
4248 AddString(Ext, Record);
4250 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4253 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4254 if (!SemaRef.Context.getLangOpts().OpenCL)
4258 for (const auto &I : SemaRef.OpenCLDeclExtMap) {
4259 Record.push_back(getDeclID(I.first));
4260 Record.push_back(static_cast<unsigned>(I.second.size()));
4261 for (auto Ext : I.second)
4262 AddString(Ext, Record);
4264 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4267 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4268 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4269 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4270 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4274 void ASTWriter::WriteObjCCategories() {
4275 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4276 RecordData Categories;
4278 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4280 unsigned StartIndex = Categories.size();
4282 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4284 // Allocate space for the size.
4285 Categories.push_back(0);
4287 // Add the categories.
4288 for (ObjCInterfaceDecl::known_categories_iterator
4289 Cat = Class->known_categories_begin(),
4290 CatEnd = Class->known_categories_end();
4291 Cat != CatEnd; ++Cat, ++Size) {
4292 assert(getDeclID(*Cat) != 0 && "Bogus category");
4293 AddDeclRef(*Cat, Categories);
4297 Categories[StartIndex] = Size;
4299 // Record this interface -> category map.
4300 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4301 CategoriesMap.push_back(CatInfo);
4304 // Sort the categories map by the definition ID, since the reader will be
4305 // performing binary searches on this information.
4306 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4308 // Emit the categories map.
4309 using namespace llvm;
4311 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4312 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4313 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4314 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4315 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4317 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4318 Stream.EmitRecordWithBlob(AbbrevID, Record,
4319 reinterpret_cast<char *>(CategoriesMap.data()),
4320 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4322 // Emit the category lists.
4323 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4326 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4327 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4333 for (auto &LPTMapEntry : LPTMap) {
4334 const FunctionDecl *FD = LPTMapEntry.first;
4335 LateParsedTemplate &LPT = *LPTMapEntry.second;
4336 AddDeclRef(FD, Record);
4337 AddDeclRef(LPT.D, Record);
4338 Record.push_back(LPT.Toks.size());
4340 for (const auto &Tok : LPT.Toks) {
4341 AddToken(Tok, Record);
4344 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4347 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4348 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4350 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4351 AddSourceLocation(PragmaLoc, Record);
4352 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4355 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
4356 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4358 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4359 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4362 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
4364 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4366 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4367 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4368 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4371 /// \brief Write the state of 'pragma pack' at the end of the module.
4372 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4373 // Don't serialize pragma pack state for modules, since it should only take
4374 // effect on a per-submodule basis.
4379 Record.push_back(SemaRef.PackStack.CurrentValue);
4380 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4381 Record.push_back(SemaRef.PackStack.Stack.size());
4382 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4383 Record.push_back(StackEntry.Value);
4384 AddSourceLocation(StackEntry.PragmaLocation, Record);
4385 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4386 AddString(StackEntry.StackSlotLabel, Record);
4388 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4391 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4392 ModuleFileExtensionWriter &Writer) {
4393 // Enter the extension block.
4394 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4396 // Emit the metadata record abbreviation.
4397 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4398 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4399 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4400 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4401 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4402 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4403 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4404 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4406 // Emit the metadata record.
4408 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4409 Record.push_back(EXTENSION_METADATA);
4410 Record.push_back(Metadata.MajorVersion);
4411 Record.push_back(Metadata.MinorVersion);
4412 Record.push_back(Metadata.BlockName.size());
4413 Record.push_back(Metadata.UserInfo.size());
4414 SmallString<64> Buffer;
4415 Buffer += Metadata.BlockName;
4416 Buffer += Metadata.UserInfo;
4417 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4419 // Emit the contents of the extension block.
4420 Writer.writeExtensionContents(SemaRef, Stream);
4422 // Exit the extension block.
4426 //===----------------------------------------------------------------------===//
4427 // General Serialization Routines
4428 //===----------------------------------------------------------------------===//
4430 /// \brief Emit the list of attributes to the specified record.
4431 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4432 auto &Record = *this;
4433 Record.push_back(Attrs.size());
4434 for (const auto *A : Attrs) {
4435 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4436 Record.AddSourceRange(A->getRange());
4438 #include "clang/Serialization/AttrPCHWrite.inc"
4442 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4443 AddSourceLocation(Tok.getLocation(), Record);
4444 Record.push_back(Tok.getLength());
4446 // FIXME: When reading literal tokens, reconstruct the literal pointer
4448 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4449 // FIXME: Should translate token kind to a stable encoding.
4450 Record.push_back(Tok.getKind());
4451 // FIXME: Should translate token flags to a stable encoding.
4452 Record.push_back(Tok.getFlags());
4455 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4456 Record.push_back(Str.size());
4457 Record.insert(Record.end(), Str.begin(), Str.end());
4460 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4461 assert(Context && "should have context when outputting path");
4464 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4466 // Remove a prefix to make the path relative, if relevant.
4467 const char *PathBegin = Path.data();
4468 const char *PathPtr =
4469 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4470 if (PathPtr != PathBegin) {
4471 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4478 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4479 SmallString<128> FilePath(Path);
4480 PreparePathForOutput(FilePath);
4481 AddString(FilePath, Record);
4484 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4486 SmallString<128> FilePath(Path);
4487 PreparePathForOutput(FilePath);
4488 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4491 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4492 RecordDataImpl &Record) {
4493 Record.push_back(Version.getMajor());
4494 if (Optional<unsigned> Minor = Version.getMinor())
4495 Record.push_back(*Minor + 1);
4497 Record.push_back(0);
4498 if (Optional<unsigned> Subminor = Version.getSubminor())
4499 Record.push_back(*Subminor + 1);
4501 Record.push_back(0);
4504 /// \brief Note that the identifier II occurs at the given offset
4505 /// within the identifier table.
4506 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4507 IdentID ID = IdentifierIDs[II];
4508 // Only store offsets new to this AST file. Other identifier names are looked
4509 // up earlier in the chain and thus don't need an offset.
4510 if (ID >= FirstIdentID)
4511 IdentifierOffsets[ID - FirstIdentID] = Offset;
4514 /// \brief Note that the selector Sel occurs at the given offset
4515 /// within the method pool/selector table.
4516 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4517 unsigned ID = SelectorIDs[Sel];
4518 assert(ID && "Unknown selector");
4519 // Don't record offsets for selectors that are also available in a different
4521 if (ID < FirstSelectorID)
4523 SelectorOffsets[ID - FirstSelectorID] = Offset;
4526 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4527 SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
4528 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4529 bool IncludeTimestamps)
4530 : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
4531 IncludeTimestamps(IncludeTimestamps) {
4532 for (const auto &Ext : Extensions) {
4533 if (auto Writer = Ext->createExtensionWriter(*this))
4534 ModuleFileExtensionWriters.push_back(std::move(Writer));
4538 ASTWriter::~ASTWriter() {
4539 llvm::DeleteContainerSeconds(FileDeclIDs);
4542 const LangOptions &ASTWriter::getLangOpts() const {
4543 assert(WritingAST && "can't determine lang opts when not writing AST");
4544 return Context->getLangOpts();
4547 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4548 return IncludeTimestamps ? E->getModificationTime() : 0;
4551 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4552 const std::string &OutputFile,
4553 Module *WritingModule, StringRef isysroot,
4557 ASTHasCompilerErrors = hasErrors;
4559 // Emit the file header.
4560 Stream.Emit((unsigned)'C', 8);
4561 Stream.Emit((unsigned)'P', 8);
4562 Stream.Emit((unsigned)'C', 8);
4563 Stream.Emit((unsigned)'H', 8);
4565 WriteBlockInfoBlock();
4567 Context = &SemaRef.Context;
4569 this->WritingModule = WritingModule;
4570 ASTFileSignature Signature =
4571 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4574 this->WritingModule = nullptr;
4575 this->BaseDirectory.clear();
4578 if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
4579 // Construct MemoryBuffer and update buffer manager.
4580 PCMCache.addBuffer(OutputFile,
4581 llvm::MemoryBuffer::getMemBufferCopy(
4582 StringRef(Buffer.begin(), Buffer.size())));
4587 template<typename Vector>
4588 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4589 ASTWriter::RecordData &Record) {
4590 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4592 Writer.AddDeclRef(*I, Record);
4596 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4597 const std::string &OutputFile,
4598 Module *WritingModule) {
4599 using namespace llvm;
4601 bool isModule = WritingModule != nullptr;
4603 // Make sure that the AST reader knows to finalize itself.
4605 Chain->finalizeForWriting();
4607 ASTContext &Context = SemaRef.Context;
4608 Preprocessor &PP = SemaRef.PP;
4610 // Set up predefined declaration IDs.
4611 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4613 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4617 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4618 PREDEF_DECL_TRANSLATION_UNIT_ID);
4619 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4620 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4621 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4622 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4623 PREDEF_DECL_OBJC_PROTOCOL_ID);
4624 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4625 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4626 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4627 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4628 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4629 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4630 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4631 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4632 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4633 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4634 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4635 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4636 PREDEF_DECL_CF_CONSTANT_STRING_ID);
4637 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4638 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4639 RegisterPredefDecl(Context.TypePackElementDecl,
4640 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4642 // Build a record containing all of the tentative definitions in this file, in
4643 // TentativeDefinitions order. Generally, this record will be empty for
4645 RecordData TentativeDefinitions;
4646 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4648 // Build a record containing all of the file scoped decls in this file.
4649 RecordData UnusedFileScopedDecls;
4651 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4652 UnusedFileScopedDecls);
4654 // Build a record containing all of the delegating constructors we still need
4656 RecordData DelegatingCtorDecls;
4658 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4660 // Write the set of weak, undeclared identifiers. We always write the
4661 // entire table, since later PCH files in a PCH chain are only interested in
4662 // the results at the end of the chain.
4663 RecordData WeakUndeclaredIdentifiers;
4664 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4665 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4666 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4667 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4668 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4669 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4670 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4673 // Build a record containing all of the ext_vector declarations.
4674 RecordData ExtVectorDecls;
4675 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4677 // Build a record containing all of the VTable uses information.
4678 RecordData VTableUses;
4679 if (!SemaRef.VTableUses.empty()) {
4680 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4681 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4682 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4683 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4687 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4688 RecordData UnusedLocalTypedefNameCandidates;
4689 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4690 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4692 // Build a record containing all of pending implicit instantiations.
4693 RecordData PendingInstantiations;
4694 for (const auto &I : SemaRef.PendingInstantiations) {
4695 AddDeclRef(I.first, PendingInstantiations);
4696 AddSourceLocation(I.second, PendingInstantiations);
4698 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4699 "There are local ones at end of translation unit!");
4701 // Build a record containing some declaration references.
4702 RecordData SemaDeclRefs;
4703 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4704 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4705 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4706 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4709 RecordData CUDASpecialDeclRefs;
4710 if (Context.getcudaConfigureCallDecl()) {
4711 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4714 // Build a record containing all of the known namespaces.
4715 RecordData KnownNamespaces;
4716 for (const auto &I : SemaRef.KnownNamespaces) {
4718 AddDeclRef(I.first, KnownNamespaces);
4721 // Build a record of all used, undefined objects that require definitions.
4722 RecordData UndefinedButUsed;
4724 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4725 SemaRef.getUndefinedButUsed(Undefined);
4726 for (const auto &I : Undefined) {
4727 AddDeclRef(I.first, UndefinedButUsed);
4728 AddSourceLocation(I.second, UndefinedButUsed);
4731 // Build a record containing all delete-expressions that we would like to
4732 // analyze later in AST.
4733 RecordData DeleteExprsToAnalyze;
4735 for (const auto &DeleteExprsInfo :
4736 SemaRef.getMismatchingDeleteExpressions()) {
4737 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4738 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4739 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4740 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4741 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4745 // Write the control block
4746 WriteControlBlock(PP, Context, isysroot, OutputFile);
4748 // Write the remaining AST contents.
4749 Stream.EnterSubblock(AST_BLOCK_ID, 5);
4751 // This is so that older clang versions, before the introduction
4752 // of the control block, can read and reject the newer PCH format.
4754 RecordData Record = {VERSION_MAJOR};
4755 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4758 // Create a lexical update block containing all of the declarations in the
4759 // translation unit that do not come from other AST files.
4760 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4761 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4762 for (const auto *D : TU->noload_decls()) {
4763 if (!D->isFromASTFile()) {
4764 NewGlobalKindDeclPairs.push_back(D->getKind());
4765 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4769 auto Abv = std::make_shared<BitCodeAbbrev>();
4770 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4771 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4772 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4774 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4775 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4776 bytes(NewGlobalKindDeclPairs));
4779 // And a visible updates block for the translation unit.
4780 Abv = std::make_shared<BitCodeAbbrev>();
4781 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4782 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4783 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4784 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4785 WriteDeclContextVisibleUpdate(TU);
4787 // If we have any extern "C" names, write out a visible update for them.
4788 if (Context.ExternCContext)
4789 WriteDeclContextVisibleUpdate(Context.ExternCContext);
4791 // If the translation unit has an anonymous namespace, and we don't already
4792 // have an update block for it, write it as an update block.
4793 // FIXME: Why do we not do this if there's already an update block?
4794 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4795 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4797 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4800 // Add update records for all mangling numbers and static local numbers.
4801 // These aren't really update records, but this is a convenient way of
4802 // tagging this rare extra data onto the declarations.
4803 for (const auto &Number : Context.MangleNumbers)
4804 if (!Number.first->isFromASTFile())
4805 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4807 for (const auto &Number : Context.StaticLocalNumbers)
4808 if (!Number.first->isFromASTFile())
4809 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4812 // Make sure visible decls, added to DeclContexts previously loaded from
4813 // an AST file, are registered for serialization. Likewise for template
4814 // specializations added to imported templates.
4815 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4819 // Make sure all decls associated with an identifier are registered for
4820 // serialization, if we're storing decls with identifiers.
4821 if (!WritingModule || !getLangOpts().CPlusPlus) {
4822 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4823 for (const auto &ID : PP.getIdentifierTable()) {
4824 const IdentifierInfo *II = ID.second;
4825 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4828 // Sort the identifiers to visit based on their name.
4829 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4830 for (const IdentifierInfo *II : IIs) {
4831 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4832 DEnd = SemaRef.IdResolver.end();
4839 // For method pool in the module, if it contains an entry for a selector,
4840 // the entry should be complete, containing everything introduced by that
4841 // module and all modules it imports. It's possible that the entry is out of
4842 // date, so we need to pull in the new content here.
4844 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4845 // safe, we copy all selectors out.
4846 llvm::SmallVector<Selector, 256> AllSelectors;
4847 for (auto &SelectorAndID : SelectorIDs)
4848 AllSelectors.push_back(SelectorAndID.first);
4849 for (auto &Selector : AllSelectors)
4850 SemaRef.updateOutOfDateSelector(Selector);
4852 // Form the record of special types.
4853 RecordData SpecialTypes;
4854 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4855 AddTypeRef(Context.getFILEType(), SpecialTypes);
4856 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4857 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4858 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4859 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4860 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4861 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4864 // Write the mapping information describing our module dependencies and how
4865 // each of those modules were mapped into our own offset/ID space, so that
4866 // the reader can build the appropriate mapping to its own offset/ID space.
4867 // The map consists solely of a blob with the following format:
4869 // module-name-len:i16 module-name:len*i8
4870 // source-location-offset:i32
4871 // identifier-id:i32
4872 // preprocessed-entity-id:i32
4873 // macro-definition-id:i32
4876 // declaration-id:i32
4877 // c++-base-specifiers-id:i32
4880 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4881 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4882 // it is the module file name.
4883 auto Abbrev = std::make_shared<BitCodeAbbrev>();
4884 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4886 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4887 SmallString<2048> Buffer;
4889 llvm::raw_svector_ostream Out(Buffer);
4890 for (ModuleFile &M : Chain->ModuleMgr) {
4891 using namespace llvm::support;
4893 endian::Writer<little> LE(Out);
4894 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4896 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4899 LE.write<uint16_t>(Name.size());
4900 Out.write(Name.data(), Name.size());
4902 // Note: if a base ID was uint max, it would not be possible to load
4903 // another module after it or have more than one entity inside it.
4904 uint32_t None = std::numeric_limits<uint32_t>::max();
4906 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4907 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4909 LE.write<uint32_t>(BaseID);
4911 LE.write<uint32_t>(None);
4914 // These values should be unique within a chain, since they will be read
4915 // as keys into ContinuousRangeMaps.
4916 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4917 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4918 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4919 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4920 M.NumPreprocessedEntities);
4921 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4922 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4923 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4924 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4927 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4928 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4929 Buffer.data(), Buffer.size());
4932 RecordData DeclUpdatesOffsetsRecord;
4934 // Keep writing types, declarations, and declaration update records
4935 // until we've emitted all of them.
4936 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4940 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4941 while (!DeclTypesToEmit.empty()) {
4942 DeclOrType DOT = DeclTypesToEmit.front();
4943 DeclTypesToEmit.pop();
4945 WriteType(DOT.getType());
4947 WriteDecl(Context, DOT.getDecl());
4949 } while (!DeclUpdates.empty());
4952 DoneWritingDeclsAndTypes = true;
4954 // These things can only be done once we've written out decls and types.
4955 WriteTypeDeclOffsets();
4956 if (!DeclUpdatesOffsetsRecord.empty())
4957 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4958 WriteFileDeclIDsMap();
4959 WriteSourceManagerBlock(Context.getSourceManager(), PP);
4961 WritePreprocessor(PP, isModule);
4962 WriteHeaderSearch(PP.getHeaderSearchInfo());
4963 WriteSelectors(SemaRef);
4964 WriteReferencedSelectorsPool(SemaRef);
4965 WriteLateParsedTemplates(SemaRef);
4966 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4967 WriteFPPragmaOptions(SemaRef.getFPOptions());
4968 WriteOpenCLExtensions(SemaRef);
4969 WriteOpenCLExtensionTypes(SemaRef);
4970 WriteOpenCLExtensionDecls(SemaRef);
4971 WriteCUDAPragmas(SemaRef);
4973 // If we're emitting a module, write out the submodule information.
4975 WriteSubmodules(WritingModule);
4977 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4979 // Write the record containing external, unnamed definitions.
4980 if (!EagerlyDeserializedDecls.empty())
4981 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4983 if (!ModularCodegenDecls.empty())
4984 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4986 // Write the record containing tentative definitions.
4987 if (!TentativeDefinitions.empty())
4988 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4990 // Write the record containing unused file scoped decls.
4991 if (!UnusedFileScopedDecls.empty())
4992 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4994 // Write the record containing weak undeclared identifiers.
4995 if (!WeakUndeclaredIdentifiers.empty())
4996 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4997 WeakUndeclaredIdentifiers);
4999 // Write the record containing ext_vector type names.
5000 if (!ExtVectorDecls.empty())
5001 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5003 // Write the record containing VTable uses information.
5004 if (!VTableUses.empty())
5005 Stream.EmitRecord(VTABLE_USES, VTableUses);
5007 // Write the record containing potentially unused local typedefs.
5008 if (!UnusedLocalTypedefNameCandidates.empty())
5009 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5010 UnusedLocalTypedefNameCandidates);
5012 // Write the record containing pending implicit instantiations.
5013 if (!PendingInstantiations.empty())
5014 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5016 // Write the record containing declaration references of Sema.
5017 if (!SemaDeclRefs.empty())
5018 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5020 // Write the record containing CUDA-specific declaration references.
5021 if (!CUDASpecialDeclRefs.empty())
5022 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5024 // Write the delegating constructors.
5025 if (!DelegatingCtorDecls.empty())
5026 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5028 // Write the known namespaces.
5029 if (!KnownNamespaces.empty())
5030 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5032 // Write the undefined internal functions and variables, and inline functions.
5033 if (!UndefinedButUsed.empty())
5034 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5036 if (!DeleteExprsToAnalyze.empty())
5037 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5039 // Write the visible updates to DeclContexts.
5040 for (auto *DC : UpdatedDeclContexts)
5041 WriteDeclContextVisibleUpdate(DC);
5043 if (!WritingModule) {
5044 // Write the submodules that were imported, if any.
5048 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5050 llvm::SmallVector<ModuleInfo, 64> Imports;
5051 for (const auto *I : Context.local_imports()) {
5052 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
5053 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5054 I->getImportedModule()));
5057 if (!Imports.empty()) {
5058 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5061 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5062 return A.ID == B.ID;
5065 // Sort and deduplicate module IDs.
5066 std::sort(Imports.begin(), Imports.end(), Cmp);
5067 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5070 RecordData ImportedModules;
5071 for (const auto &Import : Imports) {
5072 ImportedModules.push_back(Import.ID);
5073 // FIXME: If the module has macros imported then later has declarations
5074 // imported, this location won't be the right one as a location for the
5075 // declaration imports.
5076 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5079 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5083 WriteObjCCategories();
5084 if(!WritingModule) {
5085 WriteOptimizePragmaOptions(SemaRef);
5086 WriteMSStructPragmaOptions(SemaRef);
5087 WriteMSPointersToMembersPragmaOptions(SemaRef);
5089 WritePackPragmaOptions(SemaRef);
5091 // Some simple statistics
5092 RecordData::value_type Record[] = {
5093 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5094 Stream.EmitRecord(STATISTICS, Record);
5097 // Write the module file extension blocks.
5098 for (const auto &ExtWriter : ModuleFileExtensionWriters)
5099 WriteModuleFileExtension(SemaRef, *ExtWriter);
5101 return writeUnhashedControlBlock(PP, Context);
5104 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5105 if (DeclUpdates.empty())
5108 DeclUpdateMap LocalUpdates;
5109 LocalUpdates.swap(DeclUpdates);
5111 for (auto &DeclUpdate : LocalUpdates) {
5112 const Decl *D = DeclUpdate.first;
5114 bool HasUpdatedBody = false;
5115 RecordData RecordData;
5116 ASTRecordWriter Record(*this, RecordData);
5117 for (auto &Update : DeclUpdate.second) {
5118 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5120 // An updated body is emitted last, so that the reader doesn't need
5121 // to skip over the lazy body to reach statements for other records.
5122 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5123 HasUpdatedBody = true;
5125 Record.push_back(Kind);
5128 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5129 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5130 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5131 assert(Update.getDecl() && "no decl to add?");
5132 Record.push_back(GetDeclRef(Update.getDecl()));
5135 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5138 case UPD_CXX_POINT_OF_INSTANTIATION:
5139 // FIXME: Do we need to also save the template specialization kind here?
5140 Record.AddSourceLocation(Update.getLoc());
5143 case UPD_CXX_ADDED_VAR_DEFINITION: {
5144 const VarDecl *VD = cast<VarDecl>(D);
5145 Record.push_back(VD->isInline());
5146 Record.push_back(VD->isInlineSpecified());
5147 if (VD->getInit()) {
5148 Record.push_back(!VD->isInitKnownICE() ? 1
5149 : (VD->isInitICE() ? 3 : 2));
5150 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5152 Record.push_back(0);
5157 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5158 Record.AddStmt(const_cast<Expr *>(
5159 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5162 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5164 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5167 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5168 auto *RD = cast<CXXRecordDecl>(D);
5169 UpdatedDeclContexts.insert(RD->getPrimaryContext());
5170 Record.AddCXXDefinitionData(RD);
5171 Record.AddOffset(WriteDeclContextLexicalBlock(
5172 *Context, const_cast<CXXRecordDecl *>(RD)));
5174 // This state is sometimes updated by template instantiation, when we
5175 // switch from the specialization referring to the template declaration
5176 // to it referring to the template definition.
5177 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5178 Record.push_back(MSInfo->getTemplateSpecializationKind());
5179 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5181 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5182 Record.push_back(Spec->getTemplateSpecializationKind());
5183 Record.AddSourceLocation(Spec->getPointOfInstantiation());
5185 // The instantiation might have been resolved to a partial
5186 // specialization. If so, record which one.
5187 auto From = Spec->getInstantiatedFrom();
5188 if (auto PartialSpec =
5189 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5190 Record.push_back(true);
5191 Record.AddDeclRef(PartialSpec);
5192 Record.AddTemplateArgumentList(
5193 &Spec->getTemplateInstantiationArgs());
5195 Record.push_back(false);
5198 Record.push_back(RD->getTagKind());
5199 Record.AddSourceLocation(RD->getLocation());
5200 Record.AddSourceLocation(RD->getLocStart());
5201 Record.AddSourceRange(RD->getBraceRange());
5203 // Instantiation may change attributes; write them all out afresh.
5204 Record.push_back(D->hasAttrs());
5206 Record.AddAttributes(D->getAttrs());
5208 // FIXME: Ensure we don't get here for explicit instantiations.
5212 case UPD_CXX_RESOLVED_DTOR_DELETE:
5213 Record.AddDeclRef(Update.getDecl());
5214 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5217 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5219 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5223 case UPD_CXX_DEDUCED_RETURN_TYPE:
5224 Record.push_back(GetOrCreateTypeID(Update.getType()));
5227 case UPD_DECL_MARKED_USED:
5230 case UPD_MANGLING_NUMBER:
5231 case UPD_STATIC_LOCAL_NUMBER:
5232 Record.push_back(Update.getNumber());
5235 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5236 Record.AddSourceRange(
5237 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5240 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5241 Record.AddSourceRange(
5242 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5245 case UPD_DECL_EXPORTED:
5246 Record.push_back(getSubmoduleID(Update.getModule()));
5249 case UPD_ADDED_ATTR_TO_RECORD:
5250 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5255 if (HasUpdatedBody) {
5256 const auto *Def = cast<FunctionDecl>(D);
5257 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5258 Record.push_back(Def->isInlined());
5259 Record.AddSourceLocation(Def->getInnerLocStart());
5260 Record.AddFunctionDefinition(Def);
5263 OffsetsRecord.push_back(GetDeclRef(D));
5264 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5268 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5269 uint32_t Raw = Loc.getRawEncoding();
5270 Record.push_back((Raw << 1) | (Raw >> 31));
5273 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5274 AddSourceLocation(Range.getBegin(), Record);
5275 AddSourceLocation(Range.getEnd(), Record);
5278 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5279 Record->push_back(Value.getBitWidth());
5280 const uint64_t *Words = Value.getRawData();
5281 Record->append(Words, Words + Value.getNumWords());
5284 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5285 Record->push_back(Value.isUnsigned());
5289 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5290 AddAPInt(Value.bitcastToAPInt());
5293 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5294 Record.push_back(getIdentifierRef(II));
5297 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5301 IdentID &ID = IdentifierIDs[II];
5307 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5308 // Don't emit builtin macros like __LINE__ to the AST file unless they
5309 // have been redefined by the header (in which case they are not
5311 if (!MI || MI->isBuiltinMacro())
5314 MacroID &ID = MacroIDs[MI];
5317 MacroInfoToEmitData Info = { Name, MI, ID };
5318 MacroInfosToEmit.push_back(Info);
5323 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5324 if (!MI || MI->isBuiltinMacro())
5327 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5328 return MacroIDs[MI];
5331 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5332 return IdentMacroDirectivesOffsetMap.lookup(Name);
5335 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5336 Record->push_back(Writer->getSelectorRef(SelRef));
5339 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5340 if (Sel.getAsOpaquePtr() == nullptr) {
5344 SelectorID SID = SelectorIDs[Sel];
5345 if (SID == 0 && Chain) {
5346 // This might trigger a ReadSelector callback, which will set the ID for
5348 Chain->LoadSelector(Sel);
5349 SID = SelectorIDs[Sel];
5352 SID = NextSelectorID++;
5353 SelectorIDs[Sel] = SID;
5358 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5359 AddDeclRef(Temp->getDestructor());
5362 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5363 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5365 case TemplateArgument::Expression:
5366 AddStmt(Arg.getAsExpr());
5368 case TemplateArgument::Type:
5369 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5371 case TemplateArgument::Template:
5372 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5373 AddSourceLocation(Arg.getTemplateNameLoc());
5375 case TemplateArgument::TemplateExpansion:
5376 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5377 AddSourceLocation(Arg.getTemplateNameLoc());
5378 AddSourceLocation(Arg.getTemplateEllipsisLoc());
5380 case TemplateArgument::Null:
5381 case TemplateArgument::Integral:
5382 case TemplateArgument::Declaration:
5383 case TemplateArgument::NullPtr:
5384 case TemplateArgument::Pack:
5385 // FIXME: Is this right?
5390 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5391 AddTemplateArgument(Arg.getArgument());
5393 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5394 bool InfoHasSameExpr
5395 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5396 Record->push_back(InfoHasSameExpr);
5397 if (InfoHasSameExpr)
5398 return; // Avoid storing the same expr twice.
5400 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5403 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5405 AddTypeRef(QualType());
5409 AddTypeLoc(TInfo->getTypeLoc());
5412 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5413 AddTypeRef(TL.getType());
5415 TypeLocWriter TLW(*this);
5416 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5420 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5421 Record.push_back(GetOrCreateTypeID(T));
5424 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5426 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5429 assert(!T.getLocalFastQualifiers());
5431 TypeIdx &Idx = TypeIdxs[T];
5432 if (Idx.getIndex() == 0) {
5433 if (DoneWritingDeclsAndTypes) {
5434 assert(0 && "New type seen after serializing all the types to emit!");
5438 // We haven't seen this type before. Assign it a new ID and put it
5439 // into the queue of types to emit.
5440 Idx = TypeIdx(NextTypeID++);
5441 DeclTypesToEmit.push(T);
5447 TypeID ASTWriter::getTypeID(QualType T) const {
5449 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5452 assert(!T.getLocalFastQualifiers());
5454 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5455 assert(I != TypeIdxs.end() && "Type not emitted!");
5460 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5461 Record.push_back(GetDeclRef(D));
5464 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5465 assert(WritingAST && "Cannot request a declaration ID before AST writing");
5471 // If D comes from an AST file, its declaration ID is already known and
5473 if (D->isFromASTFile())
5474 return D->getGlobalID();
5476 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5477 DeclID &ID = DeclIDs[D];
5479 if (DoneWritingDeclsAndTypes) {
5480 assert(0 && "New decl seen after serializing all the decls to emit!");
5484 // We haven't seen this declaration before. Give it a new ID and
5485 // enqueue it in the list of declarations to emit.
5487 DeclTypesToEmit.push(const_cast<Decl *>(D));
5493 DeclID ASTWriter::getDeclID(const Decl *D) {
5497 // If D comes from an AST file, its declaration ID is already known and
5499 if (D->isFromASTFile())
5500 return D->getGlobalID();
5502 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5506 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5510 SourceLocation Loc = D->getLocation();
5511 if (Loc.isInvalid())
5514 // We only keep track of the file-level declarations of each file.
5515 if (!D->getLexicalDeclContext()->isFileContext())
5517 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5518 // a function/objc method, should not have TU as lexical context.
5519 if (isa<ParmVarDecl>(D))
5522 SourceManager &SM = Context->getSourceManager();
5523 SourceLocation FileLoc = SM.getFileLoc(Loc);
5524 assert(SM.isLocalSourceLocation(FileLoc));
5527 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5528 if (FID.isInvalid())
5530 assert(SM.getSLocEntry(FID).isFile());
5532 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5534 Info = new DeclIDInFileInfo();
5536 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5537 LocDeclIDsTy &Decls = Info->DeclIDs;
5539 if (Decls.empty() || Decls.back().first <= Offset) {
5540 Decls.push_back(LocDecl);
5544 LocDeclIDsTy::iterator I =
5545 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5547 Decls.insert(I, LocDecl);
5550 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5551 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5552 Record->push_back(Name.getNameKind());
5553 switch (Name.getNameKind()) {
5554 case DeclarationName::Identifier:
5555 AddIdentifierRef(Name.getAsIdentifierInfo());
5558 case DeclarationName::ObjCZeroArgSelector:
5559 case DeclarationName::ObjCOneArgSelector:
5560 case DeclarationName::ObjCMultiArgSelector:
5561 AddSelectorRef(Name.getObjCSelector());
5564 case DeclarationName::CXXConstructorName:
5565 case DeclarationName::CXXDestructorName:
5566 case DeclarationName::CXXConversionFunctionName:
5567 AddTypeRef(Name.getCXXNameType());
5570 case DeclarationName::CXXDeductionGuideName:
5571 AddDeclRef(Name.getCXXDeductionGuideTemplate());
5574 case DeclarationName::CXXOperatorName:
5575 Record->push_back(Name.getCXXOverloadedOperator());
5578 case DeclarationName::CXXLiteralOperatorName:
5579 AddIdentifierRef(Name.getCXXLiteralIdentifier());
5582 case DeclarationName::CXXUsingDirective:
5583 // No extra data to emit
5588 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5589 assert(needsAnonymousDeclarationNumber(D) &&
5590 "expected an anonymous declaration");
5592 // Number the anonymous declarations within this context, if we've not
5594 auto It = AnonymousDeclarationNumbers.find(D);
5595 if (It == AnonymousDeclarationNumbers.end()) {
5596 auto *DC = D->getLexicalDeclContext();
5597 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5598 AnonymousDeclarationNumbers[ND] = Number;
5601 It = AnonymousDeclarationNumbers.find(D);
5602 assert(It != AnonymousDeclarationNumbers.end() &&
5603 "declaration not found within its lexical context");
5609 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5610 DeclarationName Name) {
5611 switch (Name.getNameKind()) {
5612 case DeclarationName::CXXConstructorName:
5613 case DeclarationName::CXXDestructorName:
5614 case DeclarationName::CXXConversionFunctionName:
5615 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5618 case DeclarationName::CXXOperatorName:
5619 AddSourceLocation(SourceLocation::getFromRawEncoding(
5620 DNLoc.CXXOperatorName.BeginOpNameLoc));
5622 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5625 case DeclarationName::CXXLiteralOperatorName:
5626 AddSourceLocation(SourceLocation::getFromRawEncoding(
5627 DNLoc.CXXLiteralOperatorName.OpNameLoc));
5630 case DeclarationName::Identifier:
5631 case DeclarationName::ObjCZeroArgSelector:
5632 case DeclarationName::ObjCOneArgSelector:
5633 case DeclarationName::ObjCMultiArgSelector:
5634 case DeclarationName::CXXUsingDirective:
5635 case DeclarationName::CXXDeductionGuideName:
5640 void ASTRecordWriter::AddDeclarationNameInfo(
5641 const DeclarationNameInfo &NameInfo) {
5642 AddDeclarationName(NameInfo.getName());
5643 AddSourceLocation(NameInfo.getLoc());
5644 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5647 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5648 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5649 Record->push_back(Info.NumTemplParamLists);
5650 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5651 AddTemplateParameterList(Info.TemplParamLists[i]);
5654 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5655 // Nested name specifiers usually aren't too long. I think that 8 would
5656 // typically accommodate the vast majority.
5657 SmallVector<NestedNameSpecifier *, 8> NestedNames;
5659 // Push each of the NNS's onto a stack for serialization in reverse order.
5661 NestedNames.push_back(NNS);
5662 NNS = NNS->getPrefix();
5665 Record->push_back(NestedNames.size());
5666 while(!NestedNames.empty()) {
5667 NNS = NestedNames.pop_back_val();
5668 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5669 Record->push_back(Kind);
5671 case NestedNameSpecifier::Identifier:
5672 AddIdentifierRef(NNS->getAsIdentifier());
5675 case NestedNameSpecifier::Namespace:
5676 AddDeclRef(NNS->getAsNamespace());
5679 case NestedNameSpecifier::NamespaceAlias:
5680 AddDeclRef(NNS->getAsNamespaceAlias());
5683 case NestedNameSpecifier::TypeSpec:
5684 case NestedNameSpecifier::TypeSpecWithTemplate:
5685 AddTypeRef(QualType(NNS->getAsType(), 0));
5686 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5689 case NestedNameSpecifier::Global:
5690 // Don't need to write an associated value.
5693 case NestedNameSpecifier::Super:
5694 AddDeclRef(NNS->getAsRecordDecl());
5700 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5701 // Nested name specifiers usually aren't too long. I think that 8 would
5702 // typically accommodate the vast majority.
5703 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5705 // Push each of the nested-name-specifiers's onto a stack for
5706 // serialization in reverse order.
5708 NestedNames.push_back(NNS);
5709 NNS = NNS.getPrefix();
5712 Record->push_back(NestedNames.size());
5713 while(!NestedNames.empty()) {
5714 NNS = NestedNames.pop_back_val();
5715 NestedNameSpecifier::SpecifierKind Kind
5716 = NNS.getNestedNameSpecifier()->getKind();
5717 Record->push_back(Kind);
5719 case NestedNameSpecifier::Identifier:
5720 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5721 AddSourceRange(NNS.getLocalSourceRange());
5724 case NestedNameSpecifier::Namespace:
5725 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5726 AddSourceRange(NNS.getLocalSourceRange());
5729 case NestedNameSpecifier::NamespaceAlias:
5730 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5731 AddSourceRange(NNS.getLocalSourceRange());
5734 case NestedNameSpecifier::TypeSpec:
5735 case NestedNameSpecifier::TypeSpecWithTemplate:
5736 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5737 AddTypeLoc(NNS.getTypeLoc());
5738 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5741 case NestedNameSpecifier::Global:
5742 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5745 case NestedNameSpecifier::Super:
5746 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5747 AddSourceRange(NNS.getLocalSourceRange());
5753 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5754 TemplateName::NameKind Kind = Name.getKind();
5755 Record->push_back(Kind);
5757 case TemplateName::Template:
5758 AddDeclRef(Name.getAsTemplateDecl());
5761 case TemplateName::OverloadedTemplate: {
5762 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5763 Record->push_back(OvT->size());
5764 for (const auto &I : *OvT)
5769 case TemplateName::QualifiedTemplate: {
5770 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5771 AddNestedNameSpecifier(QualT->getQualifier());
5772 Record->push_back(QualT->hasTemplateKeyword());
5773 AddDeclRef(QualT->getTemplateDecl());
5777 case TemplateName::DependentTemplate: {
5778 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5779 AddNestedNameSpecifier(DepT->getQualifier());
5780 Record->push_back(DepT->isIdentifier());
5781 if (DepT->isIdentifier())
5782 AddIdentifierRef(DepT->getIdentifier());
5784 Record->push_back(DepT->getOperator());
5788 case TemplateName::SubstTemplateTemplateParm: {
5789 SubstTemplateTemplateParmStorage *subst
5790 = Name.getAsSubstTemplateTemplateParm();
5791 AddDeclRef(subst->getParameter());
5792 AddTemplateName(subst->getReplacement());
5796 case TemplateName::SubstTemplateTemplateParmPack: {
5797 SubstTemplateTemplateParmPackStorage *SubstPack
5798 = Name.getAsSubstTemplateTemplateParmPack();
5799 AddDeclRef(SubstPack->getParameterPack());
5800 AddTemplateArgument(SubstPack->getArgumentPack());
5806 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5807 Record->push_back(Arg.getKind());
5808 switch (Arg.getKind()) {
5809 case TemplateArgument::Null:
5811 case TemplateArgument::Type:
5812 AddTypeRef(Arg.getAsType());
5814 case TemplateArgument::Declaration:
5815 AddDeclRef(Arg.getAsDecl());
5816 AddTypeRef(Arg.getParamTypeForDecl());
5818 case TemplateArgument::NullPtr:
5819 AddTypeRef(Arg.getNullPtrType());
5821 case TemplateArgument::Integral:
5822 AddAPSInt(Arg.getAsIntegral());
5823 AddTypeRef(Arg.getIntegralType());
5825 case TemplateArgument::Template:
5826 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5828 case TemplateArgument::TemplateExpansion:
5829 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5830 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5831 Record->push_back(*NumExpansions + 1);
5833 Record->push_back(0);
5835 case TemplateArgument::Expression:
5836 AddStmt(Arg.getAsExpr());
5838 case TemplateArgument::Pack:
5839 Record->push_back(Arg.pack_size());
5840 for (const auto &P : Arg.pack_elements())
5841 AddTemplateArgument(P);
5846 void ASTRecordWriter::AddTemplateParameterList(
5847 const TemplateParameterList *TemplateParams) {
5848 assert(TemplateParams && "No TemplateParams!");
5849 AddSourceLocation(TemplateParams->getTemplateLoc());
5850 AddSourceLocation(TemplateParams->getLAngleLoc());
5851 AddSourceLocation(TemplateParams->getRAngleLoc());
5853 Record->push_back(TemplateParams->size());
5854 for (const auto &P : *TemplateParams)
5858 /// \brief Emit a template argument list.
5859 void ASTRecordWriter::AddTemplateArgumentList(
5860 const TemplateArgumentList *TemplateArgs) {
5861 assert(TemplateArgs && "No TemplateArgs!");
5862 Record->push_back(TemplateArgs->size());
5863 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5864 AddTemplateArgument(TemplateArgs->get(i));
5867 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5868 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5869 assert(ASTTemplArgList && "No ASTTemplArgList!");
5870 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5871 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5872 Record->push_back(ASTTemplArgList->NumTemplateArgs);
5873 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5874 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5875 AddTemplateArgumentLoc(TemplArgs[i]);
5878 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5879 Record->push_back(Set.size());
5880 for (ASTUnresolvedSet::const_iterator
5881 I = Set.begin(), E = Set.end(); I != E; ++I) {
5882 AddDeclRef(I.getDecl());
5883 Record->push_back(I.getAccess());
5887 // FIXME: Move this out of the main ASTRecordWriter interface.
5888 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5889 Record->push_back(Base.isVirtual());
5890 Record->push_back(Base.isBaseOfClass());
5891 Record->push_back(Base.getAccessSpecifierAsWritten());
5892 Record->push_back(Base.getInheritConstructors());
5893 AddTypeSourceInfo(Base.getTypeSourceInfo());
5894 AddSourceRange(Base.getSourceRange());
5895 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5896 : SourceLocation());
5899 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5900 ArrayRef<CXXBaseSpecifier> Bases) {
5901 ASTWriter::RecordData Record;
5902 ASTRecordWriter Writer(W, Record);
5903 Writer.push_back(Bases.size());
5905 for (auto &Base : Bases)
5906 Writer.AddCXXBaseSpecifier(Base);
5908 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5911 // FIXME: Move this out of the main ASTRecordWriter interface.
5912 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5913 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5917 EmitCXXCtorInitializers(ASTWriter &W,
5918 ArrayRef<CXXCtorInitializer *> CtorInits) {
5919 ASTWriter::RecordData Record;
5920 ASTRecordWriter Writer(W, Record);
5921 Writer.push_back(CtorInits.size());
5923 for (auto *Init : CtorInits) {
5924 if (Init->isBaseInitializer()) {
5925 Writer.push_back(CTOR_INITIALIZER_BASE);
5926 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5927 Writer.push_back(Init->isBaseVirtual());
5928 } else if (Init->isDelegatingInitializer()) {
5929 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5930 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5931 } else if (Init->isMemberInitializer()){
5932 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5933 Writer.AddDeclRef(Init->getMember());
5935 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5936 Writer.AddDeclRef(Init->getIndirectMember());
5939 Writer.AddSourceLocation(Init->getMemberLocation());
5940 Writer.AddStmt(Init->getInit());
5941 Writer.AddSourceLocation(Init->getLParenLoc());
5942 Writer.AddSourceLocation(Init->getRParenLoc());
5943 Writer.push_back(Init->isWritten());
5944 if (Init->isWritten())
5945 Writer.push_back(Init->getSourceOrder());
5948 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5951 // FIXME: Move this out of the main ASTRecordWriter interface.
5952 void ASTRecordWriter::AddCXXCtorInitializers(
5953 ArrayRef<CXXCtorInitializer *> CtorInits) {
5954 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5957 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5958 auto &Data = D->data();
5959 Record->push_back(Data.IsLambda);
5960 Record->push_back(Data.UserDeclaredConstructor);
5961 Record->push_back(Data.UserDeclaredSpecialMembers);
5962 Record->push_back(Data.Aggregate);
5963 Record->push_back(Data.PlainOldData);
5964 Record->push_back(Data.Empty);
5965 Record->push_back(Data.Polymorphic);
5966 Record->push_back(Data.Abstract);
5967 Record->push_back(Data.IsStandardLayout);
5968 Record->push_back(Data.HasNoNonEmptyBases);
5969 Record->push_back(Data.HasPrivateFields);
5970 Record->push_back(Data.HasProtectedFields);
5971 Record->push_back(Data.HasPublicFields);
5972 Record->push_back(Data.HasMutableFields);
5973 Record->push_back(Data.HasVariantMembers);
5974 Record->push_back(Data.HasOnlyCMembers);
5975 Record->push_back(Data.HasInClassInitializer);
5976 Record->push_back(Data.HasUninitializedReferenceMember);
5977 Record->push_back(Data.HasUninitializedFields);
5978 Record->push_back(Data.HasInheritedConstructor);
5979 Record->push_back(Data.HasInheritedAssignment);
5980 Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
5981 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5982 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5983 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5984 Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
5985 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5986 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5987 Record->push_back(Data.DefaultedDestructorIsDeleted);
5988 Record->push_back(Data.HasTrivialSpecialMembers);
5989 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5990 Record->push_back(Data.HasIrrelevantDestructor);
5991 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5992 Record->push_back(Data.HasDefaultedDefaultConstructor);
5993 Record->push_back(Data.CanPassInRegisters);
5994 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5995 Record->push_back(Data.HasConstexprDefaultConstructor);
5996 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5997 Record->push_back(Data.ComputedVisibleConversions);
5998 Record->push_back(Data.UserProvidedDefaultConstructor);
5999 Record->push_back(Data.DeclaredSpecialMembers);
6000 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
6001 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
6002 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
6003 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
6004 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
6006 // getODRHash will compute the ODRHash if it has not been previously computed.
6007 Record->push_back(D->getODRHash());
6008 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
6009 Writer->WritingModule && !D->isDependentType();
6010 Record->push_back(ModulesDebugInfo);
6011 if (ModulesDebugInfo)
6012 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6014 // IsLambda bit is already saved.
6016 Record->push_back(Data.NumBases);
6017 if (Data.NumBases > 0)
6018 AddCXXBaseSpecifiers(Data.bases());
6020 // FIXME: Make VBases lazily computed when needed to avoid storing them.
6021 Record->push_back(Data.NumVBases);
6022 if (Data.NumVBases > 0)
6023 AddCXXBaseSpecifiers(Data.vbases());
6025 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6026 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
6027 // Data.Definition is the owning decl, no need to write it.
6028 AddDeclRef(D->getFirstFriend());
6030 // Add lambda-specific data.
6031 if (Data.IsLambda) {
6032 auto &Lambda = D->getLambdaData();
6033 Record->push_back(Lambda.Dependent);
6034 Record->push_back(Lambda.IsGenericLambda);
6035 Record->push_back(Lambda.CaptureDefault);
6036 Record->push_back(Lambda.NumCaptures);
6037 Record->push_back(Lambda.NumExplicitCaptures);
6038 Record->push_back(Lambda.ManglingNumber);
6039 AddDeclRef(D->getLambdaContextDecl());
6040 AddTypeSourceInfo(Lambda.MethodTyInfo);
6041 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
6042 const LambdaCapture &Capture = Lambda.Captures[I];
6043 AddSourceLocation(Capture.getLocation());
6044 Record->push_back(Capture.isImplicit());
6045 Record->push_back(Capture.getCaptureKind());
6046 switch (Capture.getCaptureKind()) {
6054 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
6056 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
6057 : SourceLocation());
6064 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
6065 assert(Reader && "Cannot remove chain");
6066 assert((!Chain || Chain == Reader) && "Cannot replace chain");
6067 assert(FirstDeclID == NextDeclID &&
6068 FirstTypeID == NextTypeID &&
6069 FirstIdentID == NextIdentID &&
6070 FirstMacroID == NextMacroID &&
6071 FirstSubmoduleID == NextSubmoduleID &&
6072 FirstSelectorID == NextSelectorID &&
6073 "Setting chain after writing has started.");
6077 // Note, this will get called multiple times, once one the reader starts up
6078 // and again each time it's done reading a PCH or module.
6079 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6080 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6081 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6082 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6083 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6084 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6085 NextDeclID = FirstDeclID;
6086 NextTypeID = FirstTypeID;
6087 NextIdentID = FirstIdentID;
6088 NextMacroID = FirstMacroID;
6089 NextSelectorID = FirstSelectorID;
6090 NextSubmoduleID = FirstSubmoduleID;
6093 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6094 // Always keep the highest ID. See \p TypeRead() for more information.
6095 IdentID &StoredID = IdentifierIDs[II];
6100 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6101 // Always keep the highest ID. See \p TypeRead() for more information.
6102 MacroID &StoredID = MacroIDs[MI];
6107 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6108 // Always take the highest-numbered type index. This copes with an interesting
6109 // case for chained AST writing where we schedule writing the type and then,
6110 // later, deserialize the type from another AST. In this case, we want to
6111 // keep the higher-numbered entry so that we can properly write it out to
6113 TypeIdx &StoredIdx = TypeIdxs[T];
6114 if (Idx.getIndex() >= StoredIdx.getIndex())
6118 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6119 // Always keep the highest ID. See \p TypeRead() for more information.
6120 SelectorID &StoredID = SelectorIDs[S];
6125 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6126 MacroDefinitionRecord *MD) {
6127 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
6128 MacroDefinitions[MD] = ID;
6131 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6132 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
6133 SubmoduleIDs[Mod] = ID;
6136 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6137 if (Chain && Chain->isProcessingUpdateRecords()) return;
6138 assert(D->isCompleteDefinition());
6139 assert(!WritingAST && "Already writing the AST!");
6140 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6141 // We are interested when a PCH decl is modified.
6142 if (RD->isFromASTFile()) {
6143 // A forward reference was mutated into a definition. Rewrite it.
6144 // FIXME: This happens during template instantiation, should we
6145 // have created a new definition decl instead ?
6146 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6147 "completed a tag from another module but not by instantiation?");
6148 DeclUpdates[RD].push_back(
6149 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
6154 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6155 if (D->isFromASTFile())
6158 // The predefined __va_list_tag struct is imported if we imported any decls.
6159 // FIXME: This is a gross hack.
6160 return D == D->getASTContext().getVaListTagDecl();
6163 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6164 if (Chain && Chain->isProcessingUpdateRecords()) return;
6165 assert(DC->isLookupContext() &&
6166 "Should not add lookup results to non-lookup contexts!");
6168 // TU is handled elsewhere.
6169 if (isa<TranslationUnitDecl>(DC))
6172 // Namespaces are handled elsewhere, except for template instantiations of
6173 // FunctionTemplateDecls in namespaces. We are interested in cases where the
6174 // local instantiations are added to an imported context. Only happens when
6175 // adding ADL lookup candidates, for example templated friends.
6176 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6177 !isa<FunctionTemplateDecl>(D))
6180 // We're only interested in cases where a local declaration is added to an
6181 // imported context.
6182 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6185 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6186 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6187 assert(!WritingAST && "Already writing the AST!");
6188 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6189 // We're adding a visible declaration to a predefined decl context. Ensure
6190 // that we write out all of its lookup results so we don't get a nasty
6191 // surprise when we try to emit its lookup table.
6192 for (auto *Child : DC->decls())
6193 DeclsToEmitEvenIfUnreferenced.push_back(Child);
6195 DeclsToEmitEvenIfUnreferenced.push_back(D);
6198 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6199 if (Chain && Chain->isProcessingUpdateRecords()) return;
6200 assert(D->isImplicit());
6202 // We're only interested in cases where a local declaration is added to an
6203 // imported context.
6204 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6207 if (!isa<CXXMethodDecl>(D))
6210 // A decl coming from PCH was modified.
6211 assert(RD->isCompleteDefinition());
6212 assert(!WritingAST && "Already writing the AST!");
6213 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6216 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6217 if (Chain && Chain->isProcessingUpdateRecords()) return;
6218 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6220 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6221 // If we don't already know the exception specification for this redecl
6222 // chain, add an update record for it.
6223 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6225 ->castAs<FunctionProtoType>()
6226 ->getExceptionSpecType()))
6227 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6231 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6232 if (Chain && Chain->isProcessingUpdateRecords()) return;
6233 assert(!WritingAST && "Already writing the AST!");
6235 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6236 DeclUpdates[D].push_back(
6237 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6241 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6242 const FunctionDecl *Delete,
6244 if (Chain && Chain->isProcessingUpdateRecords()) return;
6245 assert(!WritingAST && "Already writing the AST!");
6246 assert(Delete && "Not given an operator delete");
6248 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6249 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6253 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6254 if (Chain && Chain->isProcessingUpdateRecords()) return;
6255 assert(!WritingAST && "Already writing the AST!");
6256 if (!D->isFromASTFile())
6257 return; // Declaration not imported from PCH.
6259 // Implicit function decl from a PCH was defined.
6260 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6263 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6264 if (Chain && Chain->isProcessingUpdateRecords()) return;
6265 assert(!WritingAST && "Already writing the AST!");
6266 if (!D->isFromASTFile())
6269 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6272 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6273 if (Chain && Chain->isProcessingUpdateRecords()) return;
6274 assert(!WritingAST && "Already writing the AST!");
6275 if (!D->isFromASTFile())
6278 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6281 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
6282 if (Chain && Chain->isProcessingUpdateRecords()) return;
6283 assert(!WritingAST && "Already writing the AST!");
6284 if (!D->isFromASTFile())
6287 // Since the actual instantiation is delayed, this really means that we need
6288 // to update the instantiation location.
6290 if (auto *VD = dyn_cast<VarDecl>(D))
6291 POI = VD->getPointOfInstantiation();
6293 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6294 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
6297 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6298 if (Chain && Chain->isProcessingUpdateRecords()) return;
6299 assert(!WritingAST && "Already writing the AST!");
6300 if (!D->isFromASTFile())
6303 DeclUpdates[D].push_back(
6304 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6307 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6308 assert(!WritingAST && "Already writing the AST!");
6309 if (!D->isFromASTFile())
6312 DeclUpdates[D].push_back(
6313 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6316 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6317 const ObjCInterfaceDecl *IFD) {
6318 if (Chain && Chain->isProcessingUpdateRecords()) return;
6319 assert(!WritingAST && "Already writing the AST!");
6320 if (!IFD->isFromASTFile())
6321 return; // Declaration not imported from PCH.
6323 assert(IFD->getDefinition() && "Category on a class without a definition?");
6324 ObjCClassesWithCategories.insert(
6325 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6328 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6329 if (Chain && Chain->isProcessingUpdateRecords()) return;
6330 assert(!WritingAST && "Already writing the AST!");
6332 // If there is *any* declaration of the entity that's not from an AST file,
6333 // we can skip writing the update record. We make sure that isUsed() triggers
6334 // completion of the redeclaration chain of the entity.
6335 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6336 if (IsLocalDecl(Prev))
6339 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6342 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6343 if (Chain && Chain->isProcessingUpdateRecords()) return;
6344 assert(!WritingAST && "Already writing the AST!");
6345 if (!D->isFromASTFile())
6348 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6351 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6353 if (Chain && Chain->isProcessingUpdateRecords()) return;
6354 assert(!WritingAST && "Already writing the AST!");
6355 if (!D->isFromASTFile())
6358 DeclUpdates[D].push_back(
6359 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6362 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6363 if (Chain && Chain->isProcessingUpdateRecords()) return;
6364 assert(!WritingAST && "Already writing the AST!");
6365 assert(D->isHidden() && "expected a hidden declaration");
6366 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6369 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6370 const RecordDecl *Record) {
6371 if (Chain && Chain->isProcessingUpdateRecords()) return;
6372 assert(!WritingAST && "Already writing the AST!");
6373 if (!Record->isFromASTFile())
6375 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6378 void ASTWriter::AddedCXXTemplateSpecialization(
6379 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6380 assert(!WritingAST && "Already writing the AST!");
6382 if (!TD->getFirstDecl()->isFromASTFile())
6384 if (Chain && Chain->isProcessingUpdateRecords())
6387 DeclsToEmitEvenIfUnreferenced.push_back(D);
6390 void ASTWriter::AddedCXXTemplateSpecialization(
6391 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6392 assert(!WritingAST && "Already writing the AST!");
6394 if (!TD->getFirstDecl()->isFromASTFile())
6396 if (Chain && Chain->isProcessingUpdateRecords())
6399 DeclsToEmitEvenIfUnreferenced.push_back(D);
6402 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6403 const FunctionDecl *D) {
6404 assert(!WritingAST && "Already writing the AST!");
6406 if (!TD->getFirstDecl()->isFromASTFile())
6408 if (Chain && Chain->isProcessingUpdateRecords())
6411 DeclsToEmitEvenIfUnreferenced.push_back(D);