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