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