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