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