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