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