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