1 //===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclContextInternals.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/LambdaCapture.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/RawCommentList.h"
30 #include "clang/AST/TemplateName.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLocVisitor.h"
33 #include "clang/Basic/DiagnosticOptions.h"
34 #include "clang/Basic/FileManager.h"
35 #include "clang/Basic/FileSystemOptions.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Basic/LangOptions.h"
38 #include "clang/Basic/MemoryBufferCache.h"
39 #include "clang/Basic/Module.h"
40 #include "clang/Basic/ObjCRuntime.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/SourceManagerInternals.h"
43 #include "clang/Basic/TargetInfo.h"
44 #include "clang/Basic/TargetOptions.h"
45 #include "clang/Basic/Version.h"
46 #include "clang/Basic/VersionTuple.h"
47 #include "clang/Lex/HeaderSearch.h"
48 #include "clang/Lex/HeaderSearchOptions.h"
49 #include "clang/Lex/MacroInfo.h"
50 #include "clang/Lex/ModuleMap.h"
51 #include "clang/Lex/PreprocessingRecord.h"
52 #include "clang/Lex/Preprocessor.h"
53 #include "clang/Lex/PreprocessorOptions.h"
54 #include "clang/Lex/Token.h"
55 #include "clang/Sema/IdentifierResolver.h"
56 #include "clang/Sema/ObjCMethodList.h"
57 #include "clang/Sema/Sema.h"
58 #include "clang/Sema/Weak.h"
59 #include "clang/Serialization/ASTReader.h"
60 #include "clang/Serialization/Module.h"
61 #include "clang/Serialization/ModuleFileExtension.h"
62 #include "clang/Serialization/SerializationDiagnostic.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/Hashing.h"
66 #include "llvm/ADT/IntrusiveRefCntPtr.h"
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/STLExtras.h"
69 #include "llvm/ADT/SmallSet.h"
70 #include "llvm/ADT/SmallString.h"
71 #include "llvm/ADT/StringExtras.h"
72 #include "llvm/Bitcode/BitCodes.h"
73 #include "llvm/Bitcode/BitstreamWriter.h"
74 #include "llvm/Support/Casting.h"
75 #include "llvm/Support/Compression.h"
76 #include "llvm/Support/EndianStream.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/MemoryBuffer.h"
80 #include "llvm/Support/OnDiskHashTable.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/Process.h"
83 #include "llvm/Support/SHA1.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include <algorithm>
86 #include <cassert>
87 #include <cstdint>
88 #include <cstdlib>
89 #include <cstring>
90 #include <deque>
91 #include <limits>
92 #include <new>
93 #include <tuple>
94 #include <utility>
95 
96 using namespace clang;
97 using namespace clang::serialization;
98 
99 template <typename T, typename Allocator>
100 static StringRef bytes(const std::vector<T, Allocator> &v) {
101   if (v.empty()) return StringRef();
102   return StringRef(reinterpret_cast<const char*>(&v[0]),
103                          sizeof(T) * v.size());
104 }
105 
106 template <typename T>
107 static StringRef bytes(const SmallVectorImpl<T> &v) {
108   return StringRef(reinterpret_cast<const char*>(v.data()),
109                          sizeof(T) * v.size());
110 }
111 
112 //===----------------------------------------------------------------------===//
113 // Type serialization
114 //===----------------------------------------------------------------------===//
115 
116 namespace clang {
117 
118   class ASTTypeWriter {
119     ASTWriter &Writer;
120     ASTRecordWriter Record;
121 
122     /// \brief Type code that corresponds to the record generated.
123     TypeCode Code;
124     /// \brief Abbreviation to use for the record, if any.
125     unsigned AbbrevToUse;
126 
127   public:
128     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
129       : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
130 
131     uint64_t Emit() {
132       return Record.Emit(Code, AbbrevToUse);
133     }
134 
135     void Visit(QualType T) {
136       if (T.hasLocalNonFastQualifiers()) {
137         Qualifiers Qs = T.getLocalQualifiers();
138         Record.AddTypeRef(T.getLocalUnqualifiedType());
139         Record.push_back(Qs.getAsOpaqueValue());
140         Code = TYPE_EXT_QUAL;
141         AbbrevToUse = Writer.TypeExtQualAbbrev;
142       } else {
143         switch (T->getTypeClass()) {
144           // For all of the concrete, non-dependent types, call the
145           // appropriate visitor function.
146 #define TYPE(Class, Base) \
147         case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
148 #define ABSTRACT_TYPE(Class, Base)
149 #include "clang/AST/TypeNodes.def"
150         }
151       }
152     }
153 
154     void VisitArrayType(const ArrayType *T);
155     void VisitFunctionType(const FunctionType *T);
156     void VisitTagType(const TagType *T);
157 
158 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
159 #define ABSTRACT_TYPE(Class, Base)
160 #include "clang/AST/TypeNodes.def"
161   };
162 
163 } // end namespace clang
164 
165 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
166   llvm_unreachable("Built-in types are never serialized");
167 }
168 
169 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
170   Record.AddTypeRef(T->getElementType());
171   Code = TYPE_COMPLEX;
172 }
173 
174 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
175   Record.AddTypeRef(T->getPointeeType());
176   Code = TYPE_POINTER;
177 }
178 
179 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
180   Record.AddTypeRef(T->getOriginalType());
181   Code = TYPE_DECAYED;
182 }
183 
184 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
185   Record.AddTypeRef(T->getOriginalType());
186   Record.AddTypeRef(T->getAdjustedType());
187   Code = TYPE_ADJUSTED;
188 }
189 
190 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
191   Record.AddTypeRef(T->getPointeeType());
192   Code = TYPE_BLOCK_POINTER;
193 }
194 
195 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
196   Record.AddTypeRef(T->getPointeeTypeAsWritten());
197   Record.push_back(T->isSpelledAsLValue());
198   Code = TYPE_LVALUE_REFERENCE;
199 }
200 
201 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
202   Record.AddTypeRef(T->getPointeeTypeAsWritten());
203   Code = TYPE_RVALUE_REFERENCE;
204 }
205 
206 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
207   Record.AddTypeRef(T->getPointeeType());
208   Record.AddTypeRef(QualType(T->getClass(), 0));
209   Code = TYPE_MEMBER_POINTER;
210 }
211 
212 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
213   Record.AddTypeRef(T->getElementType());
214   Record.push_back(T->getSizeModifier()); // FIXME: stable values
215   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
216 }
217 
218 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
219   VisitArrayType(T);
220   Record.AddAPInt(T->getSize());
221   Code = TYPE_CONSTANT_ARRAY;
222 }
223 
224 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
225   VisitArrayType(T);
226   Code = TYPE_INCOMPLETE_ARRAY;
227 }
228 
229 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
230   VisitArrayType(T);
231   Record.AddSourceLocation(T->getLBracketLoc());
232   Record.AddSourceLocation(T->getRBracketLoc());
233   Record.AddStmt(T->getSizeExpr());
234   Code = TYPE_VARIABLE_ARRAY;
235 }
236 
237 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
238   Record.AddTypeRef(T->getElementType());
239   Record.push_back(T->getNumElements());
240   Record.push_back(T->getVectorKind());
241   Code = TYPE_VECTOR;
242 }
243 
244 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
245   VisitVectorType(T);
246   Code = TYPE_EXT_VECTOR;
247 }
248 
249 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
250   Record.AddTypeRef(T->getReturnType());
251   FunctionType::ExtInfo C = T->getExtInfo();
252   Record.push_back(C.getNoReturn());
253   Record.push_back(C.getHasRegParm());
254   Record.push_back(C.getRegParm());
255   // FIXME: need to stabilize encoding of calling convention...
256   Record.push_back(C.getCC());
257   Record.push_back(C.getProducesResult());
258   Record.push_back(C.getNoCallerSavedRegs());
259 
260   if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
261     AbbrevToUse = 0;
262 }
263 
264 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
265   VisitFunctionType(T);
266   Code = TYPE_FUNCTION_NO_PROTO;
267 }
268 
269 static void addExceptionSpec(const FunctionProtoType *T,
270                              ASTRecordWriter &Record) {
271   Record.push_back(T->getExceptionSpecType());
272   if (T->getExceptionSpecType() == EST_Dynamic) {
273     Record.push_back(T->getNumExceptions());
274     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
275       Record.AddTypeRef(T->getExceptionType(I));
276   } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
277     Record.AddStmt(T->getNoexceptExpr());
278   } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
279     Record.AddDeclRef(T->getExceptionSpecDecl());
280     Record.AddDeclRef(T->getExceptionSpecTemplate());
281   } else if (T->getExceptionSpecType() == EST_Unevaluated) {
282     Record.AddDeclRef(T->getExceptionSpecDecl());
283   }
284 }
285 
286 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
287   VisitFunctionType(T);
288 
289   Record.push_back(T->isVariadic());
290   Record.push_back(T->hasTrailingReturn());
291   Record.push_back(T->getTypeQuals());
292   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
293   addExceptionSpec(T, Record);
294 
295   Record.push_back(T->getNumParams());
296   for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
297     Record.AddTypeRef(T->getParamType(I));
298 
299   if (T->hasExtParameterInfos()) {
300     for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
301       Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
302   }
303 
304   if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
305       T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
306       T->hasExtParameterInfos())
307     AbbrevToUse = 0;
308 
309   Code = TYPE_FUNCTION_PROTO;
310 }
311 
312 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
313   Record.AddDeclRef(T->getDecl());
314   Code = TYPE_UNRESOLVED_USING;
315 }
316 
317 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
318   Record.AddDeclRef(T->getDecl());
319   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
320   Record.AddTypeRef(T->getCanonicalTypeInternal());
321   Code = TYPE_TYPEDEF;
322 }
323 
324 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
325   Record.AddStmt(T->getUnderlyingExpr());
326   Code = TYPE_TYPEOF_EXPR;
327 }
328 
329 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
330   Record.AddTypeRef(T->getUnderlyingType());
331   Code = TYPE_TYPEOF;
332 }
333 
334 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
335   Record.AddTypeRef(T->getUnderlyingType());
336   Record.AddStmt(T->getUnderlyingExpr());
337   Code = TYPE_DECLTYPE;
338 }
339 
340 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
341   Record.AddTypeRef(T->getBaseType());
342   Record.AddTypeRef(T->getUnderlyingType());
343   Record.push_back(T->getUTTKind());
344   Code = TYPE_UNARY_TRANSFORM;
345 }
346 
347 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
348   Record.AddTypeRef(T->getDeducedType());
349   Record.push_back((unsigned)T->getKeyword());
350   if (T->getDeducedType().isNull())
351     Record.push_back(T->isDependentType());
352   Code = TYPE_AUTO;
353 }
354 
355 void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
356     const DeducedTemplateSpecializationType *T) {
357   Record.AddTemplateName(T->getTemplateName());
358   Record.AddTypeRef(T->getDeducedType());
359   if (T->getDeducedType().isNull())
360     Record.push_back(T->isDependentType());
361   Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
362 }
363 
364 void ASTTypeWriter::VisitTagType(const TagType *T) {
365   Record.push_back(T->isDependentType());
366   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
367   assert(!T->isBeingDefined() &&
368          "Cannot serialize in the middle of a type definition");
369 }
370 
371 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
372   VisitTagType(T);
373   Code = TYPE_RECORD;
374 }
375 
376 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
377   VisitTagType(T);
378   Code = TYPE_ENUM;
379 }
380 
381 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
382   Record.AddTypeRef(T->getModifiedType());
383   Record.AddTypeRef(T->getEquivalentType());
384   Record.push_back(T->getAttrKind());
385   Code = TYPE_ATTRIBUTED;
386 }
387 
388 void
389 ASTTypeWriter::VisitSubstTemplateTypeParmType(
390                                         const SubstTemplateTypeParmType *T) {
391   Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
392   Record.AddTypeRef(T->getReplacementType());
393   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
394 }
395 
396 void
397 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
398                                       const SubstTemplateTypeParmPackType *T) {
399   Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
400   Record.AddTemplateArgument(T->getArgumentPack());
401   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
402 }
403 
404 void
405 ASTTypeWriter::VisitTemplateSpecializationType(
406                                        const TemplateSpecializationType *T) {
407   Record.push_back(T->isDependentType());
408   Record.AddTemplateName(T->getTemplateName());
409   Record.push_back(T->getNumArgs());
410   for (const auto &ArgI : *T)
411     Record.AddTemplateArgument(ArgI);
412   Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
413                                      : T->isCanonicalUnqualified()
414                                            ? QualType()
415                                            : T->getCanonicalTypeInternal());
416   Code = TYPE_TEMPLATE_SPECIALIZATION;
417 }
418 
419 void
420 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
421   VisitArrayType(T);
422   Record.AddStmt(T->getSizeExpr());
423   Record.AddSourceRange(T->getBracketsRange());
424   Code = TYPE_DEPENDENT_SIZED_ARRAY;
425 }
426 
427 void
428 ASTTypeWriter::VisitDependentSizedExtVectorType(
429                                         const DependentSizedExtVectorType *T) {
430   Record.AddTypeRef(T->getElementType());
431   Record.AddStmt(T->getSizeExpr());
432   Record.AddSourceLocation(T->getAttributeLoc());
433   Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
434 }
435 
436 void
437 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
438   Record.push_back(T->getDepth());
439   Record.push_back(T->getIndex());
440   Record.push_back(T->isParameterPack());
441   Record.AddDeclRef(T->getDecl());
442   Code = TYPE_TEMPLATE_TYPE_PARM;
443 }
444 
445 void
446 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
447   Record.push_back(T->getKeyword());
448   Record.AddNestedNameSpecifier(T->getQualifier());
449   Record.AddIdentifierRef(T->getIdentifier());
450   Record.AddTypeRef(
451       T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
452   Code = TYPE_DEPENDENT_NAME;
453 }
454 
455 void
456 ASTTypeWriter::VisitDependentTemplateSpecializationType(
457                                 const DependentTemplateSpecializationType *T) {
458   Record.push_back(T->getKeyword());
459   Record.AddNestedNameSpecifier(T->getQualifier());
460   Record.AddIdentifierRef(T->getIdentifier());
461   Record.push_back(T->getNumArgs());
462   for (const auto &I : *T)
463     Record.AddTemplateArgument(I);
464   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
465 }
466 
467 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
468   Record.AddTypeRef(T->getPattern());
469   if (Optional<unsigned> NumExpansions = T->getNumExpansions())
470     Record.push_back(*NumExpansions + 1);
471   else
472     Record.push_back(0);
473   Code = TYPE_PACK_EXPANSION;
474 }
475 
476 void ASTTypeWriter::VisitParenType(const ParenType *T) {
477   Record.AddTypeRef(T->getInnerType());
478   Code = TYPE_PAREN;
479 }
480 
481 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
482   Record.push_back(T->getKeyword());
483   Record.AddNestedNameSpecifier(T->getQualifier());
484   Record.AddTypeRef(T->getNamedType());
485   Code = TYPE_ELABORATED;
486 }
487 
488 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
489   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
490   Record.AddTypeRef(T->getInjectedSpecializationType());
491   Code = TYPE_INJECTED_CLASS_NAME;
492 }
493 
494 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
495   Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
496   Code = TYPE_OBJC_INTERFACE;
497 }
498 
499 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
500   Record.AddDeclRef(T->getDecl());
501   Record.push_back(T->getNumProtocols());
502   for (const auto *I : T->quals())
503     Record.AddDeclRef(I);
504   Code = TYPE_OBJC_TYPE_PARAM;
505 }
506 
507 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
508   Record.AddTypeRef(T->getBaseType());
509   Record.push_back(T->getTypeArgsAsWritten().size());
510   for (auto TypeArg : T->getTypeArgsAsWritten())
511     Record.AddTypeRef(TypeArg);
512   Record.push_back(T->getNumProtocols());
513   for (const auto *I : T->quals())
514     Record.AddDeclRef(I);
515   Record.push_back(T->isKindOfTypeAsWritten());
516   Code = TYPE_OBJC_OBJECT;
517 }
518 
519 void
520 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
521   Record.AddTypeRef(T->getPointeeType());
522   Code = TYPE_OBJC_OBJECT_POINTER;
523 }
524 
525 void
526 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
527   Record.AddTypeRef(T->getValueType());
528   Code = TYPE_ATOMIC;
529 }
530 
531 void
532 ASTTypeWriter::VisitPipeType(const PipeType *T) {
533   Record.AddTypeRef(T->getElementType());
534   Record.push_back(T->isReadOnly());
535   Code = TYPE_PIPE;
536 }
537 
538 namespace {
539 
540 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
541   ASTRecordWriter &Record;
542 
543 public:
544   TypeLocWriter(ASTRecordWriter &Record)
545     : Record(Record) { }
546 
547 #define ABSTRACT_TYPELOC(CLASS, PARENT)
548 #define TYPELOC(CLASS, PARENT) \
549     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
550 #include "clang/AST/TypeLocNodes.def"
551 
552   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
553   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
554 };
555 
556 } // end anonymous namespace
557 
558 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
559   // nothing to do
560 }
561 
562 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
563   Record.AddSourceLocation(TL.getBuiltinLoc());
564   if (TL.needsExtraLocalData()) {
565     Record.push_back(TL.getWrittenTypeSpec());
566     Record.push_back(TL.getWrittenSignSpec());
567     Record.push_back(TL.getWrittenWidthSpec());
568     Record.push_back(TL.hasModeAttr());
569   }
570 }
571 
572 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
573   Record.AddSourceLocation(TL.getNameLoc());
574 }
575 
576 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
577   Record.AddSourceLocation(TL.getStarLoc());
578 }
579 
580 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
581   // nothing to do
582 }
583 
584 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
585   // nothing to do
586 }
587 
588 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
589   Record.AddSourceLocation(TL.getCaretLoc());
590 }
591 
592 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
593   Record.AddSourceLocation(TL.getAmpLoc());
594 }
595 
596 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
597   Record.AddSourceLocation(TL.getAmpAmpLoc());
598 }
599 
600 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
601   Record.AddSourceLocation(TL.getStarLoc());
602   Record.AddTypeSourceInfo(TL.getClassTInfo());
603 }
604 
605 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
606   Record.AddSourceLocation(TL.getLBracketLoc());
607   Record.AddSourceLocation(TL.getRBracketLoc());
608   Record.push_back(TL.getSizeExpr() ? 1 : 0);
609   if (TL.getSizeExpr())
610     Record.AddStmt(TL.getSizeExpr());
611 }
612 
613 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
614   VisitArrayTypeLoc(TL);
615 }
616 
617 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
618   VisitArrayTypeLoc(TL);
619 }
620 
621 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
622   VisitArrayTypeLoc(TL);
623 }
624 
625 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
626                                             DependentSizedArrayTypeLoc TL) {
627   VisitArrayTypeLoc(TL);
628 }
629 
630 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
631                                         DependentSizedExtVectorTypeLoc TL) {
632   Record.AddSourceLocation(TL.getNameLoc());
633 }
634 
635 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
636   Record.AddSourceLocation(TL.getNameLoc());
637 }
638 
639 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
640   Record.AddSourceLocation(TL.getNameLoc());
641 }
642 
643 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
644   Record.AddSourceLocation(TL.getLocalRangeBegin());
645   Record.AddSourceLocation(TL.getLParenLoc());
646   Record.AddSourceLocation(TL.getRParenLoc());
647   Record.AddSourceRange(TL.getExceptionSpecRange());
648   Record.AddSourceLocation(TL.getLocalRangeEnd());
649   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
650     Record.AddDeclRef(TL.getParam(i));
651 }
652 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
653   VisitFunctionTypeLoc(TL);
654 }
655 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
656   VisitFunctionTypeLoc(TL);
657 }
658 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
659   Record.AddSourceLocation(TL.getNameLoc());
660 }
661 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
662   Record.AddSourceLocation(TL.getNameLoc());
663 }
664 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
665   if (TL.getNumProtocols()) {
666     Record.AddSourceLocation(TL.getProtocolLAngleLoc());
667     Record.AddSourceLocation(TL.getProtocolRAngleLoc());
668   }
669   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
670     Record.AddSourceLocation(TL.getProtocolLoc(i));
671 }
672 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
673   Record.AddSourceLocation(TL.getTypeofLoc());
674   Record.AddSourceLocation(TL.getLParenLoc());
675   Record.AddSourceLocation(TL.getRParenLoc());
676 }
677 
678 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
679   Record.AddSourceLocation(TL.getTypeofLoc());
680   Record.AddSourceLocation(TL.getLParenLoc());
681   Record.AddSourceLocation(TL.getRParenLoc());
682   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
683 }
684 
685 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
686   Record.AddSourceLocation(TL.getNameLoc());
687 }
688 
689 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
690   Record.AddSourceLocation(TL.getKWLoc());
691   Record.AddSourceLocation(TL.getLParenLoc());
692   Record.AddSourceLocation(TL.getRParenLoc());
693   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
694 }
695 
696 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
697   Record.AddSourceLocation(TL.getNameLoc());
698 }
699 
700 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
701     DeducedTemplateSpecializationTypeLoc TL) {
702   Record.AddSourceLocation(TL.getTemplateNameLoc());
703 }
704 
705 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
706   Record.AddSourceLocation(TL.getNameLoc());
707 }
708 
709 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
710   Record.AddSourceLocation(TL.getNameLoc());
711 }
712 
713 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
714   Record.AddSourceLocation(TL.getAttrNameLoc());
715   if (TL.hasAttrOperand()) {
716     SourceRange range = TL.getAttrOperandParensRange();
717     Record.AddSourceLocation(range.getBegin());
718     Record.AddSourceLocation(range.getEnd());
719   }
720   if (TL.hasAttrExprOperand()) {
721     Expr *operand = TL.getAttrExprOperand();
722     Record.push_back(operand ? 1 : 0);
723     if (operand) Record.AddStmt(operand);
724   } else if (TL.hasAttrEnumOperand()) {
725     Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
726   }
727 }
728 
729 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
730   Record.AddSourceLocation(TL.getNameLoc());
731 }
732 
733 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
734                                             SubstTemplateTypeParmTypeLoc TL) {
735   Record.AddSourceLocation(TL.getNameLoc());
736 }
737 
738 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
739                                           SubstTemplateTypeParmPackTypeLoc TL) {
740   Record.AddSourceLocation(TL.getNameLoc());
741 }
742 
743 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
744                                            TemplateSpecializationTypeLoc TL) {
745   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
746   Record.AddSourceLocation(TL.getTemplateNameLoc());
747   Record.AddSourceLocation(TL.getLAngleLoc());
748   Record.AddSourceLocation(TL.getRAngleLoc());
749   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
750     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
751                                       TL.getArgLoc(i).getLocInfo());
752 }
753 
754 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
755   Record.AddSourceLocation(TL.getLParenLoc());
756   Record.AddSourceLocation(TL.getRParenLoc());
757 }
758 
759 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
760   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
761   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
762 }
763 
764 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
765   Record.AddSourceLocation(TL.getNameLoc());
766 }
767 
768 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
769   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
770   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
771   Record.AddSourceLocation(TL.getNameLoc());
772 }
773 
774 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
775        DependentTemplateSpecializationTypeLoc TL) {
776   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
777   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
778   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
779   Record.AddSourceLocation(TL.getTemplateNameLoc());
780   Record.AddSourceLocation(TL.getLAngleLoc());
781   Record.AddSourceLocation(TL.getRAngleLoc());
782   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
783     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
784                                       TL.getArgLoc(I).getLocInfo());
785 }
786 
787 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
788   Record.AddSourceLocation(TL.getEllipsisLoc());
789 }
790 
791 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
792   Record.AddSourceLocation(TL.getNameLoc());
793 }
794 
795 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
796   Record.push_back(TL.hasBaseTypeAsWritten());
797   Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
798   Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
799   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
800     Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
801   Record.AddSourceLocation(TL.getProtocolLAngleLoc());
802   Record.AddSourceLocation(TL.getProtocolRAngleLoc());
803   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
804     Record.AddSourceLocation(TL.getProtocolLoc(i));
805 }
806 
807 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
808   Record.AddSourceLocation(TL.getStarLoc());
809 }
810 
811 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
812   Record.AddSourceLocation(TL.getKWLoc());
813   Record.AddSourceLocation(TL.getLParenLoc());
814   Record.AddSourceLocation(TL.getRParenLoc());
815 }
816 
817 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
818   Record.AddSourceLocation(TL.getKWLoc());
819 }
820 
821 void ASTWriter::WriteTypeAbbrevs() {
822   using namespace llvm;
823 
824   std::shared_ptr<BitCodeAbbrev> Abv;
825 
826   // Abbreviation for TYPE_EXT_QUAL
827   Abv = std::make_shared<BitCodeAbbrev>();
828   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
829   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
830   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
831   TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
832 
833   // Abbreviation for TYPE_FUNCTION_PROTO
834   Abv = std::make_shared<BitCodeAbbrev>();
835   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
836   // FunctionType
837   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // ReturnType
838   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
839   Abv->Add(BitCodeAbbrevOp(0));                         // HasRegParm
840   Abv->Add(BitCodeAbbrevOp(0));                         // RegParm
841   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
842   Abv->Add(BitCodeAbbrevOp(0));                         // ProducesResult
843   Abv->Add(BitCodeAbbrevOp(0));                         // NoCallerSavedRegs
844   // FunctionProtoType
845   Abv->Add(BitCodeAbbrevOp(0));                         // IsVariadic
846   Abv->Add(BitCodeAbbrevOp(0));                         // HasTrailingReturn
847   Abv->Add(BitCodeAbbrevOp(0));                         // TypeQuals
848   Abv->Add(BitCodeAbbrevOp(0));                         // RefQualifier
849   Abv->Add(BitCodeAbbrevOp(EST_None));                  // ExceptionSpec
850   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // NumParams
851   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
852   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Params
853   TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
854 }
855 
856 //===----------------------------------------------------------------------===//
857 // ASTWriter Implementation
858 //===----------------------------------------------------------------------===//
859 
860 static void EmitBlockID(unsigned ID, const char *Name,
861                         llvm::BitstreamWriter &Stream,
862                         ASTWriter::RecordDataImpl &Record) {
863   Record.clear();
864   Record.push_back(ID);
865   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
866 
867   // Emit the block name if present.
868   if (!Name || Name[0] == 0)
869     return;
870   Record.clear();
871   while (*Name)
872     Record.push_back(*Name++);
873   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
874 }
875 
876 static void EmitRecordID(unsigned ID, const char *Name,
877                          llvm::BitstreamWriter &Stream,
878                          ASTWriter::RecordDataImpl &Record) {
879   Record.clear();
880   Record.push_back(ID);
881   while (*Name)
882     Record.push_back(*Name++);
883   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
884 }
885 
886 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
887                           ASTWriter::RecordDataImpl &Record) {
888 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
889   RECORD(STMT_STOP);
890   RECORD(STMT_NULL_PTR);
891   RECORD(STMT_REF_PTR);
892   RECORD(STMT_NULL);
893   RECORD(STMT_COMPOUND);
894   RECORD(STMT_CASE);
895   RECORD(STMT_DEFAULT);
896   RECORD(STMT_LABEL);
897   RECORD(STMT_ATTRIBUTED);
898   RECORD(STMT_IF);
899   RECORD(STMT_SWITCH);
900   RECORD(STMT_WHILE);
901   RECORD(STMT_DO);
902   RECORD(STMT_FOR);
903   RECORD(STMT_GOTO);
904   RECORD(STMT_INDIRECT_GOTO);
905   RECORD(STMT_CONTINUE);
906   RECORD(STMT_BREAK);
907   RECORD(STMT_RETURN);
908   RECORD(STMT_DECL);
909   RECORD(STMT_GCCASM);
910   RECORD(STMT_MSASM);
911   RECORD(EXPR_PREDEFINED);
912   RECORD(EXPR_DECL_REF);
913   RECORD(EXPR_INTEGER_LITERAL);
914   RECORD(EXPR_FLOATING_LITERAL);
915   RECORD(EXPR_IMAGINARY_LITERAL);
916   RECORD(EXPR_STRING_LITERAL);
917   RECORD(EXPR_CHARACTER_LITERAL);
918   RECORD(EXPR_PAREN);
919   RECORD(EXPR_PAREN_LIST);
920   RECORD(EXPR_UNARY_OPERATOR);
921   RECORD(EXPR_SIZEOF_ALIGN_OF);
922   RECORD(EXPR_ARRAY_SUBSCRIPT);
923   RECORD(EXPR_CALL);
924   RECORD(EXPR_MEMBER);
925   RECORD(EXPR_BINARY_OPERATOR);
926   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
927   RECORD(EXPR_CONDITIONAL_OPERATOR);
928   RECORD(EXPR_IMPLICIT_CAST);
929   RECORD(EXPR_CSTYLE_CAST);
930   RECORD(EXPR_COMPOUND_LITERAL);
931   RECORD(EXPR_EXT_VECTOR_ELEMENT);
932   RECORD(EXPR_INIT_LIST);
933   RECORD(EXPR_DESIGNATED_INIT);
934   RECORD(EXPR_DESIGNATED_INIT_UPDATE);
935   RECORD(EXPR_IMPLICIT_VALUE_INIT);
936   RECORD(EXPR_NO_INIT);
937   RECORD(EXPR_VA_ARG);
938   RECORD(EXPR_ADDR_LABEL);
939   RECORD(EXPR_STMT);
940   RECORD(EXPR_CHOOSE);
941   RECORD(EXPR_GNU_NULL);
942   RECORD(EXPR_SHUFFLE_VECTOR);
943   RECORD(EXPR_BLOCK);
944   RECORD(EXPR_GENERIC_SELECTION);
945   RECORD(EXPR_OBJC_STRING_LITERAL);
946   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
947   RECORD(EXPR_OBJC_ARRAY_LITERAL);
948   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
949   RECORD(EXPR_OBJC_ENCODE);
950   RECORD(EXPR_OBJC_SELECTOR_EXPR);
951   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
952   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
953   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
954   RECORD(EXPR_OBJC_KVC_REF_EXPR);
955   RECORD(EXPR_OBJC_MESSAGE_EXPR);
956   RECORD(STMT_OBJC_FOR_COLLECTION);
957   RECORD(STMT_OBJC_CATCH);
958   RECORD(STMT_OBJC_FINALLY);
959   RECORD(STMT_OBJC_AT_TRY);
960   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
961   RECORD(STMT_OBJC_AT_THROW);
962   RECORD(EXPR_OBJC_BOOL_LITERAL);
963   RECORD(STMT_CXX_CATCH);
964   RECORD(STMT_CXX_TRY);
965   RECORD(STMT_CXX_FOR_RANGE);
966   RECORD(EXPR_CXX_OPERATOR_CALL);
967   RECORD(EXPR_CXX_MEMBER_CALL);
968   RECORD(EXPR_CXX_CONSTRUCT);
969   RECORD(EXPR_CXX_TEMPORARY_OBJECT);
970   RECORD(EXPR_CXX_STATIC_CAST);
971   RECORD(EXPR_CXX_DYNAMIC_CAST);
972   RECORD(EXPR_CXX_REINTERPRET_CAST);
973   RECORD(EXPR_CXX_CONST_CAST);
974   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
975   RECORD(EXPR_USER_DEFINED_LITERAL);
976   RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
977   RECORD(EXPR_CXX_BOOL_LITERAL);
978   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
979   RECORD(EXPR_CXX_TYPEID_EXPR);
980   RECORD(EXPR_CXX_TYPEID_TYPE);
981   RECORD(EXPR_CXX_THIS);
982   RECORD(EXPR_CXX_THROW);
983   RECORD(EXPR_CXX_DEFAULT_ARG);
984   RECORD(EXPR_CXX_DEFAULT_INIT);
985   RECORD(EXPR_CXX_BIND_TEMPORARY);
986   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
987   RECORD(EXPR_CXX_NEW);
988   RECORD(EXPR_CXX_DELETE);
989   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
990   RECORD(EXPR_EXPR_WITH_CLEANUPS);
991   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
992   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
993   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
994   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
995   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
996   RECORD(EXPR_CXX_EXPRESSION_TRAIT);
997   RECORD(EXPR_CXX_NOEXCEPT);
998   RECORD(EXPR_OPAQUE_VALUE);
999   RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1000   RECORD(EXPR_TYPE_TRAIT);
1001   RECORD(EXPR_ARRAY_TYPE_TRAIT);
1002   RECORD(EXPR_PACK_EXPANSION);
1003   RECORD(EXPR_SIZEOF_PACK);
1004   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
1005   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
1006   RECORD(EXPR_FUNCTION_PARM_PACK);
1007   RECORD(EXPR_MATERIALIZE_TEMPORARY);
1008   RECORD(EXPR_CUDA_KERNEL_CALL);
1009   RECORD(EXPR_CXX_UUIDOF_EXPR);
1010   RECORD(EXPR_CXX_UUIDOF_TYPE);
1011   RECORD(EXPR_LAMBDA);
1012 #undef RECORD
1013 }
1014 
1015 void ASTWriter::WriteBlockInfoBlock() {
1016   RecordData Record;
1017   Stream.EnterBlockInfoBlock();
1018 
1019 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1020 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1021 
1022   // Control Block.
1023   BLOCK(CONTROL_BLOCK);
1024   RECORD(METADATA);
1025   RECORD(MODULE_NAME);
1026   RECORD(MODULE_DIRECTORY);
1027   RECORD(MODULE_MAP_FILE);
1028   RECORD(IMPORTS);
1029   RECORD(ORIGINAL_FILE);
1030   RECORD(ORIGINAL_PCH_DIR);
1031   RECORD(ORIGINAL_FILE_ID);
1032   RECORD(INPUT_FILE_OFFSETS);
1033 
1034   BLOCK(OPTIONS_BLOCK);
1035   RECORD(LANGUAGE_OPTIONS);
1036   RECORD(TARGET_OPTIONS);
1037   RECORD(FILE_SYSTEM_OPTIONS);
1038   RECORD(HEADER_SEARCH_OPTIONS);
1039   RECORD(PREPROCESSOR_OPTIONS);
1040 
1041   BLOCK(INPUT_FILES_BLOCK);
1042   RECORD(INPUT_FILE);
1043 
1044   // AST Top-Level Block.
1045   BLOCK(AST_BLOCK);
1046   RECORD(TYPE_OFFSET);
1047   RECORD(DECL_OFFSET);
1048   RECORD(IDENTIFIER_OFFSET);
1049   RECORD(IDENTIFIER_TABLE);
1050   RECORD(EAGERLY_DESERIALIZED_DECLS);
1051   RECORD(MODULAR_CODEGEN_DECLS);
1052   RECORD(SPECIAL_TYPES);
1053   RECORD(STATISTICS);
1054   RECORD(TENTATIVE_DEFINITIONS);
1055   RECORD(SELECTOR_OFFSETS);
1056   RECORD(METHOD_POOL);
1057   RECORD(PP_COUNTER_VALUE);
1058   RECORD(SOURCE_LOCATION_OFFSETS);
1059   RECORD(SOURCE_LOCATION_PRELOADS);
1060   RECORD(EXT_VECTOR_DECLS);
1061   RECORD(UNUSED_FILESCOPED_DECLS);
1062   RECORD(PPD_ENTITIES_OFFSETS);
1063   RECORD(VTABLE_USES);
1064   RECORD(REFERENCED_SELECTOR_POOL);
1065   RECORD(TU_UPDATE_LEXICAL);
1066   RECORD(SEMA_DECL_REFS);
1067   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1068   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
1069   RECORD(UPDATE_VISIBLE);
1070   RECORD(DECL_UPDATE_OFFSETS);
1071   RECORD(DECL_UPDATES);
1072   RECORD(CUDA_SPECIAL_DECL_REFS);
1073   RECORD(HEADER_SEARCH_TABLE);
1074   RECORD(FP_PRAGMA_OPTIONS);
1075   RECORD(OPENCL_EXTENSIONS);
1076   RECORD(OPENCL_EXTENSION_TYPES);
1077   RECORD(OPENCL_EXTENSION_DECLS);
1078   RECORD(DELEGATING_CTORS);
1079   RECORD(KNOWN_NAMESPACES);
1080   RECORD(MODULE_OFFSET_MAP);
1081   RECORD(SOURCE_MANAGER_LINE_TABLE);
1082   RECORD(OBJC_CATEGORIES_MAP);
1083   RECORD(FILE_SORTED_DECLS);
1084   RECORD(IMPORTED_MODULES);
1085   RECORD(OBJC_CATEGORIES);
1086   RECORD(MACRO_OFFSET);
1087   RECORD(INTERESTING_IDENTIFIERS);
1088   RECORD(UNDEFINED_BUT_USED);
1089   RECORD(LATE_PARSED_TEMPLATE);
1090   RECORD(OPTIMIZE_PRAGMA_OPTIONS);
1091   RECORD(MSSTRUCT_PRAGMA_OPTIONS);
1092   RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
1093   RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
1094   RECORD(DELETE_EXPRS_TO_ANALYZE);
1095   RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
1096   RECORD(PP_CONDITIONAL_STACK);
1097 
1098   // SourceManager Block.
1099   BLOCK(SOURCE_MANAGER_BLOCK);
1100   RECORD(SM_SLOC_FILE_ENTRY);
1101   RECORD(SM_SLOC_BUFFER_ENTRY);
1102   RECORD(SM_SLOC_BUFFER_BLOB);
1103   RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
1104   RECORD(SM_SLOC_EXPANSION_ENTRY);
1105 
1106   // Preprocessor Block.
1107   BLOCK(PREPROCESSOR_BLOCK);
1108   RECORD(PP_MACRO_DIRECTIVE_HISTORY);
1109   RECORD(PP_MACRO_FUNCTION_LIKE);
1110   RECORD(PP_MACRO_OBJECT_LIKE);
1111   RECORD(PP_MODULE_MACRO);
1112   RECORD(PP_TOKEN);
1113 
1114   // Submodule Block.
1115   BLOCK(SUBMODULE_BLOCK);
1116   RECORD(SUBMODULE_METADATA);
1117   RECORD(SUBMODULE_DEFINITION);
1118   RECORD(SUBMODULE_UMBRELLA_HEADER);
1119   RECORD(SUBMODULE_HEADER);
1120   RECORD(SUBMODULE_TOPHEADER);
1121   RECORD(SUBMODULE_UMBRELLA_DIR);
1122   RECORD(SUBMODULE_IMPORTS);
1123   RECORD(SUBMODULE_EXPORTS);
1124   RECORD(SUBMODULE_REQUIRES);
1125   RECORD(SUBMODULE_EXCLUDED_HEADER);
1126   RECORD(SUBMODULE_LINK_LIBRARY);
1127   RECORD(SUBMODULE_CONFIG_MACRO);
1128   RECORD(SUBMODULE_CONFLICT);
1129   RECORD(SUBMODULE_PRIVATE_HEADER);
1130   RECORD(SUBMODULE_TEXTUAL_HEADER);
1131   RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1132   RECORD(SUBMODULE_INITIALIZERS);
1133   RECORD(SUBMODULE_EXPORT_AS);
1134 
1135   // Comments Block.
1136   BLOCK(COMMENTS_BLOCK);
1137   RECORD(COMMENTS_RAW_COMMENT);
1138 
1139   // Decls and Types block.
1140   BLOCK(DECLTYPES_BLOCK);
1141   RECORD(TYPE_EXT_QUAL);
1142   RECORD(TYPE_COMPLEX);
1143   RECORD(TYPE_POINTER);
1144   RECORD(TYPE_BLOCK_POINTER);
1145   RECORD(TYPE_LVALUE_REFERENCE);
1146   RECORD(TYPE_RVALUE_REFERENCE);
1147   RECORD(TYPE_MEMBER_POINTER);
1148   RECORD(TYPE_CONSTANT_ARRAY);
1149   RECORD(TYPE_INCOMPLETE_ARRAY);
1150   RECORD(TYPE_VARIABLE_ARRAY);
1151   RECORD(TYPE_VECTOR);
1152   RECORD(TYPE_EXT_VECTOR);
1153   RECORD(TYPE_FUNCTION_NO_PROTO);
1154   RECORD(TYPE_FUNCTION_PROTO);
1155   RECORD(TYPE_TYPEDEF);
1156   RECORD(TYPE_TYPEOF_EXPR);
1157   RECORD(TYPE_TYPEOF);
1158   RECORD(TYPE_RECORD);
1159   RECORD(TYPE_ENUM);
1160   RECORD(TYPE_OBJC_INTERFACE);
1161   RECORD(TYPE_OBJC_OBJECT_POINTER);
1162   RECORD(TYPE_DECLTYPE);
1163   RECORD(TYPE_ELABORATED);
1164   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1165   RECORD(TYPE_UNRESOLVED_USING);
1166   RECORD(TYPE_INJECTED_CLASS_NAME);
1167   RECORD(TYPE_OBJC_OBJECT);
1168   RECORD(TYPE_TEMPLATE_TYPE_PARM);
1169   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1170   RECORD(TYPE_DEPENDENT_NAME);
1171   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1172   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1173   RECORD(TYPE_PAREN);
1174   RECORD(TYPE_PACK_EXPANSION);
1175   RECORD(TYPE_ATTRIBUTED);
1176   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
1177   RECORD(TYPE_AUTO);
1178   RECORD(TYPE_UNARY_TRANSFORM);
1179   RECORD(TYPE_ATOMIC);
1180   RECORD(TYPE_DECAYED);
1181   RECORD(TYPE_ADJUSTED);
1182   RECORD(TYPE_OBJC_TYPE_PARAM);
1183   RECORD(LOCAL_REDECLARATIONS);
1184   RECORD(DECL_TYPEDEF);
1185   RECORD(DECL_TYPEALIAS);
1186   RECORD(DECL_ENUM);
1187   RECORD(DECL_RECORD);
1188   RECORD(DECL_ENUM_CONSTANT);
1189   RECORD(DECL_FUNCTION);
1190   RECORD(DECL_OBJC_METHOD);
1191   RECORD(DECL_OBJC_INTERFACE);
1192   RECORD(DECL_OBJC_PROTOCOL);
1193   RECORD(DECL_OBJC_IVAR);
1194   RECORD(DECL_OBJC_AT_DEFS_FIELD);
1195   RECORD(DECL_OBJC_CATEGORY);
1196   RECORD(DECL_OBJC_CATEGORY_IMPL);
1197   RECORD(DECL_OBJC_IMPLEMENTATION);
1198   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1199   RECORD(DECL_OBJC_PROPERTY);
1200   RECORD(DECL_OBJC_PROPERTY_IMPL);
1201   RECORD(DECL_FIELD);
1202   RECORD(DECL_MS_PROPERTY);
1203   RECORD(DECL_VAR);
1204   RECORD(DECL_IMPLICIT_PARAM);
1205   RECORD(DECL_PARM_VAR);
1206   RECORD(DECL_FILE_SCOPE_ASM);
1207   RECORD(DECL_BLOCK);
1208   RECORD(DECL_CONTEXT_LEXICAL);
1209   RECORD(DECL_CONTEXT_VISIBLE);
1210   RECORD(DECL_NAMESPACE);
1211   RECORD(DECL_NAMESPACE_ALIAS);
1212   RECORD(DECL_USING);
1213   RECORD(DECL_USING_SHADOW);
1214   RECORD(DECL_USING_DIRECTIVE);
1215   RECORD(DECL_UNRESOLVED_USING_VALUE);
1216   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1217   RECORD(DECL_LINKAGE_SPEC);
1218   RECORD(DECL_CXX_RECORD);
1219   RECORD(DECL_CXX_METHOD);
1220   RECORD(DECL_CXX_CONSTRUCTOR);
1221   RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
1222   RECORD(DECL_CXX_DESTRUCTOR);
1223   RECORD(DECL_CXX_CONVERSION);
1224   RECORD(DECL_ACCESS_SPEC);
1225   RECORD(DECL_FRIEND);
1226   RECORD(DECL_FRIEND_TEMPLATE);
1227   RECORD(DECL_CLASS_TEMPLATE);
1228   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1229   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
1230   RECORD(DECL_VAR_TEMPLATE);
1231   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1232   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
1233   RECORD(DECL_FUNCTION_TEMPLATE);
1234   RECORD(DECL_TEMPLATE_TYPE_PARM);
1235   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1236   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1237   RECORD(DECL_TYPE_ALIAS_TEMPLATE);
1238   RECORD(DECL_STATIC_ASSERT);
1239   RECORD(DECL_CXX_BASE_SPECIFIERS);
1240   RECORD(DECL_CXX_CTOR_INITIALIZERS);
1241   RECORD(DECL_INDIRECTFIELD);
1242   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1243   RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1244   RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1245   RECORD(DECL_IMPORT);
1246   RECORD(DECL_OMP_THREADPRIVATE);
1247   RECORD(DECL_EMPTY);
1248   RECORD(DECL_OBJC_TYPE_PARAM);
1249   RECORD(DECL_OMP_CAPTUREDEXPR);
1250   RECORD(DECL_PRAGMA_COMMENT);
1251   RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1252   RECORD(DECL_OMP_DECLARE_REDUCTION);
1253 
1254   // Statements and Exprs can occur in the Decls and Types block.
1255   AddStmtsExprs(Stream, Record);
1256 
1257   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1258   RECORD(PPD_MACRO_EXPANSION);
1259   RECORD(PPD_MACRO_DEFINITION);
1260   RECORD(PPD_INCLUSION_DIRECTIVE);
1261 
1262   // Decls and Types block.
1263   BLOCK(EXTENSION_BLOCK);
1264   RECORD(EXTENSION_METADATA);
1265 
1266   BLOCK(UNHASHED_CONTROL_BLOCK);
1267   RECORD(SIGNATURE);
1268   RECORD(DIAGNOSTIC_OPTIONS);
1269   RECORD(DIAG_PRAGMA_MAPPINGS);
1270 
1271 #undef RECORD
1272 #undef BLOCK
1273   Stream.ExitBlock();
1274 }
1275 
1276 /// \brief Prepares a path for being written to an AST file by converting it
1277 /// to an absolute path and removing nested './'s.
1278 ///
1279 /// \return \c true if the path was changed.
1280 static bool cleanPathForOutput(FileManager &FileMgr,
1281                                SmallVectorImpl<char> &Path) {
1282   bool Changed = FileMgr.makeAbsolutePath(Path);
1283   return Changed | llvm::sys::path::remove_dots(Path);
1284 }
1285 
1286 /// \brief Adjusts the given filename to only write out the portion of the
1287 /// filename that is not part of the system root directory.
1288 ///
1289 /// \param Filename the file name to adjust.
1290 ///
1291 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1292 /// the returned filename will be adjusted by this root directory.
1293 ///
1294 /// \returns either the original filename (if it needs no adjustment) or the
1295 /// adjusted filename (which points into the @p Filename parameter).
1296 static const char *
1297 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1298   assert(Filename && "No file name to adjust?");
1299 
1300   if (BaseDir.empty())
1301     return Filename;
1302 
1303   // Verify that the filename and the system root have the same prefix.
1304   unsigned Pos = 0;
1305   for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1306     if (Filename[Pos] != BaseDir[Pos])
1307       return Filename; // Prefixes don't match.
1308 
1309   // We hit the end of the filename before we hit the end of the system root.
1310   if (!Filename[Pos])
1311     return Filename;
1312 
1313   // If there's not a path separator at the end of the base directory nor
1314   // immediately after it, then this isn't within the base directory.
1315   if (!llvm::sys::path::is_separator(Filename[Pos])) {
1316     if (!llvm::sys::path::is_separator(BaseDir.back()))
1317       return Filename;
1318   } else {
1319     // If the file name has a '/' at the current position, skip over the '/'.
1320     // We distinguish relative paths from absolute paths by the
1321     // absence of '/' at the beginning of relative paths.
1322     //
1323     // FIXME: This is wrong. We distinguish them by asking if the path is
1324     // absolute, which isn't the same thing. And there might be multiple '/'s
1325     // in a row. Use a better mechanism to indicate whether we have emitted an
1326     // absolute or relative path.
1327     ++Pos;
1328   }
1329 
1330   return Filename + Pos;
1331 }
1332 
1333 ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1334   // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1335   llvm::SHA1 Hasher;
1336   Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1337   auto Hash = Hasher.result();
1338 
1339   // Convert to an array [5*i32].
1340   ASTFileSignature Signature;
1341   auto LShift = [&](unsigned char Val, unsigned Shift) {
1342     return (uint32_t)Val << Shift;
1343   };
1344   for (int I = 0; I != 5; ++I)
1345     Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1346                    LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1347 
1348   return Signature;
1349 }
1350 
1351 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1352                                                       ASTContext &Context) {
1353   // Flush first to prepare the PCM hash (signature).
1354   Stream.FlushToWord();
1355   auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1356 
1357   // Enter the block and prepare to write records.
1358   RecordData Record;
1359   Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1360 
1361   // For implicit modules, write the hash of the PCM as its signature.
1362   ASTFileSignature Signature;
1363   if (WritingModule &&
1364       PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1365     Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1366     Record.append(Signature.begin(), Signature.end());
1367     Stream.EmitRecord(SIGNATURE, Record);
1368     Record.clear();
1369   }
1370 
1371   // Diagnostic options.
1372   const auto &Diags = Context.getDiagnostics();
1373   const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1374 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1375 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1376   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1377 #include "clang/Basic/DiagnosticOptions.def"
1378   Record.push_back(DiagOpts.Warnings.size());
1379   for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1380     AddString(DiagOpts.Warnings[I], Record);
1381   Record.push_back(DiagOpts.Remarks.size());
1382   for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1383     AddString(DiagOpts.Remarks[I], Record);
1384   // Note: we don't serialize the log or serialization file names, because they
1385   // are generally transient files and will almost always be overridden.
1386   Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1387 
1388   // Write out the diagnostic/pragma mappings.
1389   WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1390 
1391   // Leave the options block.
1392   Stream.ExitBlock();
1393   return Signature;
1394 }
1395 
1396 /// \brief Write the control block.
1397 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1398                                   StringRef isysroot,
1399                                   const std::string &OutputFile) {
1400   using namespace llvm;
1401   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1402   RecordData Record;
1403 
1404   // Metadata
1405   auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1406   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1407   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1408   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1409   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1410   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1411   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1412   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1413   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1414   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1415   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1416   assert((!WritingModule || isysroot.empty()) &&
1417          "writing module as a relocatable PCH?");
1418   {
1419     RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1420                                        CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1421                                        !isysroot.empty(), IncludeTimestamps,
1422                                        ASTHasCompilerErrors};
1423     Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1424                               getClangFullRepositoryVersion());
1425   }
1426 
1427   if (WritingModule) {
1428     // Module name
1429     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1430     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1431     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1432     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1433     RecordData::value_type Record[] = {MODULE_NAME};
1434     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1435   }
1436 
1437   if (WritingModule && WritingModule->Directory) {
1438     SmallString<128> BaseDir(WritingModule->Directory->getName());
1439     cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1440 
1441     // If the home of the module is the current working directory, then we
1442     // want to pick up the cwd of the build process loading the module, not
1443     // our cwd, when we load this module.
1444     if (!PP.getHeaderSearchInfo()
1445              .getHeaderSearchOpts()
1446              .ModuleMapFileHomeIsCwd ||
1447         WritingModule->Directory->getName() != StringRef(".")) {
1448       // Module directory.
1449       auto Abbrev = std::make_shared<BitCodeAbbrev>();
1450       Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1451       Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1452       unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1453 
1454       RecordData::value_type Record[] = {MODULE_DIRECTORY};
1455       Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1456     }
1457 
1458     // Write out all other paths relative to the base directory if possible.
1459     BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1460   } else if (!isysroot.empty()) {
1461     // Write out paths relative to the sysroot if possible.
1462     BaseDirectory = isysroot;
1463   }
1464 
1465   // Module map file
1466   if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1467     Record.clear();
1468 
1469     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1470     AddPath(WritingModule->PresumedModuleMapFile.empty()
1471                 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1472                 : StringRef(WritingModule->PresumedModuleMapFile),
1473             Record);
1474 
1475     // Additional module map files.
1476     if (auto *AdditionalModMaps =
1477             Map.getAdditionalModuleMapFiles(WritingModule)) {
1478       Record.push_back(AdditionalModMaps->size());
1479       for (const FileEntry *F : *AdditionalModMaps)
1480         AddPath(F->getName(), Record);
1481     } else {
1482       Record.push_back(0);
1483     }
1484 
1485     Stream.EmitRecord(MODULE_MAP_FILE, Record);
1486   }
1487 
1488   // Imports
1489   if (Chain) {
1490     serialization::ModuleManager &Mgr = Chain->getModuleManager();
1491     Record.clear();
1492 
1493     for (ModuleFile &M : Mgr) {
1494       // Skip modules that weren't directly imported.
1495       if (!M.isDirectlyImported())
1496         continue;
1497 
1498       Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1499       AddSourceLocation(M.ImportLoc, Record);
1500 
1501       // If we have calculated signature, there is no need to store
1502       // the size or timestamp.
1503       Record.push_back(M.Signature ? 0 : M.File->getSize());
1504       Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1505 
1506       for (auto I : M.Signature)
1507         Record.push_back(I);
1508 
1509       AddString(M.ModuleName, Record);
1510       AddPath(M.FileName, Record);
1511     }
1512     Stream.EmitRecord(IMPORTS, Record);
1513   }
1514 
1515   // Write the options block.
1516   Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1517 
1518   // Language options.
1519   Record.clear();
1520   const LangOptions &LangOpts = Context.getLangOpts();
1521 #define LANGOPT(Name, Bits, Default, Description) \
1522   Record.push_back(LangOpts.Name);
1523 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1524   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1525 #include "clang/Basic/LangOptions.def"
1526 #define SANITIZER(NAME, ID)                                                    \
1527   Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1528 #include "clang/Basic/Sanitizers.def"
1529 
1530   Record.push_back(LangOpts.ModuleFeatures.size());
1531   for (StringRef Feature : LangOpts.ModuleFeatures)
1532     AddString(Feature, Record);
1533 
1534   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1535   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1536 
1537   AddString(LangOpts.CurrentModule, Record);
1538 
1539   // Comment options.
1540   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1541   for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1542     AddString(I, Record);
1543   }
1544   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1545 
1546   // OpenMP offloading options.
1547   Record.push_back(LangOpts.OMPTargetTriples.size());
1548   for (auto &T : LangOpts.OMPTargetTriples)
1549     AddString(T.getTriple(), Record);
1550 
1551   AddString(LangOpts.OMPHostIRFile, Record);
1552 
1553   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1554 
1555   // Target options.
1556   Record.clear();
1557   const TargetInfo &Target = Context.getTargetInfo();
1558   const TargetOptions &TargetOpts = Target.getTargetOpts();
1559   AddString(TargetOpts.Triple, Record);
1560   AddString(TargetOpts.CPU, Record);
1561   AddString(TargetOpts.ABI, Record);
1562   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1563   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1564     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1565   }
1566   Record.push_back(TargetOpts.Features.size());
1567   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1568     AddString(TargetOpts.Features[I], Record);
1569   }
1570   Stream.EmitRecord(TARGET_OPTIONS, Record);
1571 
1572   // File system options.
1573   Record.clear();
1574   const FileSystemOptions &FSOpts =
1575       Context.getSourceManager().getFileManager().getFileSystemOpts();
1576   AddString(FSOpts.WorkingDir, Record);
1577   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1578 
1579   // Header search options.
1580   Record.clear();
1581   const HeaderSearchOptions &HSOpts
1582     = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1583   AddString(HSOpts.Sysroot, Record);
1584 
1585   // Include entries.
1586   Record.push_back(HSOpts.UserEntries.size());
1587   for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1588     const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1589     AddString(Entry.Path, Record);
1590     Record.push_back(static_cast<unsigned>(Entry.Group));
1591     Record.push_back(Entry.IsFramework);
1592     Record.push_back(Entry.IgnoreSysRoot);
1593   }
1594 
1595   // System header prefixes.
1596   Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1597   for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1598     AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1599     Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1600   }
1601 
1602   AddString(HSOpts.ResourceDir, Record);
1603   AddString(HSOpts.ModuleCachePath, Record);
1604   AddString(HSOpts.ModuleUserBuildPath, Record);
1605   Record.push_back(HSOpts.DisableModuleHash);
1606   Record.push_back(HSOpts.ImplicitModuleMaps);
1607   Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1608   Record.push_back(HSOpts.UseBuiltinIncludes);
1609   Record.push_back(HSOpts.UseStandardSystemIncludes);
1610   Record.push_back(HSOpts.UseStandardCXXIncludes);
1611   Record.push_back(HSOpts.UseLibcxx);
1612   // Write out the specific module cache path that contains the module files.
1613   AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1614   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1615 
1616   // Preprocessor options.
1617   Record.clear();
1618   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1619 
1620   // Macro definitions.
1621   Record.push_back(PPOpts.Macros.size());
1622   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1623     AddString(PPOpts.Macros[I].first, Record);
1624     Record.push_back(PPOpts.Macros[I].second);
1625   }
1626 
1627   // Includes
1628   Record.push_back(PPOpts.Includes.size());
1629   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1630     AddString(PPOpts.Includes[I], Record);
1631 
1632   // Macro includes
1633   Record.push_back(PPOpts.MacroIncludes.size());
1634   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1635     AddString(PPOpts.MacroIncludes[I], Record);
1636 
1637   Record.push_back(PPOpts.UsePredefines);
1638   // Detailed record is important since it is used for the module cache hash.
1639   Record.push_back(PPOpts.DetailedRecord);
1640   AddString(PPOpts.ImplicitPCHInclude, Record);
1641   AddString(PPOpts.ImplicitPTHInclude, Record);
1642   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1643   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1644 
1645   // Leave the options block.
1646   Stream.ExitBlock();
1647 
1648   // Original file name and file ID
1649   SourceManager &SM = Context.getSourceManager();
1650   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1651     auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1652     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1653     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1654     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1655     unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1656 
1657     Record.clear();
1658     Record.push_back(ORIGINAL_FILE);
1659     Record.push_back(SM.getMainFileID().getOpaqueValue());
1660     EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1661   }
1662 
1663   Record.clear();
1664   Record.push_back(SM.getMainFileID().getOpaqueValue());
1665   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1666 
1667   // Original PCH directory
1668   if (!OutputFile.empty() && OutputFile != "-") {
1669     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1670     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1671     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1672     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1673 
1674     SmallString<128> OutputPath(OutputFile);
1675 
1676     SM.getFileManager().makeAbsolutePath(OutputPath);
1677     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1678 
1679     RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1680     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1681   }
1682 
1683   WriteInputFiles(Context.SourceMgr,
1684                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1685                   PP.getLangOpts().Modules);
1686   Stream.ExitBlock();
1687 }
1688 
1689 namespace  {
1690 
1691   /// \brief An input file.
1692   struct InputFileEntry {
1693     const FileEntry *File;
1694     bool IsSystemFile;
1695     bool IsTransient;
1696     bool BufferOverridden;
1697     bool IsTopLevelModuleMap;
1698   };
1699 
1700 } // end anonymous namespace
1701 
1702 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1703                                 HeaderSearchOptions &HSOpts,
1704                                 bool Modules) {
1705   using namespace llvm;
1706   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1707 
1708   // Create input-file abbreviation.
1709   auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1710   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1711   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1712   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1713   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1714   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1715   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1716   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1717   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1718   unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1719 
1720   // Get all ContentCache objects for files, sorted by whether the file is a
1721   // system one or not. System files go at the back, users files at the front.
1722   std::deque<InputFileEntry> SortedFiles;
1723   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1724     // Get this source location entry.
1725     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1726     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1727 
1728     // We only care about file entries that were not overridden.
1729     if (!SLoc->isFile())
1730       continue;
1731     const SrcMgr::FileInfo &File = SLoc->getFile();
1732     const SrcMgr::ContentCache *Cache = File.getContentCache();
1733     if (!Cache->OrigEntry)
1734       continue;
1735 
1736     InputFileEntry Entry;
1737     Entry.File = Cache->OrigEntry;
1738     Entry.IsSystemFile = Cache->IsSystemFile;
1739     Entry.IsTransient = Cache->IsTransient;
1740     Entry.BufferOverridden = Cache->BufferOverridden;
1741     Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1742                                 File.getIncludeLoc().isInvalid();
1743     if (Cache->IsSystemFile)
1744       SortedFiles.push_back(Entry);
1745     else
1746       SortedFiles.push_front(Entry);
1747   }
1748 
1749   unsigned UserFilesNum = 0;
1750   // Write out all of the input files.
1751   std::vector<uint64_t> InputFileOffsets;
1752   for (const auto &Entry : SortedFiles) {
1753     uint32_t &InputFileID = InputFileIDs[Entry.File];
1754     if (InputFileID != 0)
1755       continue; // already recorded this file.
1756 
1757     // Record this entry's offset.
1758     InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1759 
1760     InputFileID = InputFileOffsets.size();
1761 
1762     if (!Entry.IsSystemFile)
1763       ++UserFilesNum;
1764 
1765     // Emit size/modification time for this file.
1766     // And whether this file was overridden.
1767     RecordData::value_type Record[] = {
1768         INPUT_FILE,
1769         InputFileOffsets.size(),
1770         (uint64_t)Entry.File->getSize(),
1771         (uint64_t)getTimestampForOutput(Entry.File),
1772         Entry.BufferOverridden,
1773         Entry.IsTransient,
1774         Entry.IsTopLevelModuleMap};
1775 
1776     EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1777   }
1778 
1779   Stream.ExitBlock();
1780 
1781   // Create input file offsets abbreviation.
1782   auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1783   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1784   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1785   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1786                                                                 //   input files
1787   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1788   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1789 
1790   // Write input file offsets.
1791   RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1792                                      InputFileOffsets.size(), UserFilesNum};
1793   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1794 }
1795 
1796 //===----------------------------------------------------------------------===//
1797 // Source Manager Serialization
1798 //===----------------------------------------------------------------------===//
1799 
1800 /// \brief Create an abbreviation for the SLocEntry that refers to a
1801 /// file.
1802 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1803   using namespace llvm;
1804 
1805   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1806   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1807   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1808   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1809   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1810   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1811   // FileEntry fields.
1812   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1813   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1814   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1815   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1816   return Stream.EmitAbbrev(std::move(Abbrev));
1817 }
1818 
1819 /// \brief Create an abbreviation for the SLocEntry that refers to a
1820 /// buffer.
1821 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1822   using namespace llvm;
1823 
1824   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1825   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1826   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1827   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1828   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1829   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1830   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1831   return Stream.EmitAbbrev(std::move(Abbrev));
1832 }
1833 
1834 /// \brief Create an abbreviation for the SLocEntry that refers to a
1835 /// buffer's blob.
1836 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1837                                            bool Compressed) {
1838   using namespace llvm;
1839 
1840   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1841   Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1842                                          : SM_SLOC_BUFFER_BLOB));
1843   if (Compressed)
1844     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1845   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1846   return Stream.EmitAbbrev(std::move(Abbrev));
1847 }
1848 
1849 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1850 /// expansion.
1851 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1852   using namespace llvm;
1853 
1854   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1855   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1856   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1857   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1858   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1859   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1860   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1861   return Stream.EmitAbbrev(std::move(Abbrev));
1862 }
1863 
1864 namespace {
1865 
1866   // Trait used for the on-disk hash table of header search information.
1867   class HeaderFileInfoTrait {
1868     ASTWriter &Writer;
1869 
1870     // Keep track of the framework names we've used during serialization.
1871     SmallVector<char, 128> FrameworkStringData;
1872     llvm::StringMap<unsigned> FrameworkNameOffset;
1873 
1874   public:
1875     HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1876 
1877     struct key_type {
1878       StringRef Filename;
1879       off_t Size;
1880       time_t ModTime;
1881     };
1882     typedef const key_type &key_type_ref;
1883 
1884     using UnresolvedModule =
1885         llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1886 
1887     struct data_type {
1888       const HeaderFileInfo &HFI;
1889       ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1890       UnresolvedModule Unresolved;
1891     };
1892     typedef const data_type &data_type_ref;
1893 
1894     typedef unsigned hash_value_type;
1895     typedef unsigned offset_type;
1896 
1897     hash_value_type ComputeHash(key_type_ref key) {
1898       // The hash is based only on size/time of the file, so that the reader can
1899       // match even when symlinking or excess path elements ("foo/../", "../")
1900       // change the form of the name. However, complete path is still the key.
1901       return llvm::hash_combine(key.Size, key.ModTime);
1902     }
1903 
1904     std::pair<unsigned,unsigned>
1905     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1906       using namespace llvm::support;
1907       endian::Writer<little> LE(Out);
1908       unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1909       LE.write<uint16_t>(KeyLen);
1910       unsigned DataLen = 1 + 2 + 4 + 4;
1911       for (auto ModInfo : Data.KnownHeaders)
1912         if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1913           DataLen += 4;
1914       if (Data.Unresolved.getPointer())
1915         DataLen += 4;
1916       LE.write<uint8_t>(DataLen);
1917       return std::make_pair(KeyLen, DataLen);
1918     }
1919 
1920     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1921       using namespace llvm::support;
1922       endian::Writer<little> LE(Out);
1923       LE.write<uint64_t>(key.Size);
1924       KeyLen -= 8;
1925       LE.write<uint64_t>(key.ModTime);
1926       KeyLen -= 8;
1927       Out.write(key.Filename.data(), KeyLen);
1928     }
1929 
1930     void EmitData(raw_ostream &Out, key_type_ref key,
1931                   data_type_ref Data, unsigned DataLen) {
1932       using namespace llvm::support;
1933       endian::Writer<little> LE(Out);
1934       uint64_t Start = Out.tell(); (void)Start;
1935 
1936       unsigned char Flags = (Data.HFI.isImport << 5)
1937                           | (Data.HFI.isPragmaOnce << 4)
1938                           | (Data.HFI.DirInfo << 1)
1939                           | Data.HFI.IndexHeaderMapHeader;
1940       LE.write<uint8_t>(Flags);
1941       LE.write<uint16_t>(Data.HFI.NumIncludes);
1942 
1943       if (!Data.HFI.ControllingMacro)
1944         LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1945       else
1946         LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1947 
1948       unsigned Offset = 0;
1949       if (!Data.HFI.Framework.empty()) {
1950         // If this header refers into a framework, save the framework name.
1951         llvm::StringMap<unsigned>::iterator Pos
1952           = FrameworkNameOffset.find(Data.HFI.Framework);
1953         if (Pos == FrameworkNameOffset.end()) {
1954           Offset = FrameworkStringData.size() + 1;
1955           FrameworkStringData.append(Data.HFI.Framework.begin(),
1956                                      Data.HFI.Framework.end());
1957           FrameworkStringData.push_back(0);
1958 
1959           FrameworkNameOffset[Data.HFI.Framework] = Offset;
1960         } else
1961           Offset = Pos->second;
1962       }
1963       LE.write<uint32_t>(Offset);
1964 
1965       auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1966         if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1967           uint32_t Value = (ModID << 2) | (unsigned)Role;
1968           assert((Value >> 2) == ModID && "overflow in header module info");
1969           LE.write<uint32_t>(Value);
1970         }
1971       };
1972 
1973       // FIXME: If the header is excluded, we should write out some
1974       // record of that fact.
1975       for (auto ModInfo : Data.KnownHeaders)
1976         EmitModule(ModInfo.getModule(), ModInfo.getRole());
1977       if (Data.Unresolved.getPointer())
1978         EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1979 
1980       assert(Out.tell() - Start == DataLen && "Wrong data length");
1981     }
1982 
1983     const char *strings_begin() const { return FrameworkStringData.begin(); }
1984     const char *strings_end() const { return FrameworkStringData.end(); }
1985   };
1986 
1987 } // end anonymous namespace
1988 
1989 /// \brief Write the header search block for the list of files that
1990 ///
1991 /// \param HS The header search structure to save.
1992 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1993   HeaderFileInfoTrait GeneratorTrait(*this);
1994   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1995   SmallVector<const char *, 4> SavedStrings;
1996   unsigned NumHeaderSearchEntries = 0;
1997 
1998   // Find all unresolved headers for the current module. We generally will
1999   // have resolved them before we get here, but not necessarily: we might be
2000   // compiling a preprocessed module, where there is no requirement for the
2001   // original files to exist any more.
2002   const HeaderFileInfo Empty; // So we can take a reference.
2003   if (WritingModule) {
2004     llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2005     while (!Worklist.empty()) {
2006       Module *M = Worklist.pop_back_val();
2007       if (!M->isAvailable())
2008         continue;
2009 
2010       // Map to disk files where possible, to pick up any missing stat
2011       // information. This also means we don't need to check the unresolved
2012       // headers list when emitting resolved headers in the first loop below.
2013       // FIXME: It'd be preferable to avoid doing this if we were given
2014       // sufficient stat information in the module map.
2015       HS.getModuleMap().resolveHeaderDirectives(M);
2016 
2017       // If the file didn't exist, we can still create a module if we were given
2018       // enough information in the module map.
2019       for (auto U : M->MissingHeaders) {
2020         // Check that we were given enough information to build a module
2021         // without this file existing on disk.
2022         if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2023           PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2024             << WritingModule->getFullModuleName() << U.Size.hasValue()
2025             << U.FileName;
2026           continue;
2027         }
2028 
2029         // Form the effective relative pathname for the file.
2030         SmallString<128> Filename(M->Directory->getName());
2031         llvm::sys::path::append(Filename, U.FileName);
2032         PreparePathForOutput(Filename);
2033 
2034         StringRef FilenameDup = strdup(Filename.c_str());
2035         SavedStrings.push_back(FilenameDup.data());
2036 
2037         HeaderFileInfoTrait::key_type Key = {
2038           FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2039         };
2040         HeaderFileInfoTrait::data_type Data = {
2041           Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2042         };
2043         // FIXME: Deal with cases where there are multiple unresolved header
2044         // directives in different submodules for the same header.
2045         Generator.insert(Key, Data, GeneratorTrait);
2046         ++NumHeaderSearchEntries;
2047       }
2048 
2049       Worklist.append(M->submodule_begin(), M->submodule_end());
2050     }
2051   }
2052 
2053   SmallVector<const FileEntry *, 16> FilesByUID;
2054   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2055 
2056   if (FilesByUID.size() > HS.header_file_size())
2057     FilesByUID.resize(HS.header_file_size());
2058 
2059   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2060     const FileEntry *File = FilesByUID[UID];
2061     if (!File)
2062       continue;
2063 
2064     // Get the file info. This will load info from the external source if
2065     // necessary. Skip emitting this file if we have no information on it
2066     // as a header file (in which case HFI will be null) or if it hasn't
2067     // changed since it was loaded. Also skip it if it's for a modular header
2068     // from a different module; in that case, we rely on the module(s)
2069     // containing the header to provide this information.
2070     const HeaderFileInfo *HFI =
2071         HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2072     if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2073       continue;
2074 
2075     // Massage the file path into an appropriate form.
2076     StringRef Filename = File->getName();
2077     SmallString<128> FilenameTmp(Filename);
2078     if (PreparePathForOutput(FilenameTmp)) {
2079       // If we performed any translation on the file name at all, we need to
2080       // save this string, since the generator will refer to it later.
2081       Filename = StringRef(strdup(FilenameTmp.c_str()));
2082       SavedStrings.push_back(Filename.data());
2083     }
2084 
2085     HeaderFileInfoTrait::key_type Key = {
2086       Filename, File->getSize(), getTimestampForOutput(File)
2087     };
2088     HeaderFileInfoTrait::data_type Data = {
2089       *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2090     };
2091     Generator.insert(Key, Data, GeneratorTrait);
2092     ++NumHeaderSearchEntries;
2093   }
2094 
2095   // Create the on-disk hash table in a buffer.
2096   SmallString<4096> TableData;
2097   uint32_t BucketOffset;
2098   {
2099     using namespace llvm::support;
2100     llvm::raw_svector_ostream Out(TableData);
2101     // Make sure that no bucket is at offset 0
2102     endian::Writer<little>(Out).write<uint32_t>(0);
2103     BucketOffset = Generator.Emit(Out, GeneratorTrait);
2104   }
2105 
2106   // Create a blob abbreviation
2107   using namespace llvm;
2108 
2109   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2110   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2111   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2112   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2113   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2114   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2115   unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2116 
2117   // Write the header search table
2118   RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2119                                      NumHeaderSearchEntries, TableData.size()};
2120   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2121   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2122 
2123   // Free all of the strings we had to duplicate.
2124   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2125     free(const_cast<char *>(SavedStrings[I]));
2126 }
2127 
2128 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2129                      unsigned SLocBufferBlobCompressedAbbrv,
2130                      unsigned SLocBufferBlobAbbrv) {
2131   typedef ASTWriter::RecordData::value_type RecordDataType;
2132 
2133   // Compress the buffer if possible. We expect that almost all PCM
2134   // consumers will not want its contents.
2135   SmallString<0> CompressedBuffer;
2136   if (llvm::zlib::isAvailable()) {
2137     llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2138     if (!E) {
2139       RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2140                                  Blob.size() - 1};
2141       Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2142                                 CompressedBuffer);
2143       return;
2144     }
2145     llvm::consumeError(std::move(E));
2146   }
2147 
2148   RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2149   Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2150 }
2151 
2152 /// \brief Writes the block containing the serialized form of the
2153 /// source manager.
2154 ///
2155 /// TODO: We should probably use an on-disk hash table (stored in a
2156 /// blob), indexed based on the file name, so that we only create
2157 /// entries for files that we actually need. In the common case (no
2158 /// errors), we probably won't have to create file entries for any of
2159 /// the files in the AST.
2160 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2161                                         const Preprocessor &PP) {
2162   RecordData Record;
2163 
2164   // Enter the source manager block.
2165   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2166 
2167   // Abbreviations for the various kinds of source-location entries.
2168   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2169   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2170   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2171   unsigned SLocBufferBlobCompressedAbbrv =
2172       CreateSLocBufferBlobAbbrev(Stream, true);
2173   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2174 
2175   // Write out the source location entry table. We skip the first
2176   // entry, which is always the same dummy entry.
2177   std::vector<uint32_t> SLocEntryOffsets;
2178   RecordData PreloadSLocs;
2179   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2180   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2181        I != N; ++I) {
2182     // Get this source location entry.
2183     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2184     FileID FID = FileID::get(I);
2185     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2186 
2187     // Record the offset of this source-location entry.
2188     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2189 
2190     // Figure out which record code to use.
2191     unsigned Code;
2192     if (SLoc->isFile()) {
2193       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2194       if (Cache->OrigEntry) {
2195         Code = SM_SLOC_FILE_ENTRY;
2196       } else
2197         Code = SM_SLOC_BUFFER_ENTRY;
2198     } else
2199       Code = SM_SLOC_EXPANSION_ENTRY;
2200     Record.clear();
2201     Record.push_back(Code);
2202 
2203     // Starting offset of this entry within this module, so skip the dummy.
2204     Record.push_back(SLoc->getOffset() - 2);
2205     if (SLoc->isFile()) {
2206       const SrcMgr::FileInfo &File = SLoc->getFile();
2207       AddSourceLocation(File.getIncludeLoc(), Record);
2208       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2209       Record.push_back(File.hasLineDirectives());
2210 
2211       const SrcMgr::ContentCache *Content = File.getContentCache();
2212       bool EmitBlob = false;
2213       if (Content->OrigEntry) {
2214         assert(Content->OrigEntry == Content->ContentsEntry &&
2215                "Writing to AST an overridden file is not supported");
2216 
2217         // The source location entry is a file. Emit input file ID.
2218         assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2219         Record.push_back(InputFileIDs[Content->OrigEntry]);
2220 
2221         Record.push_back(File.NumCreatedFIDs);
2222 
2223         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2224         if (FDI != FileDeclIDs.end()) {
2225           Record.push_back(FDI->second->FirstDeclIndex);
2226           Record.push_back(FDI->second->DeclIDs.size());
2227         } else {
2228           Record.push_back(0);
2229           Record.push_back(0);
2230         }
2231 
2232         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2233 
2234         if (Content->BufferOverridden || Content->IsTransient)
2235           EmitBlob = true;
2236       } else {
2237         // The source location entry is a buffer. The blob associated
2238         // with this entry contains the contents of the buffer.
2239 
2240         // We add one to the size so that we capture the trailing NULL
2241         // that is required by llvm::MemoryBuffer::getMemBuffer (on
2242         // the reader side).
2243         const llvm::MemoryBuffer *Buffer
2244           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2245         StringRef Name = Buffer->getBufferIdentifier();
2246         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2247                                   StringRef(Name.data(), Name.size() + 1));
2248         EmitBlob = true;
2249 
2250         if (Name == "<built-in>")
2251           PreloadSLocs.push_back(SLocEntryOffsets.size());
2252       }
2253 
2254       if (EmitBlob) {
2255         // Include the implicit terminating null character in the on-disk buffer
2256         // if we're writing it uncompressed.
2257         const llvm::MemoryBuffer *Buffer =
2258             Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2259         StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2260         emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2261                  SLocBufferBlobAbbrv);
2262       }
2263     } else {
2264       // The source location entry is a macro expansion.
2265       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2266       AddSourceLocation(Expansion.getSpellingLoc(), Record);
2267       AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2268       AddSourceLocation(Expansion.isMacroArgExpansion()
2269                             ? SourceLocation()
2270                             : Expansion.getExpansionLocEnd(),
2271                         Record);
2272 
2273       // Compute the token length for this macro expansion.
2274       unsigned NextOffset = SourceMgr.getNextLocalOffset();
2275       if (I + 1 != N)
2276         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2277       Record.push_back(NextOffset - SLoc->getOffset() - 1);
2278       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2279     }
2280   }
2281 
2282   Stream.ExitBlock();
2283 
2284   if (SLocEntryOffsets.empty())
2285     return;
2286 
2287   // Write the source-location offsets table into the AST block. This
2288   // table is used for lazily loading source-location information.
2289   using namespace llvm;
2290 
2291   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2292   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2293   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2294   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2295   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2296   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2297   {
2298     RecordData::value_type Record[] = {
2299         SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2300         SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2301     Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2302                               bytes(SLocEntryOffsets));
2303   }
2304   // Write the source location entry preloads array, telling the AST
2305   // reader which source locations entries it should load eagerly.
2306   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2307 
2308   // Write the line table. It depends on remapping working, so it must come
2309   // after the source location offsets.
2310   if (SourceMgr.hasLineTable()) {
2311     LineTableInfo &LineTable = SourceMgr.getLineTable();
2312 
2313     Record.clear();
2314 
2315     // Emit the needed file names.
2316     llvm::DenseMap<int, int> FilenameMap;
2317     for (const auto &L : LineTable) {
2318       if (L.first.ID < 0)
2319         continue;
2320       for (auto &LE : L.second) {
2321         if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2322                                               FilenameMap.size())).second)
2323           AddPath(LineTable.getFilename(LE.FilenameID), Record);
2324       }
2325     }
2326     Record.push_back(0);
2327 
2328     // Emit the line entries
2329     for (const auto &L : LineTable) {
2330       // Only emit entries for local files.
2331       if (L.first.ID < 0)
2332         continue;
2333 
2334       // Emit the file ID
2335       Record.push_back(L.first.ID);
2336 
2337       // Emit the line entries
2338       Record.push_back(L.second.size());
2339       for (const auto &LE : L.second) {
2340         Record.push_back(LE.FileOffset);
2341         Record.push_back(LE.LineNo);
2342         Record.push_back(FilenameMap[LE.FilenameID]);
2343         Record.push_back((unsigned)LE.FileKind);
2344         Record.push_back(LE.IncludeOffset);
2345       }
2346     }
2347 
2348     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2349   }
2350 }
2351 
2352 //===----------------------------------------------------------------------===//
2353 // Preprocessor Serialization
2354 //===----------------------------------------------------------------------===//
2355 
2356 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2357                               const Preprocessor &PP) {
2358   if (MacroInfo *MI = MD->getMacroInfo())
2359     if (MI->isBuiltinMacro())
2360       return true;
2361 
2362   if (IsModule) {
2363     SourceLocation Loc = MD->getLocation();
2364     if (Loc.isInvalid())
2365       return true;
2366     if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2367       return true;
2368   }
2369 
2370   return false;
2371 }
2372 
2373 /// \brief Writes the block containing the serialized form of the
2374 /// preprocessor.
2375 ///
2376 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2377   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2378   if (PPRec)
2379     WritePreprocessorDetail(*PPRec);
2380 
2381   RecordData Record;
2382   RecordData ModuleMacroRecord;
2383 
2384   // If the preprocessor __COUNTER__ value has been bumped, remember it.
2385   if (PP.getCounterValue() != 0) {
2386     RecordData::value_type Record[] = {PP.getCounterValue()};
2387     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2388   }
2389 
2390   if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2391     assert(!IsModule);
2392     for (const auto &Cond : PP.getPreambleConditionalStack()) {
2393       AddSourceLocation(Cond.IfLoc, Record);
2394       Record.push_back(Cond.WasSkipping);
2395       Record.push_back(Cond.FoundNonSkip);
2396       Record.push_back(Cond.FoundElse);
2397     }
2398     Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2399     Record.clear();
2400   }
2401 
2402   // Enter the preprocessor block.
2403   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2404 
2405   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2406   // FIXME: Include a location for the use, and say which one was used.
2407   if (PP.SawDateOrTime())
2408     PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2409 
2410   // Loop over all the macro directives that are live at the end of the file,
2411   // emitting each to the PP section.
2412 
2413   // Construct the list of identifiers with macro directives that need to be
2414   // serialized.
2415   SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2416   for (auto &Id : PP.getIdentifierTable())
2417     if (Id.second->hadMacroDefinition() &&
2418         (!Id.second->isFromAST() ||
2419          Id.second->hasChangedSinceDeserialization()))
2420       MacroIdentifiers.push_back(Id.second);
2421   // Sort the set of macro definitions that need to be serialized by the
2422   // name of the macro, to provide a stable ordering.
2423   std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2424             llvm::less_ptr<IdentifierInfo>());
2425 
2426   // Emit the macro directives as a list and associate the offset with the
2427   // identifier they belong to.
2428   for (const IdentifierInfo *Name : MacroIdentifiers) {
2429     MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2430     auto StartOffset = Stream.GetCurrentBitNo();
2431 
2432     // Emit the macro directives in reverse source order.
2433     for (; MD; MD = MD->getPrevious()) {
2434       // Once we hit an ignored macro, we're done: the rest of the chain
2435       // will all be ignored macros.
2436       if (shouldIgnoreMacro(MD, IsModule, PP))
2437         break;
2438 
2439       AddSourceLocation(MD->getLocation(), Record);
2440       Record.push_back(MD->getKind());
2441       if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2442         Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2443       } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2444         Record.push_back(VisMD->isPublic());
2445       }
2446     }
2447 
2448     // Write out any exported module macros.
2449     bool EmittedModuleMacros = false;
2450     // We write out exported module macros for PCH as well.
2451     auto Leafs = PP.getLeafModuleMacros(Name);
2452     SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2453     llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2454     while (!Worklist.empty()) {
2455       auto *Macro = Worklist.pop_back_val();
2456 
2457       // Emit a record indicating this submodule exports this macro.
2458       ModuleMacroRecord.push_back(
2459           getSubmoduleID(Macro->getOwningModule()));
2460       ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2461       for (auto *M : Macro->overrides())
2462         ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2463 
2464       Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2465       ModuleMacroRecord.clear();
2466 
2467       // Enqueue overridden macros once we've visited all their ancestors.
2468       for (auto *M : Macro->overrides())
2469         if (++Visits[M] == M->getNumOverridingMacros())
2470           Worklist.push_back(M);
2471 
2472       EmittedModuleMacros = true;
2473     }
2474 
2475     if (Record.empty() && !EmittedModuleMacros)
2476       continue;
2477 
2478     IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2479     Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2480     Record.clear();
2481   }
2482 
2483   /// \brief Offsets of each of the macros into the bitstream, indexed by
2484   /// the local macro ID
2485   ///
2486   /// For each identifier that is associated with a macro, this map
2487   /// provides the offset into the bitstream where that macro is
2488   /// defined.
2489   std::vector<uint32_t> MacroOffsets;
2490 
2491   for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2492     const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2493     MacroInfo *MI = MacroInfosToEmit[I].MI;
2494     MacroID ID = MacroInfosToEmit[I].ID;
2495 
2496     if (ID < FirstMacroID) {
2497       assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2498       continue;
2499     }
2500 
2501     // Record the local offset of this macro.
2502     unsigned Index = ID - FirstMacroID;
2503     if (Index == MacroOffsets.size())
2504       MacroOffsets.push_back(Stream.GetCurrentBitNo());
2505     else {
2506       if (Index > MacroOffsets.size())
2507         MacroOffsets.resize(Index + 1);
2508 
2509       MacroOffsets[Index] = Stream.GetCurrentBitNo();
2510     }
2511 
2512     AddIdentifierRef(Name, Record);
2513     AddSourceLocation(MI->getDefinitionLoc(), Record);
2514     AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2515     Record.push_back(MI->isUsed());
2516     Record.push_back(MI->isUsedForHeaderGuard());
2517     unsigned Code;
2518     if (MI->isObjectLike()) {
2519       Code = PP_MACRO_OBJECT_LIKE;
2520     } else {
2521       Code = PP_MACRO_FUNCTION_LIKE;
2522 
2523       Record.push_back(MI->isC99Varargs());
2524       Record.push_back(MI->isGNUVarargs());
2525       Record.push_back(MI->hasCommaPasting());
2526       Record.push_back(MI->getNumParams());
2527       for (const IdentifierInfo *Param : MI->params())
2528         AddIdentifierRef(Param, Record);
2529     }
2530 
2531     // If we have a detailed preprocessing record, record the macro definition
2532     // ID that corresponds to this macro.
2533     if (PPRec)
2534       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2535 
2536     Stream.EmitRecord(Code, Record);
2537     Record.clear();
2538 
2539     // Emit the tokens array.
2540     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2541       // Note that we know that the preprocessor does not have any annotation
2542       // tokens in it because they are created by the parser, and thus can't
2543       // be in a macro definition.
2544       const Token &Tok = MI->getReplacementToken(TokNo);
2545       AddToken(Tok, Record);
2546       Stream.EmitRecord(PP_TOKEN, Record);
2547       Record.clear();
2548     }
2549     ++NumMacros;
2550   }
2551 
2552   Stream.ExitBlock();
2553 
2554   // Write the offsets table for macro IDs.
2555   using namespace llvm;
2556 
2557   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2558   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2559   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2560   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2561   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2562 
2563   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2564   {
2565     RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2566                                        FirstMacroID - NUM_PREDEF_MACRO_IDS};
2567     Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2568   }
2569 }
2570 
2571 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2572   if (PPRec.local_begin() == PPRec.local_end())
2573     return;
2574 
2575   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2576 
2577   // Enter the preprocessor block.
2578   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2579 
2580   // If the preprocessor has a preprocessing record, emit it.
2581   unsigned NumPreprocessingRecords = 0;
2582   using namespace llvm;
2583 
2584   // Set up the abbreviation for
2585   unsigned InclusionAbbrev = 0;
2586   {
2587     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2588     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2589     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2590     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2591     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2592     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2593     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2594     InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2595   }
2596 
2597   unsigned FirstPreprocessorEntityID
2598     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2599     + NUM_PREDEF_PP_ENTITY_IDS;
2600   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2601   RecordData Record;
2602   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2603                                   EEnd = PPRec.local_end();
2604        E != EEnd;
2605        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2606     Record.clear();
2607 
2608     PreprocessedEntityOffsets.push_back(
2609         PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2610 
2611     if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2612       // Record this macro definition's ID.
2613       MacroDefinitions[MD] = NextPreprocessorEntityID;
2614 
2615       AddIdentifierRef(MD->getName(), Record);
2616       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2617       continue;
2618     }
2619 
2620     if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2621       Record.push_back(ME->isBuiltinMacro());
2622       if (ME->isBuiltinMacro())
2623         AddIdentifierRef(ME->getName(), Record);
2624       else
2625         Record.push_back(MacroDefinitions[ME->getDefinition()]);
2626       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2627       continue;
2628     }
2629 
2630     if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2631       Record.push_back(PPD_INCLUSION_DIRECTIVE);
2632       Record.push_back(ID->getFileName().size());
2633       Record.push_back(ID->wasInQuotes());
2634       Record.push_back(static_cast<unsigned>(ID->getKind()));
2635       Record.push_back(ID->importedModule());
2636       SmallString<64> Buffer;
2637       Buffer += ID->getFileName();
2638       // Check that the FileEntry is not null because it was not resolved and
2639       // we create a PCH even with compiler errors.
2640       if (ID->getFile())
2641         Buffer += ID->getFile()->getName();
2642       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2643       continue;
2644     }
2645 
2646     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2647   }
2648   Stream.ExitBlock();
2649 
2650   // Write the offsets table for the preprocessing record.
2651   if (NumPreprocessingRecords > 0) {
2652     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2653 
2654     // Write the offsets table for identifier IDs.
2655     using namespace llvm;
2656 
2657     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2658     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2659     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2660     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2661     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2662 
2663     RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2664                                        FirstPreprocessorEntityID -
2665                                            NUM_PREDEF_PP_ENTITY_IDS};
2666     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2667                               bytes(PreprocessedEntityOffsets));
2668   }
2669 }
2670 
2671 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
2672   if (!Mod)
2673     return 0;
2674 
2675   llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2676   if (Known != SubmoduleIDs.end())
2677     return Known->second;
2678 
2679   auto *Top = Mod->getTopLevelModule();
2680   if (Top != WritingModule &&
2681       (getLangOpts().CompilingPCH ||
2682        !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2683     return 0;
2684 
2685   return SubmoduleIDs[Mod] = NextSubmoduleID++;
2686 }
2687 
2688 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2689   // FIXME: This can easily happen, if we have a reference to a submodule that
2690   // did not result in us loading a module file for that submodule. For
2691   // instance, a cross-top-level-module 'conflict' declaration will hit this.
2692   unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2693   assert((ID || !Mod) &&
2694          "asked for module ID for non-local, non-imported module");
2695   return ID;
2696 }
2697 
2698 /// \brief Compute the number of modules within the given tree (including the
2699 /// given module).
2700 static unsigned getNumberOfModules(Module *Mod) {
2701   unsigned ChildModules = 0;
2702   for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2703        Sub != SubEnd; ++Sub)
2704     ChildModules += getNumberOfModules(*Sub);
2705 
2706   return ChildModules + 1;
2707 }
2708 
2709 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2710   // Enter the submodule description block.
2711   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2712 
2713   // Write the abbreviations needed for the submodules block.
2714   using namespace llvm;
2715 
2716   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2717   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2718   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2719   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2720   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2721   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2722   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2723   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2724   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2725   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2726   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2727   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2728   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2729   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2730   unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2731 
2732   Abbrev = std::make_shared<BitCodeAbbrev>();
2733   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2734   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2735   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2736 
2737   Abbrev = std::make_shared<BitCodeAbbrev>();
2738   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2739   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2740   unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2741 
2742   Abbrev = std::make_shared<BitCodeAbbrev>();
2743   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2744   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2745   unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2746 
2747   Abbrev = std::make_shared<BitCodeAbbrev>();
2748   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2749   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2750   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2751 
2752   Abbrev = std::make_shared<BitCodeAbbrev>();
2753   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2754   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2755   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2756   unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2757 
2758   Abbrev = std::make_shared<BitCodeAbbrev>();
2759   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2760   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2761   unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2762 
2763   Abbrev = std::make_shared<BitCodeAbbrev>();
2764   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2765   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2766   unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2767 
2768   Abbrev = std::make_shared<BitCodeAbbrev>();
2769   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2770   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2771   unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2772 
2773   Abbrev = std::make_shared<BitCodeAbbrev>();
2774   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2775   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2776   unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2777 
2778   Abbrev = std::make_shared<BitCodeAbbrev>();
2779   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2780   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2781   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2782   unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2783 
2784   Abbrev = std::make_shared<BitCodeAbbrev>();
2785   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2786   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2787   unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2788 
2789   Abbrev = std::make_shared<BitCodeAbbrev>();
2790   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2791   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2792   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2793   unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2794 
2795   Abbrev = std::make_shared<BitCodeAbbrev>();
2796   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2797   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2798   unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2799 
2800   // Write the submodule metadata block.
2801   RecordData::value_type Record[] = {
2802       getNumberOfModules(WritingModule),
2803       FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2804   Stream.EmitRecord(SUBMODULE_METADATA, Record);
2805 
2806   // Write all of the submodules.
2807   std::queue<Module *> Q;
2808   Q.push(WritingModule);
2809   while (!Q.empty()) {
2810     Module *Mod = Q.front();
2811     Q.pop();
2812     unsigned ID = getSubmoduleID(Mod);
2813 
2814     uint64_t ParentID = 0;
2815     if (Mod->Parent) {
2816       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2817       ParentID = SubmoduleIDs[Mod->Parent];
2818     }
2819 
2820     // Emit the definition of the block.
2821     {
2822       RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2823                                          ID,
2824                                          ParentID,
2825                                          (RecordData::value_type)Mod->Kind,
2826                                          Mod->IsFramework,
2827                                          Mod->IsExplicit,
2828                                          Mod->IsSystem,
2829                                          Mod->IsExternC,
2830                                          Mod->InferSubmodules,
2831                                          Mod->InferExplicitSubmodules,
2832                                          Mod->InferExportWildcard,
2833                                          Mod->ConfigMacrosExhaustive};
2834       Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2835     }
2836 
2837     // Emit the requirements.
2838     for (const auto &R : Mod->Requirements) {
2839       RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2840       Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2841     }
2842 
2843     // Emit the umbrella header, if there is one.
2844     if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2845       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2846       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2847                                 UmbrellaHeader.NameAsWritten);
2848     } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2849       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2850       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2851                                 UmbrellaDir.NameAsWritten);
2852     }
2853 
2854     // Emit the headers.
2855     struct {
2856       unsigned RecordKind;
2857       unsigned Abbrev;
2858       Module::HeaderKind HeaderKind;
2859     } HeaderLists[] = {
2860       {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2861       {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2862       {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2863       {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2864         Module::HK_PrivateTextual},
2865       {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2866     };
2867     for (auto &HL : HeaderLists) {
2868       RecordData::value_type Record[] = {HL.RecordKind};
2869       for (auto &H : Mod->Headers[HL.HeaderKind])
2870         Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2871     }
2872 
2873     // Emit the top headers.
2874     {
2875       auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2876       RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2877       for (auto *H : TopHeaders)
2878         Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2879     }
2880 
2881     // Emit the imports.
2882     if (!Mod->Imports.empty()) {
2883       RecordData Record;
2884       for (auto *I : Mod->Imports)
2885         Record.push_back(getSubmoduleID(I));
2886       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2887     }
2888 
2889     // Emit the exports.
2890     if (!Mod->Exports.empty()) {
2891       RecordData Record;
2892       for (const auto &E : Mod->Exports) {
2893         // FIXME: This may fail; we don't require that all exported modules
2894         // are local or imported.
2895         Record.push_back(getSubmoduleID(E.getPointer()));
2896         Record.push_back(E.getInt());
2897       }
2898       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2899     }
2900 
2901     //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
2902     // Might be unnecessary as use declarations are only used to build the
2903     // module itself.
2904 
2905     // Emit the link libraries.
2906     for (const auto &LL : Mod->LinkLibraries) {
2907       RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2908                                          LL.IsFramework};
2909       Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2910     }
2911 
2912     // Emit the conflicts.
2913     for (const auto &C : Mod->Conflicts) {
2914       // FIXME: This may fail; we don't require that all conflicting modules
2915       // are local or imported.
2916       RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2917                                          getSubmoduleID(C.Other)};
2918       Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2919     }
2920 
2921     // Emit the configuration macros.
2922     for (const auto &CM : Mod->ConfigMacros) {
2923       RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2924       Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2925     }
2926 
2927     // Emit the initializers, if any.
2928     RecordData Inits;
2929     for (Decl *D : Context->getModuleInitializers(Mod))
2930       Inits.push_back(GetDeclRef(D));
2931     if (!Inits.empty())
2932       Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2933 
2934     // Emit the name of the re-exported module, if any.
2935     if (!Mod->ExportAsModule.empty()) {
2936       RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2937       Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2938     }
2939 
2940     // Queue up the submodules of this module.
2941     for (auto *M : Mod->submodules())
2942       Q.push(M);
2943   }
2944 
2945   Stream.ExitBlock();
2946 
2947   assert((NextSubmoduleID - FirstSubmoduleID ==
2948           getNumberOfModules(WritingModule)) &&
2949          "Wrong # of submodules; found a reference to a non-local, "
2950          "non-imported submodule?");
2951 }
2952 
2953 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2954                                               bool isModule) {
2955   llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2956       DiagStateIDMap;
2957   unsigned CurrID = 0;
2958   RecordData Record;
2959 
2960   auto EncodeDiagStateFlags =
2961       [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2962     unsigned Result = (unsigned)DS->ExtBehavior;
2963     for (unsigned Val :
2964          {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2965           (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2966           (unsigned)DS->SuppressSystemWarnings})
2967       Result = (Result << 1) | Val;
2968     return Result;
2969   };
2970 
2971   unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2972   Record.push_back(Flags);
2973 
2974   auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2975                           bool IncludeNonPragmaStates) {
2976     // Ensure that the diagnostic state wasn't modified since it was created.
2977     // We will not correctly round-trip this information otherwise.
2978     assert(Flags == EncodeDiagStateFlags(State) &&
2979            "diag state flags vary in single AST file");
2980 
2981     unsigned &DiagStateID = DiagStateIDMap[State];
2982     Record.push_back(DiagStateID);
2983 
2984     if (DiagStateID == 0) {
2985       DiagStateID = ++CurrID;
2986 
2987       // Add a placeholder for the number of mappings.
2988       auto SizeIdx = Record.size();
2989       Record.emplace_back();
2990       for (const auto &I : *State) {
2991         if (I.second.isPragma() || IncludeNonPragmaStates) {
2992           Record.push_back(I.first);
2993           Record.push_back(I.second.serialize());
2994         }
2995       }
2996       // Update the placeholder.
2997       Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
2998     }
2999   };
3000 
3001   AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3002 
3003   // Reserve a spot for the number of locations with state transitions.
3004   auto NumLocationsIdx = Record.size();
3005   Record.emplace_back();
3006 
3007   // Emit the state transitions.
3008   unsigned NumLocations = 0;
3009   for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3010     if (!FileIDAndFile.first.isValid() ||
3011         !FileIDAndFile.second.HasLocalTransitions)
3012       continue;
3013     ++NumLocations;
3014     AddSourceLocation(Diag.SourceMgr->getLocForStartOfFile(FileIDAndFile.first),
3015                       Record);
3016     Record.push_back(FileIDAndFile.second.StateTransitions.size());
3017     for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3018       Record.push_back(StatePoint.Offset);
3019       AddDiagState(StatePoint.State, false);
3020     }
3021   }
3022 
3023   // Backpatch the number of locations.
3024   Record[NumLocationsIdx] = NumLocations;
3025 
3026   // Emit CurDiagStateLoc.  Do it last in order to match source order.
3027   //
3028   // This also protects against a hypothetical corner case with simulating
3029   // -Werror settings for implicit modules in the ASTReader, where reading
3030   // CurDiagState out of context could change whether warning pragmas are
3031   // treated as errors.
3032   AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3033   AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3034 
3035   Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3036 }
3037 
3038 //===----------------------------------------------------------------------===//
3039 // Type Serialization
3040 //===----------------------------------------------------------------------===//
3041 
3042 /// \brief Write the representation of a type to the AST stream.
3043 void ASTWriter::WriteType(QualType T) {
3044   TypeIdx &IdxRef = TypeIdxs[T];
3045   if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3046     IdxRef = TypeIdx(NextTypeID++);
3047   TypeIdx Idx = IdxRef;
3048 
3049   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3050 
3051   RecordData Record;
3052 
3053   // Emit the type's representation.
3054   ASTTypeWriter W(*this, Record);
3055   W.Visit(T);
3056   uint64_t Offset = W.Emit();
3057 
3058   // Record the offset for this type.
3059   unsigned Index = Idx.getIndex() - FirstTypeID;
3060   if (TypeOffsets.size() == Index)
3061     TypeOffsets.push_back(Offset);
3062   else if (TypeOffsets.size() < Index) {
3063     TypeOffsets.resize(Index + 1);
3064     TypeOffsets[Index] = Offset;
3065   } else {
3066     llvm_unreachable("Types emitted in wrong order");
3067   }
3068 }
3069 
3070 //===----------------------------------------------------------------------===//
3071 // Declaration Serialization
3072 //===----------------------------------------------------------------------===//
3073 
3074 /// \brief Write the block containing all of the declaration IDs
3075 /// lexically declared within the given DeclContext.
3076 ///
3077 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3078 /// bistream, or 0 if no block was written.
3079 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3080                                                  DeclContext *DC) {
3081   if (DC->decls_empty())
3082     return 0;
3083 
3084   uint64_t Offset = Stream.GetCurrentBitNo();
3085   SmallVector<uint32_t, 128> KindDeclPairs;
3086   for (const auto *D : DC->decls()) {
3087     KindDeclPairs.push_back(D->getKind());
3088     KindDeclPairs.push_back(GetDeclRef(D));
3089   }
3090 
3091   ++NumLexicalDeclContexts;
3092   RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3093   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3094                             bytes(KindDeclPairs));
3095   return Offset;
3096 }
3097 
3098 void ASTWriter::WriteTypeDeclOffsets() {
3099   using namespace llvm;
3100 
3101   // Write the type offsets array
3102   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3103   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3104   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3105   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3106   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3107   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3108   {
3109     RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3110                                        FirstTypeID - NUM_PREDEF_TYPE_IDS};
3111     Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3112   }
3113 
3114   // Write the declaration offsets array
3115   Abbrev = std::make_shared<BitCodeAbbrev>();
3116   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3117   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3118   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3119   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3120   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3121   {
3122     RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3123                                        FirstDeclID - NUM_PREDEF_DECL_IDS};
3124     Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3125   }
3126 }
3127 
3128 void ASTWriter::WriteFileDeclIDsMap() {
3129   using namespace llvm;
3130 
3131   SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3132       FileDeclIDs.begin(), FileDeclIDs.end());
3133   std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
3134             llvm::less_first());
3135 
3136   // Join the vectors of DeclIDs from all files.
3137   SmallVector<DeclID, 256> FileGroupedDeclIDs;
3138   for (auto &FileDeclEntry : SortedFileDeclIDs) {
3139     DeclIDInFileInfo &Info = *FileDeclEntry.second;
3140     Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3141     for (auto &LocDeclEntry : Info.DeclIDs)
3142       FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3143   }
3144 
3145   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3146   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3147   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3148   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3149   unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3150   RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3151                                      FileGroupedDeclIDs.size()};
3152   Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3153 }
3154 
3155 void ASTWriter::WriteComments() {
3156   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3157   ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
3158   RecordData Record;
3159   for (const auto *I : RawComments) {
3160     Record.clear();
3161     AddSourceRange(I->getSourceRange(), Record);
3162     Record.push_back(I->getKind());
3163     Record.push_back(I->isTrailingComment());
3164     Record.push_back(I->isAlmostTrailingComment());
3165     Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3166   }
3167   Stream.ExitBlock();
3168 }
3169 
3170 //===----------------------------------------------------------------------===//
3171 // Global Method Pool and Selector Serialization
3172 //===----------------------------------------------------------------------===//
3173 
3174 namespace {
3175 
3176 // Trait used for the on-disk hash table used in the method pool.
3177 class ASTMethodPoolTrait {
3178   ASTWriter &Writer;
3179 
3180 public:
3181   typedef Selector key_type;
3182   typedef key_type key_type_ref;
3183 
3184   struct data_type {
3185     SelectorID ID;
3186     ObjCMethodList Instance, Factory;
3187   };
3188   typedef const data_type& data_type_ref;
3189 
3190   typedef unsigned hash_value_type;
3191   typedef unsigned offset_type;
3192 
3193   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
3194 
3195   static hash_value_type ComputeHash(Selector Sel) {
3196     return serialization::ComputeHash(Sel);
3197   }
3198 
3199   std::pair<unsigned,unsigned>
3200     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3201                       data_type_ref Methods) {
3202     using namespace llvm::support;
3203     endian::Writer<little> LE(Out);
3204     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3205     LE.write<uint16_t>(KeyLen);
3206     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3207     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3208          Method = Method->getNext())
3209       if (Method->getMethod())
3210         DataLen += 4;
3211     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3212          Method = Method->getNext())
3213       if (Method->getMethod())
3214         DataLen += 4;
3215     LE.write<uint16_t>(DataLen);
3216     return std::make_pair(KeyLen, DataLen);
3217   }
3218 
3219   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3220     using namespace llvm::support;
3221     endian::Writer<little> LE(Out);
3222     uint64_t Start = Out.tell();
3223     assert((Start >> 32) == 0 && "Selector key offset too large");
3224     Writer.SetSelectorOffset(Sel, Start);
3225     unsigned N = Sel.getNumArgs();
3226     LE.write<uint16_t>(N);
3227     if (N == 0)
3228       N = 1;
3229     for (unsigned I = 0; I != N; ++I)
3230       LE.write<uint32_t>(
3231           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3232   }
3233 
3234   void EmitData(raw_ostream& Out, key_type_ref,
3235                 data_type_ref Methods, unsigned DataLen) {
3236     using namespace llvm::support;
3237     endian::Writer<little> LE(Out);
3238     uint64_t Start = Out.tell(); (void)Start;
3239     LE.write<uint32_t>(Methods.ID);
3240     unsigned NumInstanceMethods = 0;
3241     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3242          Method = Method->getNext())
3243       if (Method->getMethod())
3244         ++NumInstanceMethods;
3245 
3246     unsigned NumFactoryMethods = 0;
3247     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3248          Method = Method->getNext())
3249       if (Method->getMethod())
3250         ++NumFactoryMethods;
3251 
3252     unsigned InstanceBits = Methods.Instance.getBits();
3253     assert(InstanceBits < 4);
3254     unsigned InstanceHasMoreThanOneDeclBit =
3255         Methods.Instance.hasMoreThanOneDecl();
3256     unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3257                                 (InstanceHasMoreThanOneDeclBit << 2) |
3258                                 InstanceBits;
3259     unsigned FactoryBits = Methods.Factory.getBits();
3260     assert(FactoryBits < 4);
3261     unsigned FactoryHasMoreThanOneDeclBit =
3262         Methods.Factory.hasMoreThanOneDecl();
3263     unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3264                                (FactoryHasMoreThanOneDeclBit << 2) |
3265                                FactoryBits;
3266     LE.write<uint16_t>(FullInstanceBits);
3267     LE.write<uint16_t>(FullFactoryBits);
3268     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3269          Method = Method->getNext())
3270       if (Method->getMethod())
3271         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3272     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3273          Method = Method->getNext())
3274       if (Method->getMethod())
3275         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3276 
3277     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3278   }
3279 };
3280 
3281 } // end anonymous namespace
3282 
3283 /// \brief Write ObjC data: selectors and the method pool.
3284 ///
3285 /// The method pool contains both instance and factory methods, stored
3286 /// in an on-disk hash table indexed by the selector. The hash table also
3287 /// contains an empty entry for every other selector known to Sema.
3288 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3289   using namespace llvm;
3290 
3291   // Do we have to do anything at all?
3292   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3293     return;
3294   unsigned NumTableEntries = 0;
3295   // Create and write out the blob that contains selectors and the method pool.
3296   {
3297     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3298     ASTMethodPoolTrait Trait(*this);
3299 
3300     // Create the on-disk hash table representation. We walk through every
3301     // selector we've seen and look it up in the method pool.
3302     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3303     for (auto &SelectorAndID : SelectorIDs) {
3304       Selector S = SelectorAndID.first;
3305       SelectorID ID = SelectorAndID.second;
3306       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3307       ASTMethodPoolTrait::data_type Data = {
3308         ID,
3309         ObjCMethodList(),
3310         ObjCMethodList()
3311       };
3312       if (F != SemaRef.MethodPool.end()) {
3313         Data.Instance = F->second.first;
3314         Data.Factory = F->second.second;
3315       }
3316       // Only write this selector if it's not in an existing AST or something
3317       // changed.
3318       if (Chain && ID < FirstSelectorID) {
3319         // Selector already exists. Did it change?
3320         bool changed = false;
3321         for (ObjCMethodList *M = &Data.Instance;
3322              !changed && M && M->getMethod(); M = M->getNext()) {
3323           if (!M->getMethod()->isFromASTFile())
3324             changed = true;
3325         }
3326         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3327              M = M->getNext()) {
3328           if (!M->getMethod()->isFromASTFile())
3329             changed = true;
3330         }
3331         if (!changed)
3332           continue;
3333       } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3334         // A new method pool entry.
3335         ++NumTableEntries;
3336       }
3337       Generator.insert(S, Data, Trait);
3338     }
3339 
3340     // Create the on-disk hash table in a buffer.
3341     SmallString<4096> MethodPool;
3342     uint32_t BucketOffset;
3343     {
3344       using namespace llvm::support;
3345       ASTMethodPoolTrait Trait(*this);
3346       llvm::raw_svector_ostream Out(MethodPool);
3347       // Make sure that no bucket is at offset 0
3348       endian::Writer<little>(Out).write<uint32_t>(0);
3349       BucketOffset = Generator.Emit(Out, Trait);
3350     }
3351 
3352     // Create a blob abbreviation
3353     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3354     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3355     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3356     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3357     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3358     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3359 
3360     // Write the method pool
3361     {
3362       RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3363                                          NumTableEntries};
3364       Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3365     }
3366 
3367     // Create a blob abbreviation for the selector table offsets.
3368     Abbrev = std::make_shared<BitCodeAbbrev>();
3369     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3370     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3371     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3372     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3373     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3374 
3375     // Write the selector offsets table.
3376     {
3377       RecordData::value_type Record[] = {
3378           SELECTOR_OFFSETS, SelectorOffsets.size(),
3379           FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3380       Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3381                                 bytes(SelectorOffsets));
3382     }
3383   }
3384 }
3385 
3386 /// \brief Write the selectors referenced in @selector expression into AST file.
3387 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3388   using namespace llvm;
3389   if (SemaRef.ReferencedSelectors.empty())
3390     return;
3391 
3392   RecordData Record;
3393   ASTRecordWriter Writer(*this, Record);
3394 
3395   // Note: this writes out all references even for a dependent AST. But it is
3396   // very tricky to fix, and given that @selector shouldn't really appear in
3397   // headers, probably not worth it. It's not a correctness issue.
3398   for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3399     Selector Sel = SelectorAndLocation.first;
3400     SourceLocation Loc = SelectorAndLocation.second;
3401     Writer.AddSelectorRef(Sel);
3402     Writer.AddSourceLocation(Loc);
3403   }
3404   Writer.Emit(REFERENCED_SELECTOR_POOL);
3405 }
3406 
3407 //===----------------------------------------------------------------------===//
3408 // Identifier Table Serialization
3409 //===----------------------------------------------------------------------===//
3410 
3411 /// Determine the declaration that should be put into the name lookup table to
3412 /// represent the given declaration in this module. This is usually D itself,
3413 /// but if D was imported and merged into a local declaration, we want the most
3414 /// recent local declaration instead. The chosen declaration will be the most
3415 /// recent declaration in any module that imports this one.
3416 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3417                                         NamedDecl *D) {
3418   if (!LangOpts.Modules || !D->isFromASTFile())
3419     return D;
3420 
3421   if (Decl *Redecl = D->getPreviousDecl()) {
3422     // For Redeclarable decls, a prior declaration might be local.
3423     for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3424       // If we find a local decl, we're done.
3425       if (!Redecl->isFromASTFile()) {
3426         // Exception: in very rare cases (for injected-class-names), not all
3427         // redeclarations are in the same semantic context. Skip ones in a
3428         // different context. They don't go in this lookup table at all.
3429         if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3430                 D->getDeclContext()->getRedeclContext()))
3431           continue;
3432         return cast<NamedDecl>(Redecl);
3433       }
3434 
3435       // If we find a decl from a (chained-)PCH stop since we won't find a
3436       // local one.
3437       if (Redecl->getOwningModuleID() == 0)
3438         break;
3439     }
3440   } else if (Decl *First = D->getCanonicalDecl()) {
3441     // For Mergeable decls, the first decl might be local.
3442     if (!First->isFromASTFile())
3443       return cast<NamedDecl>(First);
3444   }
3445 
3446   // All declarations are imported. Our most recent declaration will also be
3447   // the most recent one in anyone who imports us.
3448   return D;
3449 }
3450 
3451 namespace {
3452 
3453 class ASTIdentifierTableTrait {
3454   ASTWriter &Writer;
3455   Preprocessor &PP;
3456   IdentifierResolver &IdResolver;
3457   bool IsModule;
3458   bool NeedDecls;
3459   ASTWriter::RecordData *InterestingIdentifierOffsets;
3460 
3461   /// \brief Determines whether this is an "interesting" identifier that needs a
3462   /// full IdentifierInfo structure written into the hash table. Notably, this
3463   /// doesn't check whether the name has macros defined; use PublicMacroIterator
3464   /// to check that.
3465   bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3466     if (MacroOffset ||
3467         II->isPoisoned() ||
3468         (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3469         II->hasRevertedTokenIDToIdentifier() ||
3470         (NeedDecls && II->getFETokenInfo<void>()))
3471       return true;
3472 
3473     return false;
3474   }
3475 
3476 public:
3477   typedef IdentifierInfo* key_type;
3478   typedef key_type  key_type_ref;
3479 
3480   typedef IdentID data_type;
3481   typedef data_type data_type_ref;
3482 
3483   typedef unsigned hash_value_type;
3484   typedef unsigned offset_type;
3485 
3486   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3487                           IdentifierResolver &IdResolver, bool IsModule,
3488                           ASTWriter::RecordData *InterestingIdentifierOffsets)
3489       : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3490         NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3491         InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3492 
3493   bool needDecls() const { return NeedDecls; }
3494 
3495   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3496     return llvm::HashString(II->getName());
3497   }
3498 
3499   bool isInterestingIdentifier(const IdentifierInfo *II) {
3500     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3501     return isInterestingIdentifier(II, MacroOffset);
3502   }
3503 
3504   bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3505     return isInterestingIdentifier(II, 0);
3506   }
3507 
3508   std::pair<unsigned,unsigned>
3509   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3510     unsigned KeyLen = II->getLength() + 1;
3511     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3512     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3513     if (isInterestingIdentifier(II, MacroOffset)) {
3514       DataLen += 2; // 2 bytes for builtin ID
3515       DataLen += 2; // 2 bytes for flags
3516       if (MacroOffset)
3517         DataLen += 4; // MacroDirectives offset.
3518 
3519       if (NeedDecls) {
3520         for (IdentifierResolver::iterator D = IdResolver.begin(II),
3521                                        DEnd = IdResolver.end();
3522              D != DEnd; ++D)
3523           DataLen += 4;
3524       }
3525     }
3526     using namespace llvm::support;
3527     endian::Writer<little> LE(Out);
3528 
3529     assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3530     LE.write<uint16_t>(DataLen);
3531     // We emit the key length after the data length so that every
3532     // string is preceded by a 16-bit length. This matches the PTH
3533     // format for storing identifiers.
3534     LE.write<uint16_t>(KeyLen);
3535     return std::make_pair(KeyLen, DataLen);
3536   }
3537 
3538   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3539                unsigned KeyLen) {
3540     // Record the location of the key data.  This is used when generating
3541     // the mapping from persistent IDs to strings.
3542     Writer.SetIdentifierOffset(II, Out.tell());
3543 
3544     // Emit the offset of the key/data length information to the interesting
3545     // identifiers table if necessary.
3546     if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3547       InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3548 
3549     Out.write(II->getNameStart(), KeyLen);
3550   }
3551 
3552   void EmitData(raw_ostream& Out, IdentifierInfo* II,
3553                 IdentID ID, unsigned) {
3554     using namespace llvm::support;
3555     endian::Writer<little> LE(Out);
3556 
3557     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3558     if (!isInterestingIdentifier(II, MacroOffset)) {
3559       LE.write<uint32_t>(ID << 1);
3560       return;
3561     }
3562 
3563     LE.write<uint32_t>((ID << 1) | 0x01);
3564     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3565     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3566     LE.write<uint16_t>(Bits);
3567     Bits = 0;
3568     bool HadMacroDefinition = MacroOffset != 0;
3569     Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3570     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3571     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3572     Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3573     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3574     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3575     LE.write<uint16_t>(Bits);
3576 
3577     if (HadMacroDefinition)
3578       LE.write<uint32_t>(MacroOffset);
3579 
3580     if (NeedDecls) {
3581       // Emit the declaration IDs in reverse order, because the
3582       // IdentifierResolver provides the declarations as they would be
3583       // visible (e.g., the function "stat" would come before the struct
3584       // "stat"), but the ASTReader adds declarations to the end of the list
3585       // (so we need to see the struct "stat" before the function "stat").
3586       // Only emit declarations that aren't from a chained PCH, though.
3587       SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3588                                          IdResolver.end());
3589       for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3590                                                           DEnd = Decls.rend();
3591            D != DEnd; ++D)
3592         LE.write<uint32_t>(
3593             Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3594     }
3595   }
3596 };
3597 
3598 } // end anonymous namespace
3599 
3600 /// \brief Write the identifier table into the AST file.
3601 ///
3602 /// The identifier table consists of a blob containing string data
3603 /// (the actual identifiers themselves) and a separate "offsets" index
3604 /// that maps identifier IDs to locations within the blob.
3605 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3606                                      IdentifierResolver &IdResolver,
3607                                      bool IsModule) {
3608   using namespace llvm;
3609 
3610   RecordData InterestingIdents;
3611 
3612   // Create and write out the blob that contains the identifier
3613   // strings.
3614   {
3615     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3616     ASTIdentifierTableTrait Trait(
3617         *this, PP, IdResolver, IsModule,
3618         (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3619 
3620     // Look for any identifiers that were named while processing the
3621     // headers, but are otherwise not needed. We add these to the hash
3622     // table to enable checking of the predefines buffer in the case
3623     // where the user adds new macro definitions when building the AST
3624     // file.
3625     SmallVector<const IdentifierInfo *, 128> IIs;
3626     for (const auto &ID : PP.getIdentifierTable())
3627       IIs.push_back(ID.second);
3628     // Sort the identifiers lexicographically before getting them references so
3629     // that their order is stable.
3630     std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3631     for (const IdentifierInfo *II : IIs)
3632       if (Trait.isInterestingNonMacroIdentifier(II))
3633         getIdentifierRef(II);
3634 
3635     // Create the on-disk hash table representation. We only store offsets
3636     // for identifiers that appear here for the first time.
3637     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3638     for (auto IdentIDPair : IdentifierIDs) {
3639       auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3640       IdentID ID = IdentIDPair.second;
3641       assert(II && "NULL identifier in identifier table");
3642       // Write out identifiers if either the ID is local or the identifier has
3643       // changed since it was loaded.
3644       if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3645           || II->hasChangedSinceDeserialization() ||
3646           (Trait.needDecls() &&
3647            II->hasFETokenInfoChangedSinceDeserialization()))
3648         Generator.insert(II, ID, Trait);
3649     }
3650 
3651     // Create the on-disk hash table in a buffer.
3652     SmallString<4096> IdentifierTable;
3653     uint32_t BucketOffset;
3654     {
3655       using namespace llvm::support;
3656       llvm::raw_svector_ostream Out(IdentifierTable);
3657       // Make sure that no bucket is at offset 0
3658       endian::Writer<little>(Out).write<uint32_t>(0);
3659       BucketOffset = Generator.Emit(Out, Trait);
3660     }
3661 
3662     // Create a blob abbreviation
3663     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3664     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3665     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3666     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3667     unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3668 
3669     // Write the identifier table
3670     RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3671     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3672   }
3673 
3674   // Write the offsets table for identifier IDs.
3675   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3676   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3677   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3678   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3679   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3680   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3681 
3682 #ifndef NDEBUG
3683   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3684     assert(IdentifierOffsets[I] && "Missing identifier offset?");
3685 #endif
3686 
3687   RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3688                                      IdentifierOffsets.size(),
3689                                      FirstIdentID - NUM_PREDEF_IDENT_IDS};
3690   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3691                             bytes(IdentifierOffsets));
3692 
3693   // In C++, write the list of interesting identifiers (those that are
3694   // defined as macros, poisoned, or similar unusual things).
3695   if (!InterestingIdents.empty())
3696     Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3697 }
3698 
3699 //===----------------------------------------------------------------------===//
3700 // DeclContext's Name Lookup Table Serialization
3701 //===----------------------------------------------------------------------===//
3702 
3703 namespace {
3704 
3705 // Trait used for the on-disk hash table used in the method pool.
3706 class ASTDeclContextNameLookupTrait {
3707   ASTWriter &Writer;
3708   llvm::SmallVector<DeclID, 64> DeclIDs;
3709 
3710 public:
3711   typedef DeclarationNameKey key_type;
3712   typedef key_type key_type_ref;
3713 
3714   /// A start and end index into DeclIDs, representing a sequence of decls.
3715   typedef std::pair<unsigned, unsigned> data_type;
3716   typedef const data_type& data_type_ref;
3717 
3718   typedef unsigned hash_value_type;
3719   typedef unsigned offset_type;
3720 
3721   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3722 
3723   template<typename Coll>
3724   data_type getData(const Coll &Decls) {
3725     unsigned Start = DeclIDs.size();
3726     for (NamedDecl *D : Decls) {
3727       DeclIDs.push_back(
3728           Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3729     }
3730     return std::make_pair(Start, DeclIDs.size());
3731   }
3732 
3733   data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3734     unsigned Start = DeclIDs.size();
3735     for (auto ID : FromReader)
3736       DeclIDs.push_back(ID);
3737     return std::make_pair(Start, DeclIDs.size());
3738   }
3739 
3740   static bool EqualKey(key_type_ref a, key_type_ref b) {
3741     return a == b;
3742   }
3743 
3744   hash_value_type ComputeHash(DeclarationNameKey Name) {
3745     return Name.getHash();
3746   }
3747 
3748   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3749     assert(Writer.hasChain() &&
3750            "have reference to loaded module file but no chain?");
3751 
3752     using namespace llvm::support;
3753     endian::Writer<little>(Out)
3754         .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3755   }
3756 
3757   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3758                                                   DeclarationNameKey Name,
3759                                                   data_type_ref Lookup) {
3760     using namespace llvm::support;
3761     endian::Writer<little> LE(Out);
3762     unsigned KeyLen = 1;
3763     switch (Name.getKind()) {
3764     case DeclarationName::Identifier:
3765     case DeclarationName::ObjCZeroArgSelector:
3766     case DeclarationName::ObjCOneArgSelector:
3767     case DeclarationName::ObjCMultiArgSelector:
3768     case DeclarationName::CXXLiteralOperatorName:
3769     case DeclarationName::CXXDeductionGuideName:
3770       KeyLen += 4;
3771       break;
3772     case DeclarationName::CXXOperatorName:
3773       KeyLen += 1;
3774       break;
3775     case DeclarationName::CXXConstructorName:
3776     case DeclarationName::CXXDestructorName:
3777     case DeclarationName::CXXConversionFunctionName:
3778     case DeclarationName::CXXUsingDirective:
3779       break;
3780     }
3781     LE.write<uint16_t>(KeyLen);
3782 
3783     // 4 bytes for each DeclID.
3784     unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3785     assert(uint16_t(DataLen) == DataLen &&
3786            "too many decls for serialized lookup result");
3787     LE.write<uint16_t>(DataLen);
3788 
3789     return std::make_pair(KeyLen, DataLen);
3790   }
3791 
3792   void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3793     using namespace llvm::support;
3794     endian::Writer<little> LE(Out);
3795     LE.write<uint8_t>(Name.getKind());
3796     switch (Name.getKind()) {
3797     case DeclarationName::Identifier:
3798     case DeclarationName::CXXLiteralOperatorName:
3799     case DeclarationName::CXXDeductionGuideName:
3800       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3801       return;
3802     case DeclarationName::ObjCZeroArgSelector:
3803     case DeclarationName::ObjCOneArgSelector:
3804     case DeclarationName::ObjCMultiArgSelector:
3805       LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3806       return;
3807     case DeclarationName::CXXOperatorName:
3808       assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3809              "Invalid operator?");
3810       LE.write<uint8_t>(Name.getOperatorKind());
3811       return;
3812     case DeclarationName::CXXConstructorName:
3813     case DeclarationName::CXXDestructorName:
3814     case DeclarationName::CXXConversionFunctionName:
3815     case DeclarationName::CXXUsingDirective:
3816       return;
3817     }
3818 
3819     llvm_unreachable("Invalid name kind?");
3820   }
3821 
3822   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3823                 unsigned DataLen) {
3824     using namespace llvm::support;
3825     endian::Writer<little> LE(Out);
3826     uint64_t Start = Out.tell(); (void)Start;
3827     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3828       LE.write<uint32_t>(DeclIDs[I]);
3829     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3830   }
3831 };
3832 
3833 } // end anonymous namespace
3834 
3835 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3836                                        DeclContext *DC) {
3837   return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3838 }
3839 
3840 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3841                                                DeclContext *DC) {
3842   for (auto *D : Result.getLookupResult())
3843     if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3844       return false;
3845 
3846   return true;
3847 }
3848 
3849 void
3850 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3851                                    llvm::SmallVectorImpl<char> &LookupTable) {
3852   assert(!ConstDC->HasLazyLocalLexicalLookups &&
3853          !ConstDC->HasLazyExternalLexicalLookups &&
3854          "must call buildLookups first");
3855 
3856   // FIXME: We need to build the lookups table, which is logically const.
3857   auto *DC = const_cast<DeclContext*>(ConstDC);
3858   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3859 
3860   // Create the on-disk hash table representation.
3861   MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3862                                 ASTDeclContextNameLookupTrait> Generator;
3863   ASTDeclContextNameLookupTrait Trait(*this);
3864 
3865   // The first step is to collect the declaration names which we need to
3866   // serialize into the name lookup table, and to collect them in a stable
3867   // order.
3868   SmallVector<DeclarationName, 16> Names;
3869 
3870   // We also build up small sets of the constructor and conversion function
3871   // names which are visible.
3872   llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3873 
3874   for (auto &Lookup : *DC->buildLookup()) {
3875     auto &Name = Lookup.first;
3876     auto &Result = Lookup.second;
3877 
3878     // If there are no local declarations in our lookup result, we
3879     // don't need to write an entry for the name at all. If we can't
3880     // write out a lookup set without performing more deserialization,
3881     // just skip this entry.
3882     if (isLookupResultExternal(Result, DC) &&
3883         isLookupResultEntirelyExternal(Result, DC))
3884       continue;
3885 
3886     // We also skip empty results. If any of the results could be external and
3887     // the currently available results are empty, then all of the results are
3888     // external and we skip it above. So the only way we get here with an empty
3889     // results is when no results could have been external *and* we have
3890     // external results.
3891     //
3892     // FIXME: While we might want to start emitting on-disk entries for negative
3893     // lookups into a decl context as an optimization, today we *have* to skip
3894     // them because there are names with empty lookup results in decl contexts
3895     // which we can't emit in any stable ordering: we lookup constructors and
3896     // conversion functions in the enclosing namespace scope creating empty
3897     // results for them. This in almost certainly a bug in Clang's name lookup,
3898     // but that is likely to be hard or impossible to fix and so we tolerate it
3899     // here by omitting lookups with empty results.
3900     if (Lookup.second.getLookupResult().empty())
3901       continue;
3902 
3903     switch (Lookup.first.getNameKind()) {
3904     default:
3905       Names.push_back(Lookup.first);
3906       break;
3907 
3908     case DeclarationName::CXXConstructorName:
3909       assert(isa<CXXRecordDecl>(DC) &&
3910              "Cannot have a constructor name outside of a class!");
3911       ConstructorNameSet.insert(Name);
3912       break;
3913 
3914     case DeclarationName::CXXConversionFunctionName:
3915       assert(isa<CXXRecordDecl>(DC) &&
3916              "Cannot have a conversion function name outside of a class!");
3917       ConversionNameSet.insert(Name);
3918       break;
3919     }
3920   }
3921 
3922   // Sort the names into a stable order.
3923   std::sort(Names.begin(), Names.end());
3924 
3925   if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3926     // We need to establish an ordering of constructor and conversion function
3927     // names, and they don't have an intrinsic ordering.
3928 
3929     // First we try the easy case by forming the current context's constructor
3930     // name and adding that name first. This is a very useful optimization to
3931     // avoid walking the lexical declarations in many cases, and it also
3932     // handles the only case where a constructor name can come from some other
3933     // lexical context -- when that name is an implicit constructor merged from
3934     // another declaration in the redecl chain. Any non-implicit constructor or
3935     // conversion function which doesn't occur in all the lexical contexts
3936     // would be an ODR violation.
3937     auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3938         Context->getCanonicalType(Context->getRecordType(D)));
3939     if (ConstructorNameSet.erase(ImplicitCtorName))
3940       Names.push_back(ImplicitCtorName);
3941 
3942     // If we still have constructors or conversion functions, we walk all the
3943     // names in the decl and add the constructors and conversion functions
3944     // which are visible in the order they lexically occur within the context.
3945     if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3946       for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3947         if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3948           auto Name = ChildND->getDeclName();
3949           switch (Name.getNameKind()) {
3950           default:
3951             continue;
3952 
3953           case DeclarationName::CXXConstructorName:
3954             if (ConstructorNameSet.erase(Name))
3955               Names.push_back(Name);
3956             break;
3957 
3958           case DeclarationName::CXXConversionFunctionName:
3959             if (ConversionNameSet.erase(Name))
3960               Names.push_back(Name);
3961             break;
3962           }
3963 
3964           if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3965             break;
3966         }
3967 
3968     assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3969                                          "constructors by walking all the "
3970                                          "lexical members of the context.");
3971     assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3972                                         "conversion functions by walking all "
3973                                         "the lexical members of the context.");
3974   }
3975 
3976   // Next we need to do a lookup with each name into this decl context to fully
3977   // populate any results from external sources. We don't actually use the
3978   // results of these lookups because we only want to use the results after all
3979   // results have been loaded and the pointers into them will be stable.
3980   for (auto &Name : Names)
3981     DC->lookup(Name);
3982 
3983   // Now we need to insert the results for each name into the hash table. For
3984   // constructor names and conversion function names, we actually need to merge
3985   // all of the results for them into one list of results each and insert
3986   // those.
3987   SmallVector<NamedDecl *, 8> ConstructorDecls;
3988   SmallVector<NamedDecl *, 8> ConversionDecls;
3989 
3990   // Now loop over the names, either inserting them or appending for the two
3991   // special cases.
3992   for (auto &Name : Names) {
3993     DeclContext::lookup_result Result = DC->noload_lookup(Name);
3994 
3995     switch (Name.getNameKind()) {
3996     default:
3997       Generator.insert(Name, Trait.getData(Result), Trait);
3998       break;
3999 
4000     case DeclarationName::CXXConstructorName:
4001       ConstructorDecls.append(Result.begin(), Result.end());
4002       break;
4003 
4004     case DeclarationName::CXXConversionFunctionName:
4005       ConversionDecls.append(Result.begin(), Result.end());
4006       break;
4007     }
4008   }
4009 
4010   // Handle our two special cases if we ended up having any. We arbitrarily use
4011   // the first declaration's name here because the name itself isn't part of
4012   // the key, only the kind of name is used.
4013   if (!ConstructorDecls.empty())
4014     Generator.insert(ConstructorDecls.front()->getDeclName(),
4015                      Trait.getData(ConstructorDecls), Trait);
4016   if (!ConversionDecls.empty())
4017     Generator.insert(ConversionDecls.front()->getDeclName(),
4018                      Trait.getData(ConversionDecls), Trait);
4019 
4020   // Create the on-disk hash table. Also emit the existing imported and
4021   // merged table if there is one.
4022   auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4023   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4024 }
4025 
4026 /// \brief Write the block containing all of the declaration IDs
4027 /// visible from the given DeclContext.
4028 ///
4029 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4030 /// bitstream, or 0 if no block was written.
4031 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4032                                                  DeclContext *DC) {
4033   // If we imported a key declaration of this namespace, write the visible
4034   // lookup results as an update record for it rather than including them
4035   // on this declaration. We will only look at key declarations on reload.
4036   if (isa<NamespaceDecl>(DC) && Chain &&
4037       Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4038     // Only do this once, for the first local declaration of the namespace.
4039     for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4040          Prev = Prev->getPreviousDecl())
4041       if (!Prev->isFromASTFile())
4042         return 0;
4043 
4044     // Note that we need to emit an update record for the primary context.
4045     UpdatedDeclContexts.insert(DC->getPrimaryContext());
4046 
4047     // Make sure all visible decls are written. They will be recorded later. We
4048     // do this using a side data structure so we can sort the names into
4049     // a deterministic order.
4050     StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4051     SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4052         LookupResults;
4053     if (Map) {
4054       LookupResults.reserve(Map->size());
4055       for (auto &Entry : *Map)
4056         LookupResults.push_back(
4057             std::make_pair(Entry.first, Entry.second.getLookupResult()));
4058     }
4059 
4060     std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
4061     for (auto &NameAndResult : LookupResults) {
4062       DeclarationName Name = NameAndResult.first;
4063       DeclContext::lookup_result Result = NameAndResult.second;
4064       if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4065           Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4066         // We have to work around a name lookup bug here where negative lookup
4067         // results for these names get cached in namespace lookup tables (these
4068         // names should never be looked up in a namespace).
4069         assert(Result.empty() && "Cannot have a constructor or conversion "
4070                                  "function name in a namespace!");
4071         continue;
4072       }
4073 
4074       for (NamedDecl *ND : Result)
4075         if (!ND->isFromASTFile())
4076           GetDeclRef(ND);
4077     }
4078 
4079     return 0;
4080   }
4081 
4082   if (DC->getPrimaryContext() != DC)
4083     return 0;
4084 
4085   // Skip contexts which don't support name lookup.
4086   if (!DC->isLookupContext())
4087     return 0;
4088 
4089   // If not in C++, we perform name lookup for the translation unit via the
4090   // IdentifierInfo chains, don't bother to build a visible-declarations table.
4091   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4092     return 0;
4093 
4094   // Serialize the contents of the mapping used for lookup. Note that,
4095   // although we have two very different code paths, the serialized
4096   // representation is the same for both cases: a declaration name,
4097   // followed by a size, followed by references to the visible
4098   // declarations that have that name.
4099   uint64_t Offset = Stream.GetCurrentBitNo();
4100   StoredDeclsMap *Map = DC->buildLookup();
4101   if (!Map || Map->empty())
4102     return 0;
4103 
4104   // Create the on-disk hash table in a buffer.
4105   SmallString<4096> LookupTable;
4106   GenerateNameLookupTable(DC, LookupTable);
4107 
4108   // Write the lookup table
4109   RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4110   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4111                             LookupTable);
4112   ++NumVisibleDeclContexts;
4113   return Offset;
4114 }
4115 
4116 /// \brief Write an UPDATE_VISIBLE block for the given context.
4117 ///
4118 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4119 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4120 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4121 /// enumeration members (in C++11).
4122 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4123   StoredDeclsMap *Map = DC->getLookupPtr();
4124   if (!Map || Map->empty())
4125     return;
4126 
4127   // Create the on-disk hash table in a buffer.
4128   SmallString<4096> LookupTable;
4129   GenerateNameLookupTable(DC, LookupTable);
4130 
4131   // If we're updating a namespace, select a key declaration as the key for the
4132   // update record; those are the only ones that will be checked on reload.
4133   if (isa<NamespaceDecl>(DC))
4134     DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4135 
4136   // Write the lookup table
4137   RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4138   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4139 }
4140 
4141 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4142 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4143   RecordData::value_type Record[] = {Opts.getInt()};
4144   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4145 }
4146 
4147 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4148 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4149   if (!SemaRef.Context.getLangOpts().OpenCL)
4150     return;
4151 
4152   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4153   RecordData Record;
4154   for (const auto &I:Opts.OptMap) {
4155     AddString(I.getKey(), Record);
4156     auto V = I.getValue();
4157     Record.push_back(V.Supported ? 1 : 0);
4158     Record.push_back(V.Enabled ? 1 : 0);
4159     Record.push_back(V.Avail);
4160     Record.push_back(V.Core);
4161   }
4162   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4163 }
4164 
4165 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4166   if (!SemaRef.Context.getLangOpts().OpenCL)
4167     return;
4168 
4169   RecordData Record;
4170   for (const auto &I : SemaRef.OpenCLTypeExtMap) {
4171     Record.push_back(
4172         static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
4173     Record.push_back(I.second.size());
4174     for (auto Ext : I.second)
4175       AddString(Ext, Record);
4176   }
4177   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4178 }
4179 
4180 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4181   if (!SemaRef.Context.getLangOpts().OpenCL)
4182     return;
4183 
4184   RecordData Record;
4185   for (const auto &I : SemaRef.OpenCLDeclExtMap) {
4186     Record.push_back(getDeclID(I.first));
4187     Record.push_back(static_cast<unsigned>(I.second.size()));
4188     for (auto Ext : I.second)
4189       AddString(Ext, Record);
4190   }
4191   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4192 }
4193 
4194 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4195   if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4196     RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4197     Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4198   }
4199 }
4200 
4201 void ASTWriter::WriteObjCCategories() {
4202   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4203   RecordData Categories;
4204 
4205   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4206     unsigned Size = 0;
4207     unsigned StartIndex = Categories.size();
4208 
4209     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4210 
4211     // Allocate space for the size.
4212     Categories.push_back(0);
4213 
4214     // Add the categories.
4215     for (ObjCInterfaceDecl::known_categories_iterator
4216            Cat = Class->known_categories_begin(),
4217            CatEnd = Class->known_categories_end();
4218          Cat != CatEnd; ++Cat, ++Size) {
4219       assert(getDeclID(*Cat) != 0 && "Bogus category");
4220       AddDeclRef(*Cat, Categories);
4221     }
4222 
4223     // Update the size.
4224     Categories[StartIndex] = Size;
4225 
4226     // Record this interface -> category map.
4227     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4228     CategoriesMap.push_back(CatInfo);
4229   }
4230 
4231   // Sort the categories map by the definition ID, since the reader will be
4232   // performing binary searches on this information.
4233   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4234 
4235   // Emit the categories map.
4236   using namespace llvm;
4237 
4238   auto Abbrev = std::make_shared<BitCodeAbbrev>();
4239   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4240   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4241   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4242   unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4243 
4244   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4245   Stream.EmitRecordWithBlob(AbbrevID, Record,
4246                             reinterpret_cast<char *>(CategoriesMap.data()),
4247                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4248 
4249   // Emit the category lists.
4250   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4251 }
4252 
4253 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4254   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4255 
4256   if (LPTMap.empty())
4257     return;
4258 
4259   RecordData Record;
4260   for (auto &LPTMapEntry : LPTMap) {
4261     const FunctionDecl *FD = LPTMapEntry.first;
4262     LateParsedTemplate &LPT = *LPTMapEntry.second;
4263     AddDeclRef(FD, Record);
4264     AddDeclRef(LPT.D, Record);
4265     Record.push_back(LPT.Toks.size());
4266 
4267     for (const auto &Tok : LPT.Toks) {
4268       AddToken(Tok, Record);
4269     }
4270   }
4271   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4272 }
4273 
4274 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
4275 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4276   RecordData Record;
4277   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4278   AddSourceLocation(PragmaLoc, Record);
4279   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4280 }
4281 
4282 /// \brief Write the state of 'pragma ms_struct' at the end of the module.
4283 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4284   RecordData Record;
4285   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4286   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4287 }
4288 
4289 /// \brief Write the state of 'pragma pointers_to_members' at the end of the
4290 //module.
4291 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4292   RecordData Record;
4293   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4294   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4295   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4296 }
4297 
4298 /// \brief Write the state of 'pragma pack' at the end of the module.
4299 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4300   // Don't serialize pragma pack state for modules, since it should only take
4301   // effect on a per-submodule basis.
4302   if (WritingModule)
4303     return;
4304 
4305   RecordData Record;
4306   Record.push_back(SemaRef.PackStack.CurrentValue);
4307   AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4308   Record.push_back(SemaRef.PackStack.Stack.size());
4309   for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4310     Record.push_back(StackEntry.Value);
4311     AddSourceLocation(StackEntry.PragmaLocation, Record);
4312     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4313     AddString(StackEntry.StackSlotLabel, Record);
4314   }
4315   Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4316 }
4317 
4318 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4319                                          ModuleFileExtensionWriter &Writer) {
4320   // Enter the extension block.
4321   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4322 
4323   // Emit the metadata record abbreviation.
4324   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4325   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4326   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4327   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4328   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4329   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4330   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4331   unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4332 
4333   // Emit the metadata record.
4334   RecordData Record;
4335   auto Metadata = Writer.getExtension()->getExtensionMetadata();
4336   Record.push_back(EXTENSION_METADATA);
4337   Record.push_back(Metadata.MajorVersion);
4338   Record.push_back(Metadata.MinorVersion);
4339   Record.push_back(Metadata.BlockName.size());
4340   Record.push_back(Metadata.UserInfo.size());
4341   SmallString<64> Buffer;
4342   Buffer += Metadata.BlockName;
4343   Buffer += Metadata.UserInfo;
4344   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4345 
4346   // Emit the contents of the extension block.
4347   Writer.writeExtensionContents(SemaRef, Stream);
4348 
4349   // Exit the extension block.
4350   Stream.ExitBlock();
4351 }
4352 
4353 //===----------------------------------------------------------------------===//
4354 // General Serialization Routines
4355 //===----------------------------------------------------------------------===//
4356 
4357 /// \brief Emit the list of attributes to the specified record.
4358 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4359   auto &Record = *this;
4360   Record.push_back(Attrs.size());
4361   for (const auto *A : Attrs) {
4362     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
4363     Record.AddSourceRange(A->getRange());
4364 
4365 #include "clang/Serialization/AttrPCHWrite.inc"
4366 
4367   }
4368 }
4369 
4370 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4371   AddSourceLocation(Tok.getLocation(), Record);
4372   Record.push_back(Tok.getLength());
4373 
4374   // FIXME: When reading literal tokens, reconstruct the literal pointer
4375   // if it is needed.
4376   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4377   // FIXME: Should translate token kind to a stable encoding.
4378   Record.push_back(Tok.getKind());
4379   // FIXME: Should translate token flags to a stable encoding.
4380   Record.push_back(Tok.getFlags());
4381 }
4382 
4383 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4384   Record.push_back(Str.size());
4385   Record.insert(Record.end(), Str.begin(), Str.end());
4386 }
4387 
4388 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4389   assert(Context && "should have context when outputting path");
4390 
4391   bool Changed =
4392       cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4393 
4394   // Remove a prefix to make the path relative, if relevant.
4395   const char *PathBegin = Path.data();
4396   const char *PathPtr =
4397       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4398   if (PathPtr != PathBegin) {
4399     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4400     Changed = true;
4401   }
4402 
4403   return Changed;
4404 }
4405 
4406 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4407   SmallString<128> FilePath(Path);
4408   PreparePathForOutput(FilePath);
4409   AddString(FilePath, Record);
4410 }
4411 
4412 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4413                                    StringRef Path) {
4414   SmallString<128> FilePath(Path);
4415   PreparePathForOutput(FilePath);
4416   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4417 }
4418 
4419 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4420                                 RecordDataImpl &Record) {
4421   Record.push_back(Version.getMajor());
4422   if (Optional<unsigned> Minor = Version.getMinor())
4423     Record.push_back(*Minor + 1);
4424   else
4425     Record.push_back(0);
4426   if (Optional<unsigned> Subminor = Version.getSubminor())
4427     Record.push_back(*Subminor + 1);
4428   else
4429     Record.push_back(0);
4430 }
4431 
4432 /// \brief Note that the identifier II occurs at the given offset
4433 /// within the identifier table.
4434 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4435   IdentID ID = IdentifierIDs[II];
4436   // Only store offsets new to this AST file. Other identifier names are looked
4437   // up earlier in the chain and thus don't need an offset.
4438   if (ID >= FirstIdentID)
4439     IdentifierOffsets[ID - FirstIdentID] = Offset;
4440 }
4441 
4442 /// \brief Note that the selector Sel occurs at the given offset
4443 /// within the method pool/selector table.
4444 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4445   unsigned ID = SelectorIDs[Sel];
4446   assert(ID && "Unknown selector");
4447   // Don't record offsets for selectors that are also available in a different
4448   // file.
4449   if (ID < FirstSelectorID)
4450     return;
4451   SelectorOffsets[ID - FirstSelectorID] = Offset;
4452 }
4453 
4454 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4455                      SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
4456                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4457                      bool IncludeTimestamps)
4458     : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
4459       IncludeTimestamps(IncludeTimestamps) {
4460   for (const auto &Ext : Extensions) {
4461     if (auto Writer = Ext->createExtensionWriter(*this))
4462       ModuleFileExtensionWriters.push_back(std::move(Writer));
4463   }
4464 }
4465 
4466 ASTWriter::~ASTWriter() {
4467   llvm::DeleteContainerSeconds(FileDeclIDs);
4468 }
4469 
4470 const LangOptions &ASTWriter::getLangOpts() const {
4471   assert(WritingAST && "can't determine lang opts when not writing AST");
4472   return Context->getLangOpts();
4473 }
4474 
4475 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4476   return IncludeTimestamps ? E->getModificationTime() : 0;
4477 }
4478 
4479 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4480                                      const std::string &OutputFile,
4481                                      Module *WritingModule, StringRef isysroot,
4482                                      bool hasErrors) {
4483   WritingAST = true;
4484 
4485   ASTHasCompilerErrors = hasErrors;
4486 
4487   // Emit the file header.
4488   Stream.Emit((unsigned)'C', 8);
4489   Stream.Emit((unsigned)'P', 8);
4490   Stream.Emit((unsigned)'C', 8);
4491   Stream.Emit((unsigned)'H', 8);
4492 
4493   WriteBlockInfoBlock();
4494 
4495   Context = &SemaRef.Context;
4496   PP = &SemaRef.PP;
4497   this->WritingModule = WritingModule;
4498   ASTFileSignature Signature =
4499       WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4500   Context = nullptr;
4501   PP = nullptr;
4502   this->WritingModule = nullptr;
4503   this->BaseDirectory.clear();
4504 
4505   WritingAST = false;
4506   if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
4507     // Construct MemoryBuffer and update buffer manager.
4508     PCMCache.addBuffer(OutputFile,
4509                        llvm::MemoryBuffer::getMemBufferCopy(
4510                            StringRef(Buffer.begin(), Buffer.size())));
4511   }
4512   return Signature;
4513 }
4514 
4515 template<typename Vector>
4516 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4517                                ASTWriter::RecordData &Record) {
4518   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4519        I != E; ++I) {
4520     Writer.AddDeclRef(*I, Record);
4521   }
4522 }
4523 
4524 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4525                                          const std::string &OutputFile,
4526                                          Module *WritingModule) {
4527   using namespace llvm;
4528 
4529   bool isModule = WritingModule != nullptr;
4530 
4531   // Make sure that the AST reader knows to finalize itself.
4532   if (Chain)
4533     Chain->finalizeForWriting();
4534 
4535   ASTContext &Context = SemaRef.Context;
4536   Preprocessor &PP = SemaRef.PP;
4537 
4538   // Set up predefined declaration IDs.
4539   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4540     if (D) {
4541       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4542       DeclIDs[D] = ID;
4543     }
4544   };
4545   RegisterPredefDecl(Context.getTranslationUnitDecl(),
4546                      PREDEF_DECL_TRANSLATION_UNIT_ID);
4547   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4548   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4549   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4550   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4551                      PREDEF_DECL_OBJC_PROTOCOL_ID);
4552   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4553   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4554   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4555                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4556   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4557   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4558   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4559                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4560   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4561   RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4562                      PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4563   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4564                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
4565   RegisterPredefDecl(Context.CFConstantStringTagDecl,
4566                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4567   RegisterPredefDecl(Context.TypePackElementDecl,
4568                      PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4569 
4570   // Build a record containing all of the tentative definitions in this file, in
4571   // TentativeDefinitions order.  Generally, this record will be empty for
4572   // headers.
4573   RecordData TentativeDefinitions;
4574   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4575 
4576   // Build a record containing all of the file scoped decls in this file.
4577   RecordData UnusedFileScopedDecls;
4578   if (!isModule)
4579     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4580                        UnusedFileScopedDecls);
4581 
4582   // Build a record containing all of the delegating constructors we still need
4583   // to resolve.
4584   RecordData DelegatingCtorDecls;
4585   if (!isModule)
4586     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4587 
4588   // Write the set of weak, undeclared identifiers. We always write the
4589   // entire table, since later PCH files in a PCH chain are only interested in
4590   // the results at the end of the chain.
4591   RecordData WeakUndeclaredIdentifiers;
4592   for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4593     IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4594     WeakInfo &WI = WeakUndeclaredIdentifier.second;
4595     AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4596     AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4597     AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4598     WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4599   }
4600 
4601   // Build a record containing all of the ext_vector declarations.
4602   RecordData ExtVectorDecls;
4603   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4604 
4605   // Build a record containing all of the VTable uses information.
4606   RecordData VTableUses;
4607   if (!SemaRef.VTableUses.empty()) {
4608     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4609       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4610       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4611       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4612     }
4613   }
4614 
4615   // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4616   RecordData UnusedLocalTypedefNameCandidates;
4617   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4618     AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4619 
4620   // Build a record containing all of pending implicit instantiations.
4621   RecordData PendingInstantiations;
4622   for (const auto &I : SemaRef.PendingInstantiations) {
4623     AddDeclRef(I.first, PendingInstantiations);
4624     AddSourceLocation(I.second, PendingInstantiations);
4625   }
4626   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4627          "There are local ones at end of translation unit!");
4628 
4629   // Build a record containing some declaration references.
4630   RecordData SemaDeclRefs;
4631   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4632     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4633     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4634     AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4635   }
4636 
4637   RecordData CUDASpecialDeclRefs;
4638   if (Context.getcudaConfigureCallDecl()) {
4639     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4640   }
4641 
4642   // Build a record containing all of the known namespaces.
4643   RecordData KnownNamespaces;
4644   for (const auto &I : SemaRef.KnownNamespaces) {
4645     if (!I.second)
4646       AddDeclRef(I.first, KnownNamespaces);
4647   }
4648 
4649   // Build a record of all used, undefined objects that require definitions.
4650   RecordData UndefinedButUsed;
4651 
4652   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4653   SemaRef.getUndefinedButUsed(Undefined);
4654   for (const auto &I : Undefined) {
4655     AddDeclRef(I.first, UndefinedButUsed);
4656     AddSourceLocation(I.second, UndefinedButUsed);
4657   }
4658 
4659   // Build a record containing all delete-expressions that we would like to
4660   // analyze later in AST.
4661   RecordData DeleteExprsToAnalyze;
4662 
4663   for (const auto &DeleteExprsInfo :
4664        SemaRef.getMismatchingDeleteExpressions()) {
4665     AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4666     DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4667     for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4668       AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4669       DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4670     }
4671   }
4672 
4673   // Write the control block
4674   WriteControlBlock(PP, Context, isysroot, OutputFile);
4675 
4676   // Write the remaining AST contents.
4677   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4678 
4679   // This is so that older clang versions, before the introduction
4680   // of the control block, can read and reject the newer PCH format.
4681   {
4682     RecordData Record = {VERSION_MAJOR};
4683     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4684   }
4685 
4686   // Create a lexical update block containing all of the declarations in the
4687   // translation unit that do not come from other AST files.
4688   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4689   SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4690   for (const auto *D : TU->noload_decls()) {
4691     if (!D->isFromASTFile()) {
4692       NewGlobalKindDeclPairs.push_back(D->getKind());
4693       NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4694     }
4695   }
4696 
4697   auto Abv = std::make_shared<BitCodeAbbrev>();
4698   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4699   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4700   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4701   {
4702     RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4703     Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4704                               bytes(NewGlobalKindDeclPairs));
4705   }
4706 
4707   // And a visible updates block for the translation unit.
4708   Abv = std::make_shared<BitCodeAbbrev>();
4709   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4710   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4711   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4712   UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4713   WriteDeclContextVisibleUpdate(TU);
4714 
4715   // If we have any extern "C" names, write out a visible update for them.
4716   if (Context.ExternCContext)
4717     WriteDeclContextVisibleUpdate(Context.ExternCContext);
4718 
4719   // If the translation unit has an anonymous namespace, and we don't already
4720   // have an update block for it, write it as an update block.
4721   // FIXME: Why do we not do this if there's already an update block?
4722   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4723     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4724     if (Record.empty())
4725       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4726   }
4727 
4728   // Add update records for all mangling numbers and static local numbers.
4729   // These aren't really update records, but this is a convenient way of
4730   // tagging this rare extra data onto the declarations.
4731   for (const auto &Number : Context.MangleNumbers)
4732     if (!Number.first->isFromASTFile())
4733       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4734                                                      Number.second));
4735   for (const auto &Number : Context.StaticLocalNumbers)
4736     if (!Number.first->isFromASTFile())
4737       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4738                                                      Number.second));
4739 
4740   // Make sure visible decls, added to DeclContexts previously loaded from
4741   // an AST file, are registered for serialization. Likewise for template
4742   // specializations added to imported templates.
4743   for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4744     GetDeclRef(I);
4745   }
4746 
4747   // Make sure all decls associated with an identifier are registered for
4748   // serialization, if we're storing decls with identifiers.
4749   if (!WritingModule || !getLangOpts().CPlusPlus) {
4750     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4751     for (const auto &ID : PP.getIdentifierTable()) {
4752       const IdentifierInfo *II = ID.second;
4753       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4754         IIs.push_back(II);
4755     }
4756     // Sort the identifiers to visit based on their name.
4757     std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4758     for (const IdentifierInfo *II : IIs) {
4759       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4760                                      DEnd = SemaRef.IdResolver.end();
4761            D != DEnd; ++D) {
4762         GetDeclRef(*D);
4763       }
4764     }
4765   }
4766 
4767   // For method pool in the module, if it contains an entry for a selector,
4768   // the entry should be complete, containing everything introduced by that
4769   // module and all modules it imports. It's possible that the entry is out of
4770   // date, so we need to pull in the new content here.
4771 
4772   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4773   // safe, we copy all selectors out.
4774   llvm::SmallVector<Selector, 256> AllSelectors;
4775   for (auto &SelectorAndID : SelectorIDs)
4776     AllSelectors.push_back(SelectorAndID.first);
4777   for (auto &Selector : AllSelectors)
4778     SemaRef.updateOutOfDateSelector(Selector);
4779 
4780   // Form the record of special types.
4781   RecordData SpecialTypes;
4782   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4783   AddTypeRef(Context.getFILEType(), SpecialTypes);
4784   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4785   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4786   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4787   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4788   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4789   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4790 
4791   if (Chain) {
4792     // Write the mapping information describing our module dependencies and how
4793     // each of those modules were mapped into our own offset/ID space, so that
4794     // the reader can build the appropriate mapping to its own offset/ID space.
4795     // The map consists solely of a blob with the following format:
4796     // *(module-kind:i8
4797     //   module-name-len:i16 module-name:len*i8
4798     //   source-location-offset:i32
4799     //   identifier-id:i32
4800     //   preprocessed-entity-id:i32
4801     //   macro-definition-id:i32
4802     //   submodule-id:i32
4803     //   selector-id:i32
4804     //   declaration-id:i32
4805     //   c++-base-specifiers-id:i32
4806     //   type-id:i32)
4807     //
4808     // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4809     // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4810     // it is the module file name.
4811     //
4812     auto Abbrev = std::make_shared<BitCodeAbbrev>();
4813     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4814     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4815     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4816     SmallString<2048> Buffer;
4817     {
4818       llvm::raw_svector_ostream Out(Buffer);
4819       for (ModuleFile &M : Chain->ModuleMgr) {
4820         using namespace llvm::support;
4821         endian::Writer<little> LE(Out);
4822         LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4823         StringRef Name =
4824           M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4825           ? M.ModuleName
4826           : M.FileName;
4827         LE.write<uint16_t>(Name.size());
4828         Out.write(Name.data(), Name.size());
4829 
4830         // Note: if a base ID was uint max, it would not be possible to load
4831         // another module after it or have more than one entity inside it.
4832         uint32_t None = std::numeric_limits<uint32_t>::max();
4833 
4834         auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4835           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4836           if (ShouldWrite)
4837             LE.write<uint32_t>(BaseID);
4838           else
4839             LE.write<uint32_t>(None);
4840         };
4841 
4842         // These values should be unique within a chain, since they will be read
4843         // as keys into ContinuousRangeMaps.
4844         writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4845         writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4846         writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4847         writeBaseIDOrNone(M.BasePreprocessedEntityID,
4848                           M.NumPreprocessedEntities);
4849         writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4850         writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4851         writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4852         writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4853       }
4854     }
4855     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4856     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4857                               Buffer.data(), Buffer.size());
4858   }
4859 
4860   RecordData DeclUpdatesOffsetsRecord;
4861 
4862   // Keep writing types, declarations, and declaration update records
4863   // until we've emitted all of them.
4864   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4865   WriteTypeAbbrevs();
4866   WriteDeclAbbrevs();
4867   do {
4868     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4869     while (!DeclTypesToEmit.empty()) {
4870       DeclOrType DOT = DeclTypesToEmit.front();
4871       DeclTypesToEmit.pop();
4872       if (DOT.isType())
4873         WriteType(DOT.getType());
4874       else
4875         WriteDecl(Context, DOT.getDecl());
4876     }
4877   } while (!DeclUpdates.empty());
4878   Stream.ExitBlock();
4879 
4880   DoneWritingDeclsAndTypes = true;
4881 
4882   // These things can only be done once we've written out decls and types.
4883   WriteTypeDeclOffsets();
4884   if (!DeclUpdatesOffsetsRecord.empty())
4885     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4886   WriteFileDeclIDsMap();
4887   WriteSourceManagerBlock(Context.getSourceManager(), PP);
4888   WriteComments();
4889   WritePreprocessor(PP, isModule);
4890   WriteHeaderSearch(PP.getHeaderSearchInfo());
4891   WriteSelectors(SemaRef);
4892   WriteReferencedSelectorsPool(SemaRef);
4893   WriteLateParsedTemplates(SemaRef);
4894   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4895   WriteFPPragmaOptions(SemaRef.getFPOptions());
4896   WriteOpenCLExtensions(SemaRef);
4897   WriteOpenCLExtensionTypes(SemaRef);
4898   WriteOpenCLExtensionDecls(SemaRef);
4899   WriteCUDAPragmas(SemaRef);
4900 
4901   // If we're emitting a module, write out the submodule information.
4902   if (WritingModule)
4903     WriteSubmodules(WritingModule);
4904 
4905   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4906 
4907   // Write the record containing external, unnamed definitions.
4908   if (!EagerlyDeserializedDecls.empty())
4909     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4910 
4911   if (!ModularCodegenDecls.empty())
4912     Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4913 
4914   // Write the record containing tentative definitions.
4915   if (!TentativeDefinitions.empty())
4916     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4917 
4918   // Write the record containing unused file scoped decls.
4919   if (!UnusedFileScopedDecls.empty())
4920     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4921 
4922   // Write the record containing weak undeclared identifiers.
4923   if (!WeakUndeclaredIdentifiers.empty())
4924     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4925                       WeakUndeclaredIdentifiers);
4926 
4927   // Write the record containing ext_vector type names.
4928   if (!ExtVectorDecls.empty())
4929     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4930 
4931   // Write the record containing VTable uses information.
4932   if (!VTableUses.empty())
4933     Stream.EmitRecord(VTABLE_USES, VTableUses);
4934 
4935   // Write the record containing potentially unused local typedefs.
4936   if (!UnusedLocalTypedefNameCandidates.empty())
4937     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4938                       UnusedLocalTypedefNameCandidates);
4939 
4940   // Write the record containing pending implicit instantiations.
4941   if (!PendingInstantiations.empty())
4942     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4943 
4944   // Write the record containing declaration references of Sema.
4945   if (!SemaDeclRefs.empty())
4946     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4947 
4948   // Write the record containing CUDA-specific declaration references.
4949   if (!CUDASpecialDeclRefs.empty())
4950     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4951 
4952   // Write the delegating constructors.
4953   if (!DelegatingCtorDecls.empty())
4954     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4955 
4956   // Write the known namespaces.
4957   if (!KnownNamespaces.empty())
4958     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4959 
4960   // Write the undefined internal functions and variables, and inline functions.
4961   if (!UndefinedButUsed.empty())
4962     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4963 
4964   if (!DeleteExprsToAnalyze.empty())
4965     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4966 
4967   // Write the visible updates to DeclContexts.
4968   for (auto *DC : UpdatedDeclContexts)
4969     WriteDeclContextVisibleUpdate(DC);
4970 
4971   if (!WritingModule) {
4972     // Write the submodules that were imported, if any.
4973     struct ModuleInfo {
4974       uint64_t ID;
4975       Module *M;
4976       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4977     };
4978     llvm::SmallVector<ModuleInfo, 64> Imports;
4979     for (const auto *I : Context.local_imports()) {
4980       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4981       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4982                          I->getImportedModule()));
4983     }
4984 
4985     if (!Imports.empty()) {
4986       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4987         return A.ID < B.ID;
4988       };
4989       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4990         return A.ID == B.ID;
4991       };
4992 
4993       // Sort and deduplicate module IDs.
4994       std::sort(Imports.begin(), Imports.end(), Cmp);
4995       Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4996                     Imports.end());
4997 
4998       RecordData ImportedModules;
4999       for (const auto &Import : Imports) {
5000         ImportedModules.push_back(Import.ID);
5001         // FIXME: If the module has macros imported then later has declarations
5002         // imported, this location won't be the right one as a location for the
5003         // declaration imports.
5004         AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5005       }
5006 
5007       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5008     }
5009   }
5010 
5011   WriteObjCCategories();
5012   if(!WritingModule) {
5013     WriteOptimizePragmaOptions(SemaRef);
5014     WriteMSStructPragmaOptions(SemaRef);
5015     WriteMSPointersToMembersPragmaOptions(SemaRef);
5016   }
5017   WritePackPragmaOptions(SemaRef);
5018 
5019   // Some simple statistics
5020   RecordData::value_type Record[] = {
5021       NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5022   Stream.EmitRecord(STATISTICS, Record);
5023   Stream.ExitBlock();
5024 
5025   // Write the module file extension blocks.
5026   for (const auto &ExtWriter : ModuleFileExtensionWriters)
5027     WriteModuleFileExtension(SemaRef, *ExtWriter);
5028 
5029   return writeUnhashedControlBlock(PP, Context);
5030 }
5031 
5032 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5033   if (DeclUpdates.empty())
5034     return;
5035 
5036   DeclUpdateMap LocalUpdates;
5037   LocalUpdates.swap(DeclUpdates);
5038 
5039   for (auto &DeclUpdate : LocalUpdates) {
5040     const Decl *D = DeclUpdate.first;
5041 
5042     bool HasUpdatedBody = false;
5043     RecordData RecordData;
5044     ASTRecordWriter Record(*this, RecordData);
5045     for (auto &Update : DeclUpdate.second) {
5046       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5047 
5048       // An updated body is emitted last, so that the reader doesn't need
5049       // to skip over the lazy body to reach statements for other records.
5050       if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5051         HasUpdatedBody = true;
5052       else
5053         Record.push_back(Kind);
5054 
5055       switch (Kind) {
5056       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5057       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5058       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
5059         assert(Update.getDecl() && "no decl to add?");
5060         Record.push_back(GetDeclRef(Update.getDecl()));
5061         break;
5062 
5063       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
5064         break;
5065 
5066       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: {
5067         const VarDecl *VD = cast<VarDecl>(D);
5068         Record.AddSourceLocation(Update.getLoc());
5069         if (VD->getInit()) {
5070           Record.push_back(!VD->isInitKnownICE() ? 1
5071                                                  : (VD->isInitICE() ? 3 : 2));
5072           Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5073         } else {
5074           Record.push_back(0);
5075         }
5076         break;
5077       }
5078 
5079       case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
5080         Record.AddStmt(const_cast<Expr *>(
5081             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5082         break;
5083 
5084       case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5085         Record.AddStmt(
5086             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5087         break;
5088 
5089       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5090         auto *RD = cast<CXXRecordDecl>(D);
5091         UpdatedDeclContexts.insert(RD->getPrimaryContext());
5092         Record.AddCXXDefinitionData(RD);
5093         Record.AddOffset(WriteDeclContextLexicalBlock(
5094             *Context, const_cast<CXXRecordDecl *>(RD)));
5095 
5096         // This state is sometimes updated by template instantiation, when we
5097         // switch from the specialization referring to the template declaration
5098         // to it referring to the template definition.
5099         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5100           Record.push_back(MSInfo->getTemplateSpecializationKind());
5101           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5102         } else {
5103           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5104           Record.push_back(Spec->getTemplateSpecializationKind());
5105           Record.AddSourceLocation(Spec->getPointOfInstantiation());
5106 
5107           // The instantiation might have been resolved to a partial
5108           // specialization. If so, record which one.
5109           auto From = Spec->getInstantiatedFrom();
5110           if (auto PartialSpec =
5111                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5112             Record.push_back(true);
5113             Record.AddDeclRef(PartialSpec);
5114             Record.AddTemplateArgumentList(
5115                 &Spec->getTemplateInstantiationArgs());
5116           } else {
5117             Record.push_back(false);
5118           }
5119         }
5120         Record.push_back(RD->getTagKind());
5121         Record.AddSourceLocation(RD->getLocation());
5122         Record.AddSourceLocation(RD->getLocStart());
5123         Record.AddSourceRange(RD->getBraceRange());
5124 
5125         // Instantiation may change attributes; write them all out afresh.
5126         Record.push_back(D->hasAttrs());
5127         if (D->hasAttrs())
5128           Record.AddAttributes(D->getAttrs());
5129 
5130         // FIXME: Ensure we don't get here for explicit instantiations.
5131         break;
5132       }
5133 
5134       case UPD_CXX_RESOLVED_DTOR_DELETE:
5135         Record.AddDeclRef(Update.getDecl());
5136         break;
5137 
5138       case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5139         addExceptionSpec(
5140             cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5141             Record);
5142         break;
5143 
5144       case UPD_CXX_DEDUCED_RETURN_TYPE:
5145         Record.push_back(GetOrCreateTypeID(Update.getType()));
5146         break;
5147 
5148       case UPD_DECL_MARKED_USED:
5149         break;
5150 
5151       case UPD_MANGLING_NUMBER:
5152       case UPD_STATIC_LOCAL_NUMBER:
5153         Record.push_back(Update.getNumber());
5154         break;
5155 
5156       case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5157         Record.AddSourceRange(
5158             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5159         break;
5160 
5161       case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5162         Record.AddSourceRange(
5163             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5164         break;
5165 
5166       case UPD_DECL_EXPORTED:
5167         Record.push_back(getSubmoduleID(Update.getModule()));
5168         break;
5169 
5170       case UPD_ADDED_ATTR_TO_RECORD:
5171         Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5172         break;
5173       }
5174     }
5175 
5176     if (HasUpdatedBody) {
5177       const auto *Def = cast<FunctionDecl>(D);
5178       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5179       Record.push_back(Def->isInlined());
5180       Record.AddSourceLocation(Def->getInnerLocStart());
5181       Record.AddFunctionDefinition(Def);
5182     }
5183 
5184     OffsetsRecord.push_back(GetDeclRef(D));
5185     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5186   }
5187 }
5188 
5189 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5190   uint32_t Raw = Loc.getRawEncoding();
5191   Record.push_back((Raw << 1) | (Raw >> 31));
5192 }
5193 
5194 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5195   AddSourceLocation(Range.getBegin(), Record);
5196   AddSourceLocation(Range.getEnd(), Record);
5197 }
5198 
5199 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5200   Record->push_back(Value.getBitWidth());
5201   const uint64_t *Words = Value.getRawData();
5202   Record->append(Words, Words + Value.getNumWords());
5203 }
5204 
5205 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5206   Record->push_back(Value.isUnsigned());
5207   AddAPInt(Value);
5208 }
5209 
5210 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5211   AddAPInt(Value.bitcastToAPInt());
5212 }
5213 
5214 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5215   Record.push_back(getIdentifierRef(II));
5216 }
5217 
5218 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5219   if (!II)
5220     return 0;
5221 
5222   IdentID &ID = IdentifierIDs[II];
5223   if (ID == 0)
5224     ID = NextIdentID++;
5225   return ID;
5226 }
5227 
5228 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5229   // Don't emit builtin macros like __LINE__ to the AST file unless they
5230   // have been redefined by the header (in which case they are not
5231   // isBuiltinMacro).
5232   if (!MI || MI->isBuiltinMacro())
5233     return 0;
5234 
5235   MacroID &ID = MacroIDs[MI];
5236   if (ID == 0) {
5237     ID = NextMacroID++;
5238     MacroInfoToEmitData Info = { Name, MI, ID };
5239     MacroInfosToEmit.push_back(Info);
5240   }
5241   return ID;
5242 }
5243 
5244 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5245   if (!MI || MI->isBuiltinMacro())
5246     return 0;
5247 
5248   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5249   return MacroIDs[MI];
5250 }
5251 
5252 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5253   return IdentMacroDirectivesOffsetMap.lookup(Name);
5254 }
5255 
5256 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5257   Record->push_back(Writer->getSelectorRef(SelRef));
5258 }
5259 
5260 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5261   if (Sel.getAsOpaquePtr() == nullptr) {
5262     return 0;
5263   }
5264 
5265   SelectorID SID = SelectorIDs[Sel];
5266   if (SID == 0 && Chain) {
5267     // This might trigger a ReadSelector callback, which will set the ID for
5268     // this selector.
5269     Chain->LoadSelector(Sel);
5270     SID = SelectorIDs[Sel];
5271   }
5272   if (SID == 0) {
5273     SID = NextSelectorID++;
5274     SelectorIDs[Sel] = SID;
5275   }
5276   return SID;
5277 }
5278 
5279 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5280   AddDeclRef(Temp->getDestructor());
5281 }
5282 
5283 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5284     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5285   switch (Kind) {
5286   case TemplateArgument::Expression:
5287     AddStmt(Arg.getAsExpr());
5288     break;
5289   case TemplateArgument::Type:
5290     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5291     break;
5292   case TemplateArgument::Template:
5293     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5294     AddSourceLocation(Arg.getTemplateNameLoc());
5295     break;
5296   case TemplateArgument::TemplateExpansion:
5297     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5298     AddSourceLocation(Arg.getTemplateNameLoc());
5299     AddSourceLocation(Arg.getTemplateEllipsisLoc());
5300     break;
5301   case TemplateArgument::Null:
5302   case TemplateArgument::Integral:
5303   case TemplateArgument::Declaration:
5304   case TemplateArgument::NullPtr:
5305   case TemplateArgument::Pack:
5306     // FIXME: Is this right?
5307     break;
5308   }
5309 }
5310 
5311 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5312   AddTemplateArgument(Arg.getArgument());
5313 
5314   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5315     bool InfoHasSameExpr
5316       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5317     Record->push_back(InfoHasSameExpr);
5318     if (InfoHasSameExpr)
5319       return; // Avoid storing the same expr twice.
5320   }
5321   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5322 }
5323 
5324 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5325   if (!TInfo) {
5326     AddTypeRef(QualType());
5327     return;
5328   }
5329 
5330   AddTypeLoc(TInfo->getTypeLoc());
5331 }
5332 
5333 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5334   AddTypeRef(TL.getType());
5335 
5336   TypeLocWriter TLW(*this);
5337   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5338     TLW.Visit(TL);
5339 }
5340 
5341 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5342   Record.push_back(GetOrCreateTypeID(T));
5343 }
5344 
5345 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5346   assert(Context);
5347   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5348     if (T.isNull())
5349       return TypeIdx();
5350     assert(!T.getLocalFastQualifiers());
5351 
5352     TypeIdx &Idx = TypeIdxs[T];
5353     if (Idx.getIndex() == 0) {
5354       if (DoneWritingDeclsAndTypes) {
5355         assert(0 && "New type seen after serializing all the types to emit!");
5356         return TypeIdx();
5357       }
5358 
5359       // We haven't seen this type before. Assign it a new ID and put it
5360       // into the queue of types to emit.
5361       Idx = TypeIdx(NextTypeID++);
5362       DeclTypesToEmit.push(T);
5363     }
5364     return Idx;
5365   });
5366 }
5367 
5368 TypeID ASTWriter::getTypeID(QualType T) const {
5369   assert(Context);
5370   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5371     if (T.isNull())
5372       return TypeIdx();
5373     assert(!T.getLocalFastQualifiers());
5374 
5375     TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5376     assert(I != TypeIdxs.end() && "Type not emitted!");
5377     return I->second;
5378   });
5379 }
5380 
5381 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5382   Record.push_back(GetDeclRef(D));
5383 }
5384 
5385 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5386   assert(WritingAST && "Cannot request a declaration ID before AST writing");
5387 
5388   if (!D) {
5389     return 0;
5390   }
5391 
5392   // If D comes from an AST file, its declaration ID is already known and
5393   // fixed.
5394   if (D->isFromASTFile())
5395     return D->getGlobalID();
5396 
5397   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5398   DeclID &ID = DeclIDs[D];
5399   if (ID == 0) {
5400     if (DoneWritingDeclsAndTypes) {
5401       assert(0 && "New decl seen after serializing all the decls to emit!");
5402       return 0;
5403     }
5404 
5405     // We haven't seen this declaration before. Give it a new ID and
5406     // enqueue it in the list of declarations to emit.
5407     ID = NextDeclID++;
5408     DeclTypesToEmit.push(const_cast<Decl *>(D));
5409   }
5410 
5411   return ID;
5412 }
5413 
5414 DeclID ASTWriter::getDeclID(const Decl *D) {
5415   if (!D)
5416     return 0;
5417 
5418   // If D comes from an AST file, its declaration ID is already known and
5419   // fixed.
5420   if (D->isFromASTFile())
5421     return D->getGlobalID();
5422 
5423   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5424   return DeclIDs[D];
5425 }
5426 
5427 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5428   assert(ID);
5429   assert(D);
5430 
5431   SourceLocation Loc = D->getLocation();
5432   if (Loc.isInvalid())
5433     return;
5434 
5435   // We only keep track of the file-level declarations of each file.
5436   if (!D->getLexicalDeclContext()->isFileContext())
5437     return;
5438   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5439   // a function/objc method, should not have TU as lexical context.
5440   if (isa<ParmVarDecl>(D))
5441     return;
5442 
5443   SourceManager &SM = Context->getSourceManager();
5444   SourceLocation FileLoc = SM.getFileLoc(Loc);
5445   assert(SM.isLocalSourceLocation(FileLoc));
5446   FileID FID;
5447   unsigned Offset;
5448   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5449   if (FID.isInvalid())
5450     return;
5451   assert(SM.getSLocEntry(FID).isFile());
5452 
5453   DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5454   if (!Info)
5455     Info = new DeclIDInFileInfo();
5456 
5457   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5458   LocDeclIDsTy &Decls = Info->DeclIDs;
5459 
5460   if (Decls.empty() || Decls.back().first <= Offset) {
5461     Decls.push_back(LocDecl);
5462     return;
5463   }
5464 
5465   LocDeclIDsTy::iterator I =
5466       std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5467 
5468   Decls.insert(I, LocDecl);
5469 }
5470 
5471 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
5472   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
5473   Record->push_back(Name.getNameKind());
5474   switch (Name.getNameKind()) {
5475   case DeclarationName::Identifier:
5476     AddIdentifierRef(Name.getAsIdentifierInfo());
5477     break;
5478 
5479   case DeclarationName::ObjCZeroArgSelector:
5480   case DeclarationName::ObjCOneArgSelector:
5481   case DeclarationName::ObjCMultiArgSelector:
5482     AddSelectorRef(Name.getObjCSelector());
5483     break;
5484 
5485   case DeclarationName::CXXConstructorName:
5486   case DeclarationName::CXXDestructorName:
5487   case DeclarationName::CXXConversionFunctionName:
5488     AddTypeRef(Name.getCXXNameType());
5489     break;
5490 
5491   case DeclarationName::CXXDeductionGuideName:
5492     AddDeclRef(Name.getCXXDeductionGuideTemplate());
5493     break;
5494 
5495   case DeclarationName::CXXOperatorName:
5496     Record->push_back(Name.getCXXOverloadedOperator());
5497     break;
5498 
5499   case DeclarationName::CXXLiteralOperatorName:
5500     AddIdentifierRef(Name.getCXXLiteralIdentifier());
5501     break;
5502 
5503   case DeclarationName::CXXUsingDirective:
5504     // No extra data to emit
5505     break;
5506   }
5507 }
5508 
5509 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5510   assert(needsAnonymousDeclarationNumber(D) &&
5511          "expected an anonymous declaration");
5512 
5513   // Number the anonymous declarations within this context, if we've not
5514   // already done so.
5515   auto It = AnonymousDeclarationNumbers.find(D);
5516   if (It == AnonymousDeclarationNumbers.end()) {
5517     auto *DC = D->getLexicalDeclContext();
5518     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5519       AnonymousDeclarationNumbers[ND] = Number;
5520     });
5521 
5522     It = AnonymousDeclarationNumbers.find(D);
5523     assert(It != AnonymousDeclarationNumbers.end() &&
5524            "declaration not found within its lexical context");
5525   }
5526 
5527   return It->second;
5528 }
5529 
5530 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5531                                             DeclarationName Name) {
5532   switch (Name.getNameKind()) {
5533   case DeclarationName::CXXConstructorName:
5534   case DeclarationName::CXXDestructorName:
5535   case DeclarationName::CXXConversionFunctionName:
5536     AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5537     break;
5538 
5539   case DeclarationName::CXXOperatorName:
5540     AddSourceLocation(SourceLocation::getFromRawEncoding(
5541         DNLoc.CXXOperatorName.BeginOpNameLoc));
5542     AddSourceLocation(
5543         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5544     break;
5545 
5546   case DeclarationName::CXXLiteralOperatorName:
5547     AddSourceLocation(SourceLocation::getFromRawEncoding(
5548         DNLoc.CXXLiteralOperatorName.OpNameLoc));
5549     break;
5550 
5551   case DeclarationName::Identifier:
5552   case DeclarationName::ObjCZeroArgSelector:
5553   case DeclarationName::ObjCOneArgSelector:
5554   case DeclarationName::ObjCMultiArgSelector:
5555   case DeclarationName::CXXUsingDirective:
5556   case DeclarationName::CXXDeductionGuideName:
5557     break;
5558   }
5559 }
5560 
5561 void ASTRecordWriter::AddDeclarationNameInfo(
5562     const DeclarationNameInfo &NameInfo) {
5563   AddDeclarationName(NameInfo.getName());
5564   AddSourceLocation(NameInfo.getLoc());
5565   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5566 }
5567 
5568 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5569   AddNestedNameSpecifierLoc(Info.QualifierLoc);
5570   Record->push_back(Info.NumTemplParamLists);
5571   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5572     AddTemplateParameterList(Info.TemplParamLists[i]);
5573 }
5574 
5575 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
5576   // Nested name specifiers usually aren't too long. I think that 8 would
5577   // typically accommodate the vast majority.
5578   SmallVector<NestedNameSpecifier *, 8> NestedNames;
5579 
5580   // Push each of the NNS's onto a stack for serialization in reverse order.
5581   while (NNS) {
5582     NestedNames.push_back(NNS);
5583     NNS = NNS->getPrefix();
5584   }
5585 
5586   Record->push_back(NestedNames.size());
5587   while(!NestedNames.empty()) {
5588     NNS = NestedNames.pop_back_val();
5589     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5590     Record->push_back(Kind);
5591     switch (Kind) {
5592     case NestedNameSpecifier::Identifier:
5593       AddIdentifierRef(NNS->getAsIdentifier());
5594       break;
5595 
5596     case NestedNameSpecifier::Namespace:
5597       AddDeclRef(NNS->getAsNamespace());
5598       break;
5599 
5600     case NestedNameSpecifier::NamespaceAlias:
5601       AddDeclRef(NNS->getAsNamespaceAlias());
5602       break;
5603 
5604     case NestedNameSpecifier::TypeSpec:
5605     case NestedNameSpecifier::TypeSpecWithTemplate:
5606       AddTypeRef(QualType(NNS->getAsType(), 0));
5607       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5608       break;
5609 
5610     case NestedNameSpecifier::Global:
5611       // Don't need to write an associated value.
5612       break;
5613 
5614     case NestedNameSpecifier::Super:
5615       AddDeclRef(NNS->getAsRecordDecl());
5616       break;
5617     }
5618   }
5619 }
5620 
5621 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5622   // Nested name specifiers usually aren't too long. I think that 8 would
5623   // typically accommodate the vast majority.
5624   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5625 
5626   // Push each of the nested-name-specifiers's onto a stack for
5627   // serialization in reverse order.
5628   while (NNS) {
5629     NestedNames.push_back(NNS);
5630     NNS = NNS.getPrefix();
5631   }
5632 
5633   Record->push_back(NestedNames.size());
5634   while(!NestedNames.empty()) {
5635     NNS = NestedNames.pop_back_val();
5636     NestedNameSpecifier::SpecifierKind Kind
5637       = NNS.getNestedNameSpecifier()->getKind();
5638     Record->push_back(Kind);
5639     switch (Kind) {
5640     case NestedNameSpecifier::Identifier:
5641       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5642       AddSourceRange(NNS.getLocalSourceRange());
5643       break;
5644 
5645     case NestedNameSpecifier::Namespace:
5646       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5647       AddSourceRange(NNS.getLocalSourceRange());
5648       break;
5649 
5650     case NestedNameSpecifier::NamespaceAlias:
5651       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5652       AddSourceRange(NNS.getLocalSourceRange());
5653       break;
5654 
5655     case NestedNameSpecifier::TypeSpec:
5656     case NestedNameSpecifier::TypeSpecWithTemplate:
5657       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5658       AddTypeLoc(NNS.getTypeLoc());
5659       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5660       break;
5661 
5662     case NestedNameSpecifier::Global:
5663       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5664       break;
5665 
5666     case NestedNameSpecifier::Super:
5667       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5668       AddSourceRange(NNS.getLocalSourceRange());
5669       break;
5670     }
5671   }
5672 }
5673 
5674 void ASTRecordWriter::AddTemplateName(TemplateName Name) {
5675   TemplateName::NameKind Kind = Name.getKind();
5676   Record->push_back(Kind);
5677   switch (Kind) {
5678   case TemplateName::Template:
5679     AddDeclRef(Name.getAsTemplateDecl());
5680     break;
5681 
5682   case TemplateName::OverloadedTemplate: {
5683     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5684     Record->push_back(OvT->size());
5685     for (const auto &I : *OvT)
5686       AddDeclRef(I);
5687     break;
5688   }
5689 
5690   case TemplateName::QualifiedTemplate: {
5691     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5692     AddNestedNameSpecifier(QualT->getQualifier());
5693     Record->push_back(QualT->hasTemplateKeyword());
5694     AddDeclRef(QualT->getTemplateDecl());
5695     break;
5696   }
5697 
5698   case TemplateName::DependentTemplate: {
5699     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5700     AddNestedNameSpecifier(DepT->getQualifier());
5701     Record->push_back(DepT->isIdentifier());
5702     if (DepT->isIdentifier())
5703       AddIdentifierRef(DepT->getIdentifier());
5704     else
5705       Record->push_back(DepT->getOperator());
5706     break;
5707   }
5708 
5709   case TemplateName::SubstTemplateTemplateParm: {
5710     SubstTemplateTemplateParmStorage *subst
5711       = Name.getAsSubstTemplateTemplateParm();
5712     AddDeclRef(subst->getParameter());
5713     AddTemplateName(subst->getReplacement());
5714     break;
5715   }
5716 
5717   case TemplateName::SubstTemplateTemplateParmPack: {
5718     SubstTemplateTemplateParmPackStorage *SubstPack
5719       = Name.getAsSubstTemplateTemplateParmPack();
5720     AddDeclRef(SubstPack->getParameterPack());
5721     AddTemplateArgument(SubstPack->getArgumentPack());
5722     break;
5723   }
5724   }
5725 }
5726 
5727 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5728   Record->push_back(Arg.getKind());
5729   switch (Arg.getKind()) {
5730   case TemplateArgument::Null:
5731     break;
5732   case TemplateArgument::Type:
5733     AddTypeRef(Arg.getAsType());
5734     break;
5735   case TemplateArgument::Declaration:
5736     AddDeclRef(Arg.getAsDecl());
5737     AddTypeRef(Arg.getParamTypeForDecl());
5738     break;
5739   case TemplateArgument::NullPtr:
5740     AddTypeRef(Arg.getNullPtrType());
5741     break;
5742   case TemplateArgument::Integral:
5743     AddAPSInt(Arg.getAsIntegral());
5744     AddTypeRef(Arg.getIntegralType());
5745     break;
5746   case TemplateArgument::Template:
5747     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5748     break;
5749   case TemplateArgument::TemplateExpansion:
5750     AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
5751     if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5752       Record->push_back(*NumExpansions + 1);
5753     else
5754       Record->push_back(0);
5755     break;
5756   case TemplateArgument::Expression:
5757     AddStmt(Arg.getAsExpr());
5758     break;
5759   case TemplateArgument::Pack:
5760     Record->push_back(Arg.pack_size());
5761     for (const auto &P : Arg.pack_elements())
5762       AddTemplateArgument(P);
5763     break;
5764   }
5765 }
5766 
5767 void ASTRecordWriter::AddTemplateParameterList(
5768     const TemplateParameterList *TemplateParams) {
5769   assert(TemplateParams && "No TemplateParams!");
5770   AddSourceLocation(TemplateParams->getTemplateLoc());
5771   AddSourceLocation(TemplateParams->getLAngleLoc());
5772   AddSourceLocation(TemplateParams->getRAngleLoc());
5773   // TODO: Concepts
5774   Record->push_back(TemplateParams->size());
5775   for (const auto &P : *TemplateParams)
5776     AddDeclRef(P);
5777 }
5778 
5779 /// \brief Emit a template argument list.
5780 void ASTRecordWriter::AddTemplateArgumentList(
5781     const TemplateArgumentList *TemplateArgs) {
5782   assert(TemplateArgs && "No TemplateArgs!");
5783   Record->push_back(TemplateArgs->size());
5784   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5785     AddTemplateArgument(TemplateArgs->get(i));
5786 }
5787 
5788 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5789     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5790   assert(ASTTemplArgList && "No ASTTemplArgList!");
5791   AddSourceLocation(ASTTemplArgList->LAngleLoc);
5792   AddSourceLocation(ASTTemplArgList->RAngleLoc);
5793   Record->push_back(ASTTemplArgList->NumTemplateArgs);
5794   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5795   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5796     AddTemplateArgumentLoc(TemplArgs[i]);
5797 }
5798 
5799 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5800   Record->push_back(Set.size());
5801   for (ASTUnresolvedSet::const_iterator
5802          I = Set.begin(), E = Set.end(); I != E; ++I) {
5803     AddDeclRef(I.getDecl());
5804     Record->push_back(I.getAccess());
5805   }
5806 }
5807 
5808 // FIXME: Move this out of the main ASTRecordWriter interface.
5809 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5810   Record->push_back(Base.isVirtual());
5811   Record->push_back(Base.isBaseOfClass());
5812   Record->push_back(Base.getAccessSpecifierAsWritten());
5813   Record->push_back(Base.getInheritConstructors());
5814   AddTypeSourceInfo(Base.getTypeSourceInfo());
5815   AddSourceRange(Base.getSourceRange());
5816   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5817                                           : SourceLocation());
5818 }
5819 
5820 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5821                                       ArrayRef<CXXBaseSpecifier> Bases) {
5822   ASTWriter::RecordData Record;
5823   ASTRecordWriter Writer(W, Record);
5824   Writer.push_back(Bases.size());
5825 
5826   for (auto &Base : Bases)
5827     Writer.AddCXXBaseSpecifier(Base);
5828 
5829   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5830 }
5831 
5832 // FIXME: Move this out of the main ASTRecordWriter interface.
5833 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5834   AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5835 }
5836 
5837 static uint64_t
5838 EmitCXXCtorInitializers(ASTWriter &W,
5839                         ArrayRef<CXXCtorInitializer *> CtorInits) {
5840   ASTWriter::RecordData Record;
5841   ASTRecordWriter Writer(W, Record);
5842   Writer.push_back(CtorInits.size());
5843 
5844   for (auto *Init : CtorInits) {
5845     if (Init->isBaseInitializer()) {
5846       Writer.push_back(CTOR_INITIALIZER_BASE);
5847       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5848       Writer.push_back(Init->isBaseVirtual());
5849     } else if (Init->isDelegatingInitializer()) {
5850       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5851       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5852     } else if (Init->isMemberInitializer()){
5853       Writer.push_back(CTOR_INITIALIZER_MEMBER);
5854       Writer.AddDeclRef(Init->getMember());
5855     } else {
5856       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5857       Writer.AddDeclRef(Init->getIndirectMember());
5858     }
5859 
5860     Writer.AddSourceLocation(Init->getMemberLocation());
5861     Writer.AddStmt(Init->getInit());
5862     Writer.AddSourceLocation(Init->getLParenLoc());
5863     Writer.AddSourceLocation(Init->getRParenLoc());
5864     Writer.push_back(Init->isWritten());
5865     if (Init->isWritten())
5866       Writer.push_back(Init->getSourceOrder());
5867   }
5868 
5869   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5870 }
5871 
5872 // FIXME: Move this out of the main ASTRecordWriter interface.
5873 void ASTRecordWriter::AddCXXCtorInitializers(
5874     ArrayRef<CXXCtorInitializer *> CtorInits) {
5875   AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5876 }
5877 
5878 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5879   auto &Data = D->data();
5880   Record->push_back(Data.IsLambda);
5881   Record->push_back(Data.UserDeclaredConstructor);
5882   Record->push_back(Data.UserDeclaredSpecialMembers);
5883   Record->push_back(Data.Aggregate);
5884   Record->push_back(Data.PlainOldData);
5885   Record->push_back(Data.Empty);
5886   Record->push_back(Data.Polymorphic);
5887   Record->push_back(Data.Abstract);
5888   Record->push_back(Data.IsStandardLayout);
5889   Record->push_back(Data.HasNoNonEmptyBases);
5890   Record->push_back(Data.HasPrivateFields);
5891   Record->push_back(Data.HasProtectedFields);
5892   Record->push_back(Data.HasPublicFields);
5893   Record->push_back(Data.HasMutableFields);
5894   Record->push_back(Data.HasVariantMembers);
5895   Record->push_back(Data.HasOnlyCMembers);
5896   Record->push_back(Data.HasInClassInitializer);
5897   Record->push_back(Data.HasUninitializedReferenceMember);
5898   Record->push_back(Data.HasUninitializedFields);
5899   Record->push_back(Data.HasInheritedConstructor);
5900   Record->push_back(Data.HasInheritedAssignment);
5901   Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
5902   Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5903   Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5904   Record->push_back(Data.NeedOverloadResolutionForDestructor);
5905   Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
5906   Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5907   Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5908   Record->push_back(Data.DefaultedDestructorIsDeleted);
5909   Record->push_back(Data.HasTrivialSpecialMembers);
5910   Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5911   Record->push_back(Data.HasIrrelevantDestructor);
5912   Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5913   Record->push_back(Data.HasDefaultedDefaultConstructor);
5914   Record->push_back(Data.CanPassInRegisters);
5915   Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5916   Record->push_back(Data.HasConstexprDefaultConstructor);
5917   Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5918   Record->push_back(Data.ComputedVisibleConversions);
5919   Record->push_back(Data.UserProvidedDefaultConstructor);
5920   Record->push_back(Data.DeclaredSpecialMembers);
5921   Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
5922   Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
5923   Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5924   Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5925   Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5926 
5927   // getODRHash will compute the ODRHash if it has not been previously computed.
5928   Record->push_back(D->getODRHash());
5929   bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
5930                           Writer->WritingModule && !D->isDependentType();
5931   Record->push_back(ModulesDebugInfo);
5932   if (ModulesDebugInfo)
5933     Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5934 
5935   // IsLambda bit is already saved.
5936 
5937   Record->push_back(Data.NumBases);
5938   if (Data.NumBases > 0)
5939     AddCXXBaseSpecifiers(Data.bases());
5940 
5941   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5942   Record->push_back(Data.NumVBases);
5943   if (Data.NumVBases > 0)
5944     AddCXXBaseSpecifiers(Data.vbases());
5945 
5946   AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5947   AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5948   // Data.Definition is the owning decl, no need to write it.
5949   AddDeclRef(D->getFirstFriend());
5950 
5951   // Add lambda-specific data.
5952   if (Data.IsLambda) {
5953     auto &Lambda = D->getLambdaData();
5954     Record->push_back(Lambda.Dependent);
5955     Record->push_back(Lambda.IsGenericLambda);
5956     Record->push_back(Lambda.CaptureDefault);
5957     Record->push_back(Lambda.NumCaptures);
5958     Record->push_back(Lambda.NumExplicitCaptures);
5959     Record->push_back(Lambda.ManglingNumber);
5960     AddDeclRef(D->getLambdaContextDecl());
5961     AddTypeSourceInfo(Lambda.MethodTyInfo);
5962     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5963       const LambdaCapture &Capture = Lambda.Captures[I];
5964       AddSourceLocation(Capture.getLocation());
5965       Record->push_back(Capture.isImplicit());
5966       Record->push_back(Capture.getCaptureKind());
5967       switch (Capture.getCaptureKind()) {
5968       case LCK_StarThis:
5969       case LCK_This:
5970       case LCK_VLAType:
5971         break;
5972       case LCK_ByCopy:
5973       case LCK_ByRef:
5974         VarDecl *Var =
5975             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5976         AddDeclRef(Var);
5977         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5978                                                     : SourceLocation());
5979         break;
5980       }
5981     }
5982   }
5983 }
5984 
5985 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5986   assert(Reader && "Cannot remove chain");
5987   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5988   assert(FirstDeclID == NextDeclID &&
5989          FirstTypeID == NextTypeID &&
5990          FirstIdentID == NextIdentID &&
5991          FirstMacroID == NextMacroID &&
5992          FirstSubmoduleID == NextSubmoduleID &&
5993          FirstSelectorID == NextSelectorID &&
5994          "Setting chain after writing has started.");
5995 
5996   Chain = Reader;
5997 
5998   // Note, this will get called multiple times, once one the reader starts up
5999   // and again each time it's done reading a PCH or module.
6000   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6001   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6002   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
6003   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
6004   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
6005   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
6006   NextDeclID = FirstDeclID;
6007   NextTypeID = FirstTypeID;
6008   NextIdentID = FirstIdentID;
6009   NextMacroID = FirstMacroID;
6010   NextSelectorID = FirstSelectorID;
6011   NextSubmoduleID = FirstSubmoduleID;
6012 }
6013 
6014 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
6015   // Always keep the highest ID. See \p TypeRead() for more information.
6016   IdentID &StoredID = IdentifierIDs[II];
6017   if (ID > StoredID)
6018     StoredID = ID;
6019 }
6020 
6021 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
6022   // Always keep the highest ID. See \p TypeRead() for more information.
6023   MacroID &StoredID = MacroIDs[MI];
6024   if (ID > StoredID)
6025     StoredID = ID;
6026 }
6027 
6028 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
6029   // Always take the highest-numbered type index. This copes with an interesting
6030   // case for chained AST writing where we schedule writing the type and then,
6031   // later, deserialize the type from another AST. In this case, we want to
6032   // keep the higher-numbered entry so that we can properly write it out to
6033   // the AST file.
6034   TypeIdx &StoredIdx = TypeIdxs[T];
6035   if (Idx.getIndex() >= StoredIdx.getIndex())
6036     StoredIdx = Idx;
6037 }
6038 
6039 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
6040   // Always keep the highest ID. See \p TypeRead() for more information.
6041   SelectorID &StoredID = SelectorIDs[S];
6042   if (ID > StoredID)
6043     StoredID = ID;
6044 }
6045 
6046 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
6047                                     MacroDefinitionRecord *MD) {
6048   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
6049   MacroDefinitions[MD] = ID;
6050 }
6051 
6052 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6053   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
6054   SubmoduleIDs[Mod] = ID;
6055 }
6056 
6057 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
6058   if (Chain && Chain->isProcessingUpdateRecords()) return;
6059   assert(D->isCompleteDefinition());
6060   assert(!WritingAST && "Already writing the AST!");
6061   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6062     // We are interested when a PCH decl is modified.
6063     if (RD->isFromASTFile()) {
6064       // A forward reference was mutated into a definition. Rewrite it.
6065       // FIXME: This happens during template instantiation, should we
6066       // have created a new definition decl instead ?
6067       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6068              "completed a tag from another module but not by instantiation?");
6069       DeclUpdates[RD].push_back(
6070           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
6071     }
6072   }
6073 }
6074 
6075 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6076   if (D->isFromASTFile())
6077     return true;
6078 
6079   // The predefined __va_list_tag struct is imported if we imported any decls.
6080   // FIXME: This is a gross hack.
6081   return D == D->getASTContext().getVaListTagDecl();
6082 }
6083 
6084 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
6085   if (Chain && Chain->isProcessingUpdateRecords()) return;
6086   assert(DC->isLookupContext() &&
6087           "Should not add lookup results to non-lookup contexts!");
6088 
6089   // TU is handled elsewhere.
6090   if (isa<TranslationUnitDecl>(DC))
6091     return;
6092 
6093   // Namespaces are handled elsewhere, except for template instantiations of
6094   // FunctionTemplateDecls in namespaces. We are interested in cases where the
6095   // local instantiations are added to an imported context. Only happens when
6096   // adding ADL lookup candidates, for example templated friends.
6097   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6098       !isa<FunctionTemplateDecl>(D))
6099     return;
6100 
6101   // We're only interested in cases where a local declaration is added to an
6102   // imported context.
6103   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6104     return;
6105 
6106   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
6107   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
6108   assert(!WritingAST && "Already writing the AST!");
6109   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6110     // We're adding a visible declaration to a predefined decl context. Ensure
6111     // that we write out all of its lookup results so we don't get a nasty
6112     // surprise when we try to emit its lookup table.
6113     for (auto *Child : DC->decls())
6114       DeclsToEmitEvenIfUnreferenced.push_back(Child);
6115   }
6116   DeclsToEmitEvenIfUnreferenced.push_back(D);
6117 }
6118 
6119 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
6120   if (Chain && Chain->isProcessingUpdateRecords()) return;
6121   assert(D->isImplicit());
6122 
6123   // We're only interested in cases where a local declaration is added to an
6124   // imported context.
6125   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6126     return;
6127 
6128   if (!isa<CXXMethodDecl>(D))
6129     return;
6130 
6131   // A decl coming from PCH was modified.
6132   assert(RD->isCompleteDefinition());
6133   assert(!WritingAST && "Already writing the AST!");
6134   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
6135 }
6136 
6137 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
6138   if (Chain && Chain->isProcessingUpdateRecords()) return;
6139   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6140   if (!Chain) return;
6141   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6142     // If we don't already know the exception specification for this redecl
6143     // chain, add an update record for it.
6144     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6145                                       ->getType()
6146                                       ->castAs<FunctionProtoType>()
6147                                       ->getExceptionSpecType()))
6148       DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6149   });
6150 }
6151 
6152 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
6153   if (Chain && Chain->isProcessingUpdateRecords()) return;
6154   assert(!WritingAST && "Already writing the AST!");
6155   if (!Chain) return;
6156   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
6157     DeclUpdates[D].push_back(
6158         DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6159   });
6160 }
6161 
6162 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
6163                                        const FunctionDecl *Delete) {
6164   if (Chain && Chain->isProcessingUpdateRecords()) return;
6165   assert(!WritingAST && "Already writing the AST!");
6166   assert(Delete && "Not given an operator delete");
6167   if (!Chain) return;
6168   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
6169     DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6170   });
6171 }
6172 
6173 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
6174   if (Chain && Chain->isProcessingUpdateRecords()) return;
6175   assert(!WritingAST && "Already writing the AST!");
6176   if (!D->isFromASTFile())
6177     return; // Declaration not imported from PCH.
6178 
6179   // Implicit function decl from a PCH was defined.
6180   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6181 }
6182 
6183 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
6184   if (Chain && Chain->isProcessingUpdateRecords()) return;
6185   assert(!WritingAST && "Already writing the AST!");
6186   if (!D->isFromASTFile())
6187     return;
6188 
6189   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
6190 }
6191 
6192 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
6193   if (Chain && Chain->isProcessingUpdateRecords()) return;
6194   assert(!WritingAST && "Already writing the AST!");
6195   if (!D->isFromASTFile())
6196     return;
6197 
6198   // Since the actual instantiation is delayed, this really means that we need
6199   // to update the instantiation location.
6200   DeclUpdates[D].push_back(
6201       DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
6202        D->getMemberSpecializationInfo()->getPointOfInstantiation()));
6203 }
6204 
6205 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
6206   if (Chain && Chain->isProcessingUpdateRecords()) return;
6207   assert(!WritingAST && "Already writing the AST!");
6208   if (!D->isFromASTFile())
6209     return;
6210 
6211   DeclUpdates[D].push_back(
6212       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6213 }
6214 
6215 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6216   assert(!WritingAST && "Already writing the AST!");
6217   if (!D->isFromASTFile())
6218     return;
6219 
6220   DeclUpdates[D].push_back(
6221       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6222 }
6223 
6224 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6225                                              const ObjCInterfaceDecl *IFD) {
6226   if (Chain && Chain->isProcessingUpdateRecords()) return;
6227   assert(!WritingAST && "Already writing the AST!");
6228   if (!IFD->isFromASTFile())
6229     return; // Declaration not imported from PCH.
6230 
6231   assert(IFD->getDefinition() && "Category on a class without a definition?");
6232   ObjCClassesWithCategories.insert(
6233     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
6234 }
6235 
6236 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
6237   if (Chain && Chain->isProcessingUpdateRecords()) return;
6238   assert(!WritingAST && "Already writing the AST!");
6239 
6240   // If there is *any* declaration of the entity that's not from an AST file,
6241   // we can skip writing the update record. We make sure that isUsed() triggers
6242   // completion of the redeclaration chain of the entity.
6243   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6244     if (IsLocalDecl(Prev))
6245       return;
6246 
6247   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
6248 }
6249 
6250 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
6251   if (Chain && Chain->isProcessingUpdateRecords()) return;
6252   assert(!WritingAST && "Already writing the AST!");
6253   if (!D->isFromASTFile())
6254     return;
6255 
6256   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6257 }
6258 
6259 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6260                                                      const Attr *Attr) {
6261   if (Chain && Chain->isProcessingUpdateRecords()) return;
6262   assert(!WritingAST && "Already writing the AST!");
6263   if (!D->isFromASTFile())
6264     return;
6265 
6266   DeclUpdates[D].push_back(
6267       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6268 }
6269 
6270 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6271   if (Chain && Chain->isProcessingUpdateRecords()) return;
6272   assert(!WritingAST && "Already writing the AST!");
6273   assert(D->isHidden() && "expected a hidden declaration");
6274   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6275 }
6276 
6277 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6278                                        const RecordDecl *Record) {
6279   if (Chain && Chain->isProcessingUpdateRecords()) return;
6280   assert(!WritingAST && "Already writing the AST!");
6281   if (!Record->isFromASTFile())
6282     return;
6283   DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6284 }
6285 
6286 void ASTWriter::AddedCXXTemplateSpecialization(
6287     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6288   assert(!WritingAST && "Already writing the AST!");
6289 
6290   if (!TD->getFirstDecl()->isFromASTFile())
6291     return;
6292   if (Chain && Chain->isProcessingUpdateRecords())
6293     return;
6294 
6295   DeclsToEmitEvenIfUnreferenced.push_back(D);
6296 }
6297 
6298 void ASTWriter::AddedCXXTemplateSpecialization(
6299     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6300   assert(!WritingAST && "Already writing the AST!");
6301 
6302   if (!TD->getFirstDecl()->isFromASTFile())
6303     return;
6304   if (Chain && Chain->isProcessingUpdateRecords())
6305     return;
6306 
6307   DeclsToEmitEvenIfUnreferenced.push_back(D);
6308 }
6309 
6310 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6311                                                const FunctionDecl *D) {
6312   assert(!WritingAST && "Already writing the AST!");
6313 
6314   if (!TD->getFirstDecl()->isFromASTFile())
6315     return;
6316   if (Chain && Chain->isProcessingUpdateRecords())
6317     return;
6318 
6319   DeclsToEmitEvenIfUnreferenced.push_back(D);
6320 }
6321