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