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