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