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