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