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