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