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