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