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