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