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