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 "clang/Serialization/ASTSerializationListener.h"
16 #include "ASTCommon.h"
17 #include "clang/Sema/Sema.h"
18 #include "clang/Sema/IdentifierResolver.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclContextInternals.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeLocVisitor.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/PreprocessingRecord.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Basic/FileManager.h"
34 #include "clang/Basic/FileSystemStatCache.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/TargetInfo.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 <cstdio>
49 #include <string.h>
50 using namespace clang;
51 using namespace clang::serialization;
52 
53 template <typename T, typename Allocator>
54 T *data(std::vector<T, Allocator> &v) {
55   return v.empty() ? 0 : &v.front();
56 }
57 template <typename T, typename Allocator>
58 const T *data(const std::vector<T, Allocator> &v) {
59   return v.empty() ? 0 : &v.front();
60 }
61 
62 //===----------------------------------------------------------------------===//
63 // Type serialization
64 //===----------------------------------------------------------------------===//
65 
66 namespace {
67   class ASTTypeWriter {
68     ASTWriter &Writer;
69     ASTWriter::RecordDataImpl &Record;
70 
71   public:
72     /// \brief Type code that corresponds to the record generated.
73     TypeCode Code;
74 
75     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
76       : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
77 
78     void VisitArrayType(const ArrayType *T);
79     void VisitFunctionType(const FunctionType *T);
80     void VisitTagType(const TagType *T);
81 
82 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
83 #define ABSTRACT_TYPE(Class, Base)
84 #include "clang/AST/TypeNodes.def"
85   };
86 }
87 
88 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
89   assert(false && "Built-in types are never serialized");
90 }
91 
92 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
93   Writer.AddTypeRef(T->getElementType(), Record);
94   Code = TYPE_COMPLEX;
95 }
96 
97 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
98   Writer.AddTypeRef(T->getPointeeType(), Record);
99   Code = TYPE_POINTER;
100 }
101 
102 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
103   Writer.AddTypeRef(T->getPointeeType(), Record);
104   Code = TYPE_BLOCK_POINTER;
105 }
106 
107 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
108   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
109   Record.push_back(T->isSpelledAsLValue());
110   Code = TYPE_LVALUE_REFERENCE;
111 }
112 
113 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
114   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
115   Code = TYPE_RVALUE_REFERENCE;
116 }
117 
118 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
119   Writer.AddTypeRef(T->getPointeeType(), Record);
120   Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
121   Code = TYPE_MEMBER_POINTER;
122 }
123 
124 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
125   Writer.AddTypeRef(T->getElementType(), Record);
126   Record.push_back(T->getSizeModifier()); // FIXME: stable values
127   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
128 }
129 
130 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
131   VisitArrayType(T);
132   Writer.AddAPInt(T->getSize(), Record);
133   Code = TYPE_CONSTANT_ARRAY;
134 }
135 
136 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
137   VisitArrayType(T);
138   Code = TYPE_INCOMPLETE_ARRAY;
139 }
140 
141 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
142   VisitArrayType(T);
143   Writer.AddSourceLocation(T->getLBracketLoc(), Record);
144   Writer.AddSourceLocation(T->getRBracketLoc(), Record);
145   Writer.AddStmt(T->getSizeExpr());
146   Code = TYPE_VARIABLE_ARRAY;
147 }
148 
149 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
150   Writer.AddTypeRef(T->getElementType(), Record);
151   Record.push_back(T->getNumElements());
152   Record.push_back(T->getVectorKind());
153   Code = TYPE_VECTOR;
154 }
155 
156 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
157   VisitVectorType(T);
158   Code = TYPE_EXT_VECTOR;
159 }
160 
161 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
162   Writer.AddTypeRef(T->getResultType(), Record);
163   FunctionType::ExtInfo C = T->getExtInfo();
164   Record.push_back(C.getNoReturn());
165   Record.push_back(C.getHasRegParm());
166   Record.push_back(C.getRegParm());
167   // FIXME: need to stabilize encoding of calling convention...
168   Record.push_back(C.getCC());
169 }
170 
171 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
172   VisitFunctionType(T);
173   Code = TYPE_FUNCTION_NO_PROTO;
174 }
175 
176 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
177   VisitFunctionType(T);
178   Record.push_back(T->getNumArgs());
179   for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
180     Writer.AddTypeRef(T->getArgType(I), Record);
181   Record.push_back(T->isVariadic());
182   Record.push_back(T->getTypeQuals());
183   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
184   Record.push_back(T->getExceptionSpecType());
185   if (T->getExceptionSpecType() == EST_Dynamic) {
186     Record.push_back(T->getNumExceptions());
187     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
188       Writer.AddTypeRef(T->getExceptionType(I), Record);
189   } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
190     Writer.AddStmt(T->getNoexceptExpr());
191   }
192   Code = TYPE_FUNCTION_PROTO;
193 }
194 
195 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
196   Writer.AddDeclRef(T->getDecl(), Record);
197   Code = TYPE_UNRESOLVED_USING;
198 }
199 
200 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
201   Writer.AddDeclRef(T->getDecl(), Record);
202   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
203   Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
204   Code = TYPE_TYPEDEF;
205 }
206 
207 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
208   Writer.AddStmt(T->getUnderlyingExpr());
209   Code = TYPE_TYPEOF_EXPR;
210 }
211 
212 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
213   Writer.AddTypeRef(T->getUnderlyingType(), Record);
214   Code = TYPE_TYPEOF;
215 }
216 
217 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
218   Writer.AddStmt(T->getUnderlyingExpr());
219   Code = TYPE_DECLTYPE;
220 }
221 
222 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
223   Writer.AddTypeRef(T->getDeducedType(), Record);
224   Code = TYPE_AUTO;
225 }
226 
227 void ASTTypeWriter::VisitTagType(const TagType *T) {
228   Record.push_back(T->isDependentType());
229   Writer.AddDeclRef(T->getDecl(), Record);
230   assert(!T->isBeingDefined() &&
231          "Cannot serialize in the middle of a type definition");
232 }
233 
234 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
235   VisitTagType(T);
236   Code = TYPE_RECORD;
237 }
238 
239 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
240   VisitTagType(T);
241   Code = TYPE_ENUM;
242 }
243 
244 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
245   Writer.AddTypeRef(T->getModifiedType(), Record);
246   Writer.AddTypeRef(T->getEquivalentType(), Record);
247   Record.push_back(T->getAttrKind());
248   Code = TYPE_ATTRIBUTED;
249 }
250 
251 void
252 ASTTypeWriter::VisitSubstTemplateTypeParmType(
253                                         const SubstTemplateTypeParmType *T) {
254   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
255   Writer.AddTypeRef(T->getReplacementType(), Record);
256   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
257 }
258 
259 void
260 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
261                                       const SubstTemplateTypeParmPackType *T) {
262   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
263   Writer.AddTemplateArgument(T->getArgumentPack(), Record);
264   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
265 }
266 
267 void
268 ASTTypeWriter::VisitTemplateSpecializationType(
269                                        const TemplateSpecializationType *T) {
270   Record.push_back(T->isDependentType());
271   Writer.AddTemplateName(T->getTemplateName(), Record);
272   Record.push_back(T->getNumArgs());
273   for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
274          ArgI != ArgE; ++ArgI)
275     Writer.AddTemplateArgument(*ArgI, Record);
276   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
277                                                 : T->getCanonicalTypeInternal(),
278                     Record);
279   Code = TYPE_TEMPLATE_SPECIALIZATION;
280 }
281 
282 void
283 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
284   VisitArrayType(T);
285   Writer.AddStmt(T->getSizeExpr());
286   Writer.AddSourceRange(T->getBracketsRange(), Record);
287   Code = TYPE_DEPENDENT_SIZED_ARRAY;
288 }
289 
290 void
291 ASTTypeWriter::VisitDependentSizedExtVectorType(
292                                         const DependentSizedExtVectorType *T) {
293   // FIXME: Serialize this type (C++ only)
294   assert(false && "Cannot serialize dependent sized extended vector types");
295 }
296 
297 void
298 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
299   Record.push_back(T->getDepth());
300   Record.push_back(T->getIndex());
301   Record.push_back(T->isParameterPack());
302   Writer.AddIdentifierRef(T->getName(), Record);
303   Code = TYPE_TEMPLATE_TYPE_PARM;
304 }
305 
306 void
307 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
308   Record.push_back(T->getKeyword());
309   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
310   Writer.AddIdentifierRef(T->getIdentifier(), Record);
311   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
312                                                 : T->getCanonicalTypeInternal(),
313                     Record);
314   Code = TYPE_DEPENDENT_NAME;
315 }
316 
317 void
318 ASTTypeWriter::VisitDependentTemplateSpecializationType(
319                                 const DependentTemplateSpecializationType *T) {
320   Record.push_back(T->getKeyword());
321   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
322   Writer.AddIdentifierRef(T->getIdentifier(), Record);
323   Record.push_back(T->getNumArgs());
324   for (DependentTemplateSpecializationType::iterator
325          I = T->begin(), E = T->end(); I != E; ++I)
326     Writer.AddTemplateArgument(*I, Record);
327   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
328 }
329 
330 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
331   Writer.AddTypeRef(T->getPattern(), Record);
332   if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
333     Record.push_back(*NumExpansions + 1);
334   else
335     Record.push_back(0);
336   Code = TYPE_PACK_EXPANSION;
337 }
338 
339 void ASTTypeWriter::VisitParenType(const ParenType *T) {
340   Writer.AddTypeRef(T->getInnerType(), Record);
341   Code = TYPE_PAREN;
342 }
343 
344 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
345   Record.push_back(T->getKeyword());
346   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
347   Writer.AddTypeRef(T->getNamedType(), Record);
348   Code = TYPE_ELABORATED;
349 }
350 
351 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
352   Writer.AddDeclRef(T->getDecl(), Record);
353   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
354   Code = TYPE_INJECTED_CLASS_NAME;
355 }
356 
357 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
358   Writer.AddDeclRef(T->getDecl(), Record);
359   Code = TYPE_OBJC_INTERFACE;
360 }
361 
362 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
363   Writer.AddTypeRef(T->getBaseType(), Record);
364   Record.push_back(T->getNumProtocols());
365   for (ObjCObjectType::qual_iterator I = T->qual_begin(),
366        E = T->qual_end(); I != E; ++I)
367     Writer.AddDeclRef(*I, Record);
368   Code = TYPE_OBJC_OBJECT;
369 }
370 
371 void
372 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
373   Writer.AddTypeRef(T->getPointeeType(), Record);
374   Code = TYPE_OBJC_OBJECT_POINTER;
375 }
376 
377 namespace {
378 
379 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
380   ASTWriter &Writer;
381   ASTWriter::RecordDataImpl &Record;
382 
383 public:
384   TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
385     : Writer(Writer), Record(Record) { }
386 
387 #define ABSTRACT_TYPELOC(CLASS, PARENT)
388 #define TYPELOC(CLASS, PARENT) \
389     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
390 #include "clang/AST/TypeLocNodes.def"
391 
392   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
393   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
394 };
395 
396 }
397 
398 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
399   // nothing to do
400 }
401 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
402   Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
403   if (TL.needsExtraLocalData()) {
404     Record.push_back(TL.getWrittenTypeSpec());
405     Record.push_back(TL.getWrittenSignSpec());
406     Record.push_back(TL.getWrittenWidthSpec());
407     Record.push_back(TL.hasModeAttr());
408   }
409 }
410 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
411   Writer.AddSourceLocation(TL.getNameLoc(), Record);
412 }
413 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
414   Writer.AddSourceLocation(TL.getStarLoc(), Record);
415 }
416 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
417   Writer.AddSourceLocation(TL.getCaretLoc(), Record);
418 }
419 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
420   Writer.AddSourceLocation(TL.getAmpLoc(), Record);
421 }
422 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
423   Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
424 }
425 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
426   Writer.AddSourceLocation(TL.getStarLoc(), Record);
427   Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
428 }
429 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
430   Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
431   Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
432   Record.push_back(TL.getSizeExpr() ? 1 : 0);
433   if (TL.getSizeExpr())
434     Writer.AddStmt(TL.getSizeExpr());
435 }
436 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
437   VisitArrayTypeLoc(TL);
438 }
439 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
440   VisitArrayTypeLoc(TL);
441 }
442 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
443   VisitArrayTypeLoc(TL);
444 }
445 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
446                                             DependentSizedArrayTypeLoc TL) {
447   VisitArrayTypeLoc(TL);
448 }
449 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
450                                         DependentSizedExtVectorTypeLoc TL) {
451   Writer.AddSourceLocation(TL.getNameLoc(), Record);
452 }
453 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
454   Writer.AddSourceLocation(TL.getNameLoc(), Record);
455 }
456 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
457   Writer.AddSourceLocation(TL.getNameLoc(), Record);
458 }
459 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
460   Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
461   Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
462   Record.push_back(TL.getTrailingReturn());
463   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
464     Writer.AddDeclRef(TL.getArg(i), Record);
465 }
466 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
467   VisitFunctionTypeLoc(TL);
468 }
469 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
470   VisitFunctionTypeLoc(TL);
471 }
472 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
473   Writer.AddSourceLocation(TL.getNameLoc(), Record);
474 }
475 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
476   Writer.AddSourceLocation(TL.getNameLoc(), Record);
477 }
478 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
479   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
480   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
481   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
482 }
483 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
484   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
485   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
486   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
487   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
488 }
489 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
490   Writer.AddSourceLocation(TL.getNameLoc(), Record);
491 }
492 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
493   Writer.AddSourceLocation(TL.getNameLoc(), Record);
494 }
495 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
496   Writer.AddSourceLocation(TL.getNameLoc(), Record);
497 }
498 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
499   Writer.AddSourceLocation(TL.getNameLoc(), Record);
500 }
501 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
502   Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
503   if (TL.hasAttrOperand()) {
504     SourceRange range = TL.getAttrOperandParensRange();
505     Writer.AddSourceLocation(range.getBegin(), Record);
506     Writer.AddSourceLocation(range.getEnd(), Record);
507   }
508   if (TL.hasAttrExprOperand()) {
509     Expr *operand = TL.getAttrExprOperand();
510     Record.push_back(operand ? 1 : 0);
511     if (operand) Writer.AddStmt(operand);
512   } else if (TL.hasAttrEnumOperand()) {
513     Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
514   }
515 }
516 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
517   Writer.AddSourceLocation(TL.getNameLoc(), Record);
518 }
519 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
520                                             SubstTemplateTypeParmTypeLoc TL) {
521   Writer.AddSourceLocation(TL.getNameLoc(), Record);
522 }
523 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
524                                           SubstTemplateTypeParmPackTypeLoc TL) {
525   Writer.AddSourceLocation(TL.getNameLoc(), Record);
526 }
527 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
528                                            TemplateSpecializationTypeLoc TL) {
529   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
530   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
531   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
532   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
533     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
534                                       TL.getArgLoc(i).getLocInfo(), Record);
535 }
536 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
537   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
538   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
539 }
540 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
541   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
542   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
543 }
544 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
545   Writer.AddSourceLocation(TL.getNameLoc(), Record);
546 }
547 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
548   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
549   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
550   Writer.AddSourceLocation(TL.getNameLoc(), Record);
551 }
552 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
553        DependentTemplateSpecializationTypeLoc TL) {
554   Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
555   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
556   Writer.AddSourceLocation(TL.getNameLoc(), Record);
557   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
558   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
559   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
560     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
561                                       TL.getArgLoc(I).getLocInfo(), Record);
562 }
563 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
564   Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
565 }
566 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
567   Writer.AddSourceLocation(TL.getNameLoc(), Record);
568 }
569 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
570   Record.push_back(TL.hasBaseTypeAsWritten());
571   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
572   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
573   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
574     Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
575 }
576 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
577   Writer.AddSourceLocation(TL.getStarLoc(), Record);
578 }
579 
580 //===----------------------------------------------------------------------===//
581 // ASTWriter Implementation
582 //===----------------------------------------------------------------------===//
583 
584 static void EmitBlockID(unsigned ID, const char *Name,
585                         llvm::BitstreamWriter &Stream,
586                         ASTWriter::RecordDataImpl &Record) {
587   Record.clear();
588   Record.push_back(ID);
589   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
590 
591   // Emit the block name if present.
592   if (Name == 0 || Name[0] == 0) return;
593   Record.clear();
594   while (*Name)
595     Record.push_back(*Name++);
596   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
597 }
598 
599 static void EmitRecordID(unsigned ID, const char *Name,
600                          llvm::BitstreamWriter &Stream,
601                          ASTWriter::RecordDataImpl &Record) {
602   Record.clear();
603   Record.push_back(ID);
604   while (*Name)
605     Record.push_back(*Name++);
606   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
607 }
608 
609 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
610                           ASTWriter::RecordDataImpl &Record) {
611 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
612   RECORD(STMT_STOP);
613   RECORD(STMT_NULL_PTR);
614   RECORD(STMT_NULL);
615   RECORD(STMT_COMPOUND);
616   RECORD(STMT_CASE);
617   RECORD(STMT_DEFAULT);
618   RECORD(STMT_LABEL);
619   RECORD(STMT_IF);
620   RECORD(STMT_SWITCH);
621   RECORD(STMT_WHILE);
622   RECORD(STMT_DO);
623   RECORD(STMT_FOR);
624   RECORD(STMT_GOTO);
625   RECORD(STMT_INDIRECT_GOTO);
626   RECORD(STMT_CONTINUE);
627   RECORD(STMT_BREAK);
628   RECORD(STMT_RETURN);
629   RECORD(STMT_DECL);
630   RECORD(STMT_ASM);
631   RECORD(EXPR_PREDEFINED);
632   RECORD(EXPR_DECL_REF);
633   RECORD(EXPR_INTEGER_LITERAL);
634   RECORD(EXPR_FLOATING_LITERAL);
635   RECORD(EXPR_IMAGINARY_LITERAL);
636   RECORD(EXPR_STRING_LITERAL);
637   RECORD(EXPR_CHARACTER_LITERAL);
638   RECORD(EXPR_PAREN);
639   RECORD(EXPR_UNARY_OPERATOR);
640   RECORD(EXPR_SIZEOF_ALIGN_OF);
641   RECORD(EXPR_ARRAY_SUBSCRIPT);
642   RECORD(EXPR_CALL);
643   RECORD(EXPR_MEMBER);
644   RECORD(EXPR_BINARY_OPERATOR);
645   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
646   RECORD(EXPR_CONDITIONAL_OPERATOR);
647   RECORD(EXPR_IMPLICIT_CAST);
648   RECORD(EXPR_CSTYLE_CAST);
649   RECORD(EXPR_COMPOUND_LITERAL);
650   RECORD(EXPR_EXT_VECTOR_ELEMENT);
651   RECORD(EXPR_INIT_LIST);
652   RECORD(EXPR_DESIGNATED_INIT);
653   RECORD(EXPR_IMPLICIT_VALUE_INIT);
654   RECORD(EXPR_VA_ARG);
655   RECORD(EXPR_ADDR_LABEL);
656   RECORD(EXPR_STMT);
657   RECORD(EXPR_CHOOSE);
658   RECORD(EXPR_GNU_NULL);
659   RECORD(EXPR_SHUFFLE_VECTOR);
660   RECORD(EXPR_BLOCK);
661   RECORD(EXPR_BLOCK_DECL_REF);
662   RECORD(EXPR_GENERIC_SELECTION);
663   RECORD(EXPR_OBJC_STRING_LITERAL);
664   RECORD(EXPR_OBJC_ENCODE);
665   RECORD(EXPR_OBJC_SELECTOR_EXPR);
666   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
667   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
668   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
669   RECORD(EXPR_OBJC_KVC_REF_EXPR);
670   RECORD(EXPR_OBJC_MESSAGE_EXPR);
671   RECORD(STMT_OBJC_FOR_COLLECTION);
672   RECORD(STMT_OBJC_CATCH);
673   RECORD(STMT_OBJC_FINALLY);
674   RECORD(STMT_OBJC_AT_TRY);
675   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
676   RECORD(STMT_OBJC_AT_THROW);
677   RECORD(EXPR_CXX_OPERATOR_CALL);
678   RECORD(EXPR_CXX_CONSTRUCT);
679   RECORD(EXPR_CXX_STATIC_CAST);
680   RECORD(EXPR_CXX_DYNAMIC_CAST);
681   RECORD(EXPR_CXX_REINTERPRET_CAST);
682   RECORD(EXPR_CXX_CONST_CAST);
683   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
684   RECORD(EXPR_CXX_BOOL_LITERAL);
685   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
686   RECORD(EXPR_CXX_TYPEID_EXPR);
687   RECORD(EXPR_CXX_TYPEID_TYPE);
688   RECORD(EXPR_CXX_UUIDOF_EXPR);
689   RECORD(EXPR_CXX_UUIDOF_TYPE);
690   RECORD(EXPR_CXX_THIS);
691   RECORD(EXPR_CXX_THROW);
692   RECORD(EXPR_CXX_DEFAULT_ARG);
693   RECORD(EXPR_CXX_BIND_TEMPORARY);
694   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
695   RECORD(EXPR_CXX_NEW);
696   RECORD(EXPR_CXX_DELETE);
697   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
698   RECORD(EXPR_EXPR_WITH_CLEANUPS);
699   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
700   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
701   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
702   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
703   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
704   RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
705   RECORD(EXPR_CXX_NOEXCEPT);
706   RECORD(EXPR_OPAQUE_VALUE);
707   RECORD(EXPR_BINARY_TYPE_TRAIT);
708   RECORD(EXPR_PACK_EXPANSION);
709   RECORD(EXPR_SIZEOF_PACK);
710   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
711   RECORD(EXPR_CUDA_KERNEL_CALL);
712 #undef RECORD
713 }
714 
715 void ASTWriter::WriteBlockInfoBlock() {
716   RecordData Record;
717   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
718 
719 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
720 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
721 
722   // AST Top-Level Block.
723   BLOCK(AST_BLOCK);
724   RECORD(ORIGINAL_FILE_NAME);
725   RECORD(TYPE_OFFSET);
726   RECORD(DECL_OFFSET);
727   RECORD(LANGUAGE_OPTIONS);
728   RECORD(METADATA);
729   RECORD(IDENTIFIER_OFFSET);
730   RECORD(IDENTIFIER_TABLE);
731   RECORD(EXTERNAL_DEFINITIONS);
732   RECORD(SPECIAL_TYPES);
733   RECORD(STATISTICS);
734   RECORD(TENTATIVE_DEFINITIONS);
735   RECORD(UNUSED_FILESCOPED_DECLS);
736   RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
737   RECORD(SELECTOR_OFFSETS);
738   RECORD(METHOD_POOL);
739   RECORD(PP_COUNTER_VALUE);
740   RECORD(SOURCE_LOCATION_OFFSETS);
741   RECORD(SOURCE_LOCATION_PRELOADS);
742   RECORD(STAT_CACHE);
743   RECORD(EXT_VECTOR_DECLS);
744   RECORD(VERSION_CONTROL_BRANCH_REVISION);
745   RECORD(MACRO_DEFINITION_OFFSETS);
746   RECORD(CHAINED_METADATA);
747   RECORD(REFERENCED_SELECTOR_POOL);
748   RECORD(TU_UPDATE_LEXICAL);
749   RECORD(REDECLS_UPDATE_LATEST);
750   RECORD(SEMA_DECL_REFS);
751   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
752   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
753   RECORD(DECL_REPLACEMENTS);
754   RECORD(UPDATE_VISIBLE);
755   RECORD(DECL_UPDATE_OFFSETS);
756   RECORD(DECL_UPDATES);
757   RECORD(CXX_BASE_SPECIFIER_OFFSETS);
758   RECORD(DIAG_PRAGMA_MAPPINGS);
759   RECORD(CUDA_SPECIAL_DECL_REFS);
760   RECORD(HEADER_SEARCH_TABLE);
761   RECORD(FP_PRAGMA_OPTIONS);
762   RECORD(OPENCL_EXTENSIONS);
763 
764   // SourceManager Block.
765   BLOCK(SOURCE_MANAGER_BLOCK);
766   RECORD(SM_SLOC_FILE_ENTRY);
767   RECORD(SM_SLOC_BUFFER_ENTRY);
768   RECORD(SM_SLOC_BUFFER_BLOB);
769   RECORD(SM_SLOC_INSTANTIATION_ENTRY);
770   RECORD(SM_LINE_TABLE);
771 
772   // Preprocessor Block.
773   BLOCK(PREPROCESSOR_BLOCK);
774   RECORD(PP_MACRO_OBJECT_LIKE);
775   RECORD(PP_MACRO_FUNCTION_LIKE);
776   RECORD(PP_TOKEN);
777 
778   // Decls and Types block.
779   BLOCK(DECLTYPES_BLOCK);
780   RECORD(TYPE_EXT_QUAL);
781   RECORD(TYPE_COMPLEX);
782   RECORD(TYPE_POINTER);
783   RECORD(TYPE_BLOCK_POINTER);
784   RECORD(TYPE_LVALUE_REFERENCE);
785   RECORD(TYPE_RVALUE_REFERENCE);
786   RECORD(TYPE_MEMBER_POINTER);
787   RECORD(TYPE_CONSTANT_ARRAY);
788   RECORD(TYPE_INCOMPLETE_ARRAY);
789   RECORD(TYPE_VARIABLE_ARRAY);
790   RECORD(TYPE_VECTOR);
791   RECORD(TYPE_EXT_VECTOR);
792   RECORD(TYPE_FUNCTION_PROTO);
793   RECORD(TYPE_FUNCTION_NO_PROTO);
794   RECORD(TYPE_TYPEDEF);
795   RECORD(TYPE_TYPEOF_EXPR);
796   RECORD(TYPE_TYPEOF);
797   RECORD(TYPE_RECORD);
798   RECORD(TYPE_ENUM);
799   RECORD(TYPE_OBJC_INTERFACE);
800   RECORD(TYPE_OBJC_OBJECT);
801   RECORD(TYPE_OBJC_OBJECT_POINTER);
802   RECORD(TYPE_DECLTYPE);
803   RECORD(TYPE_ELABORATED);
804   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
805   RECORD(TYPE_UNRESOLVED_USING);
806   RECORD(TYPE_INJECTED_CLASS_NAME);
807   RECORD(TYPE_OBJC_OBJECT);
808   RECORD(TYPE_TEMPLATE_TYPE_PARM);
809   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
810   RECORD(TYPE_DEPENDENT_NAME);
811   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
812   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
813   RECORD(TYPE_PAREN);
814   RECORD(TYPE_PACK_EXPANSION);
815   RECORD(TYPE_ATTRIBUTED);
816   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
817   RECORD(DECL_TRANSLATION_UNIT);
818   RECORD(DECL_TYPEDEF);
819   RECORD(DECL_ENUM);
820   RECORD(DECL_RECORD);
821   RECORD(DECL_ENUM_CONSTANT);
822   RECORD(DECL_FUNCTION);
823   RECORD(DECL_OBJC_METHOD);
824   RECORD(DECL_OBJC_INTERFACE);
825   RECORD(DECL_OBJC_PROTOCOL);
826   RECORD(DECL_OBJC_IVAR);
827   RECORD(DECL_OBJC_AT_DEFS_FIELD);
828   RECORD(DECL_OBJC_CLASS);
829   RECORD(DECL_OBJC_FORWARD_PROTOCOL);
830   RECORD(DECL_OBJC_CATEGORY);
831   RECORD(DECL_OBJC_CATEGORY_IMPL);
832   RECORD(DECL_OBJC_IMPLEMENTATION);
833   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
834   RECORD(DECL_OBJC_PROPERTY);
835   RECORD(DECL_OBJC_PROPERTY_IMPL);
836   RECORD(DECL_FIELD);
837   RECORD(DECL_VAR);
838   RECORD(DECL_IMPLICIT_PARAM);
839   RECORD(DECL_PARM_VAR);
840   RECORD(DECL_FILE_SCOPE_ASM);
841   RECORD(DECL_BLOCK);
842   RECORD(DECL_CONTEXT_LEXICAL);
843   RECORD(DECL_CONTEXT_VISIBLE);
844   RECORD(DECL_NAMESPACE);
845   RECORD(DECL_NAMESPACE_ALIAS);
846   RECORD(DECL_USING);
847   RECORD(DECL_USING_SHADOW);
848   RECORD(DECL_USING_DIRECTIVE);
849   RECORD(DECL_UNRESOLVED_USING_VALUE);
850   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
851   RECORD(DECL_LINKAGE_SPEC);
852   RECORD(DECL_CXX_RECORD);
853   RECORD(DECL_CXX_METHOD);
854   RECORD(DECL_CXX_CONSTRUCTOR);
855   RECORD(DECL_CXX_DESTRUCTOR);
856   RECORD(DECL_CXX_CONVERSION);
857   RECORD(DECL_ACCESS_SPEC);
858   RECORD(DECL_FRIEND);
859   RECORD(DECL_FRIEND_TEMPLATE);
860   RECORD(DECL_CLASS_TEMPLATE);
861   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
862   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
863   RECORD(DECL_FUNCTION_TEMPLATE);
864   RECORD(DECL_TEMPLATE_TYPE_PARM);
865   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
866   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
867   RECORD(DECL_STATIC_ASSERT);
868   RECORD(DECL_CXX_BASE_SPECIFIERS);
869   RECORD(DECL_INDIRECTFIELD);
870   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
871 
872   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
873   RECORD(PPD_MACRO_INSTANTIATION);
874   RECORD(PPD_MACRO_DEFINITION);
875   RECORD(PPD_INCLUSION_DIRECTIVE);
876 
877   // Statements and Exprs can occur in the Decls and Types block.
878   AddStmtsExprs(Stream, Record);
879 #undef RECORD
880 #undef BLOCK
881   Stream.ExitBlock();
882 }
883 
884 /// \brief Adjusts the given filename to only write out the portion of the
885 /// filename that is not part of the system root directory.
886 ///
887 /// \param Filename the file name to adjust.
888 ///
889 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
890 /// the returned filename will be adjusted by this system root.
891 ///
892 /// \returns either the original filename (if it needs no adjustment) or the
893 /// adjusted filename (which points into the @p Filename parameter).
894 static const char *
895 adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
896   assert(Filename && "No file name to adjust?");
897 
898   if (!isysroot)
899     return Filename;
900 
901   // Verify that the filename and the system root have the same prefix.
902   unsigned Pos = 0;
903   for (; Filename[Pos] && isysroot[Pos]; ++Pos)
904     if (Filename[Pos] != isysroot[Pos])
905       return Filename; // Prefixes don't match.
906 
907   // We hit the end of the filename before we hit the end of the system root.
908   if (!Filename[Pos])
909     return Filename;
910 
911   // If the file name has a '/' at the current position, skip over the '/'.
912   // We distinguish sysroot-based includes from absolute includes by the
913   // absence of '/' at the beginning of sysroot-based includes.
914   if (Filename[Pos] == '/')
915     ++Pos;
916 
917   return Filename + Pos;
918 }
919 
920 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
921 void ASTWriter::WriteMetadata(ASTContext &Context, const char *isysroot,
922                               const std::string &OutputFile) {
923   using namespace llvm;
924 
925   // Metadata
926   const TargetInfo &Target = Context.Target;
927   BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
928   MetaAbbrev->Add(BitCodeAbbrevOp(
929                     Chain ? CHAINED_METADATA : METADATA));
930   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
931   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
932   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
933   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
934   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
935   // Target triple or chained PCH name
936   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
937   unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
938 
939   RecordData Record;
940   Record.push_back(Chain ? CHAINED_METADATA : METADATA);
941   Record.push_back(VERSION_MAJOR);
942   Record.push_back(VERSION_MINOR);
943   Record.push_back(CLANG_VERSION_MAJOR);
944   Record.push_back(CLANG_VERSION_MINOR);
945   Record.push_back(isysroot != 0);
946   // FIXME: This writes the absolute path for chained headers.
947   const std::string &BlobStr = Chain ? Chain->getFileName() : Target.getTriple().getTriple();
948   Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, BlobStr);
949 
950   // Original file name
951   SourceManager &SM = Context.getSourceManager();
952   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
953     BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
954     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
955     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
956     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
957 
958     llvm::SmallString<128> MainFilePath(MainFile->getName());
959 
960     llvm::sys::fs::make_absolute(MainFilePath);
961 
962     const char *MainFileNameStr = MainFilePath.c_str();
963     MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
964                                                       isysroot);
965     RecordData Record;
966     Record.push_back(ORIGINAL_FILE_NAME);
967     Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
968   }
969 
970   // Original PCH directory
971   if (!OutputFile.empty() && OutputFile != "-") {
972     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
973     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
974     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
975     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
976 
977     llvm::SmallString<128> OutputPath(OutputFile);
978 
979     llvm::sys::fs::make_absolute(OutputPath);
980     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
981 
982     RecordData Record;
983     Record.push_back(ORIGINAL_PCH_DIR);
984     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
985   }
986 
987   // Repository branch/version information.
988   BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
989   RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
990   RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
991   unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
992   Record.clear();
993   Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
994   Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
995                             getClangFullRepositoryVersion());
996 }
997 
998 /// \brief Write the LangOptions structure.
999 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
1000   RecordData Record;
1001   Record.push_back(LangOpts.Trigraphs);
1002   Record.push_back(LangOpts.BCPLComment);  // BCPL-style '//' comments.
1003   Record.push_back(LangOpts.DollarIdents);  // '$' allowed in identifiers.
1004   Record.push_back(LangOpts.AsmPreprocessor);  // Preprocessor in asm mode.
1005   Record.push_back(LangOpts.GNUMode);  // True in gnu99 mode false in c99 mode (etc)
1006   Record.push_back(LangOpts.GNUKeywords);  // Allow GNU-extension keywords
1007   Record.push_back(LangOpts.ImplicitInt);  // C89 implicit 'int'.
1008   Record.push_back(LangOpts.Digraphs);  // C94, C99 and C++
1009   Record.push_back(LangOpts.HexFloats);  // C99 Hexadecimal float constants.
1010   Record.push_back(LangOpts.C99);  // C99 Support
1011   Record.push_back(LangOpts.C1X);  // C1X Support
1012   Record.push_back(LangOpts.Microsoft);  // Microsoft extensions.
1013   // LangOpts.MSCVersion is ignored because all it does it set a macro, which is
1014   // already saved elsewhere.
1015   Record.push_back(LangOpts.CPlusPlus);  // C++ Support
1016   Record.push_back(LangOpts.CPlusPlus0x);  // C++0x Support
1017   Record.push_back(LangOpts.CXXOperatorNames);  // Treat C++ operator names as keywords.
1018 
1019   Record.push_back(LangOpts.ObjC1);  // Objective-C 1 support enabled.
1020   Record.push_back(LangOpts.ObjC2);  // Objective-C 2 support enabled.
1021   Record.push_back(LangOpts.ObjCNonFragileABI);  // Objective-C
1022                                                  // modern abi enabled.
1023   Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
1024                                                  // modern abi enabled.
1025   Record.push_back(LangOpts.AppleKext);          // Apple's kernel extensions ABI
1026   Record.push_back(LangOpts.ObjCDefaultSynthProperties); // Objective-C auto-synthesized
1027                                                       // properties enabled.
1028   Record.push_back(LangOpts.NoConstantCFStrings); // non cfstring generation enabled..
1029 
1030   Record.push_back(LangOpts.PascalStrings);  // Allow Pascal strings
1031   Record.push_back(LangOpts.WritableStrings);  // Allow writable strings
1032   Record.push_back(LangOpts.LaxVectorConversions);
1033   Record.push_back(LangOpts.AltiVec);
1034   Record.push_back(LangOpts.Exceptions);  // Support exception handling.
1035   Record.push_back(LangOpts.ObjCExceptions);
1036   Record.push_back(LangOpts.CXXExceptions);
1037   Record.push_back(LangOpts.SjLjExceptions);
1038 
1039   Record.push_back(LangOpts.MSBitfields); // MS-compatible structure layout
1040   Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
1041   Record.push_back(LangOpts.Freestanding); // Freestanding implementation
1042   Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
1043 
1044   // Whether static initializers are protected by locks.
1045   Record.push_back(LangOpts.ThreadsafeStatics);
1046   Record.push_back(LangOpts.POSIXThreads);
1047   Record.push_back(LangOpts.Blocks); // block extension to C
1048   Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
1049                                   // they are unused.
1050   Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
1051                                   // (modulo the platform support).
1052 
1053   Record.push_back(LangOpts.getSignedOverflowBehavior());
1054   Record.push_back(LangOpts.HeinousExtensions);
1055 
1056   Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
1057   Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
1058                                   // defined.
1059   Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
1060                                   // opposed to __DYNAMIC__).
1061   Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
1062 
1063   Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
1064                                   // used (instead of C99 semantics).
1065   Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
1066   Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
1067                                             // be enabled.
1068   Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
1069                                            // unsigned type
1070   Record.push_back(LangOpts.ShortWChar);  // force wchar_t to be unsigned short
1071   Record.push_back(LangOpts.ShortEnums);  // Should the enum type be equivalent
1072                                           // to the smallest integer type with
1073                                           // enough room.
1074   Record.push_back(LangOpts.getGCMode());
1075   Record.push_back(LangOpts.getVisibilityMode());
1076   Record.push_back(LangOpts.getStackProtectorMode());
1077   Record.push_back(LangOpts.InstantiationDepth);
1078   Record.push_back(LangOpts.OpenCL);
1079   Record.push_back(LangOpts.CUDA);
1080   Record.push_back(LangOpts.CatchUndefined);
1081   Record.push_back(LangOpts.DefaultFPContract);
1082   Record.push_back(LangOpts.ElideConstructors);
1083   Record.push_back(LangOpts.SpellChecking);
1084   Record.push_back(LangOpts.MRTD);
1085   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1086 }
1087 
1088 //===----------------------------------------------------------------------===//
1089 // stat cache Serialization
1090 //===----------------------------------------------------------------------===//
1091 
1092 namespace {
1093 // Trait used for the on-disk hash table of stat cache results.
1094 class ASTStatCacheTrait {
1095 public:
1096   typedef const char * key_type;
1097   typedef key_type key_type_ref;
1098 
1099   typedef struct stat data_type;
1100   typedef const data_type &data_type_ref;
1101 
1102   static unsigned ComputeHash(const char *path) {
1103     return llvm::HashString(path);
1104   }
1105 
1106   std::pair<unsigned,unsigned>
1107     EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1108                       data_type_ref Data) {
1109     unsigned StrLen = strlen(path);
1110     clang::io::Emit16(Out, StrLen);
1111     unsigned DataLen = 4 + 4 + 2 + 8 + 8;
1112     clang::io::Emit8(Out, DataLen);
1113     return std::make_pair(StrLen + 1, DataLen);
1114   }
1115 
1116   void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1117     Out.write(path, KeyLen);
1118   }
1119 
1120   void EmitData(llvm::raw_ostream &Out, key_type_ref,
1121                 data_type_ref Data, unsigned DataLen) {
1122     using namespace clang::io;
1123     uint64_t Start = Out.tell(); (void)Start;
1124 
1125     Emit32(Out, (uint32_t) Data.st_ino);
1126     Emit32(Out, (uint32_t) Data.st_dev);
1127     Emit16(Out, (uint16_t) Data.st_mode);
1128     Emit64(Out, (uint64_t) Data.st_mtime);
1129     Emit64(Out, (uint64_t) Data.st_size);
1130 
1131     assert(Out.tell() - Start == DataLen && "Wrong data length");
1132   }
1133 };
1134 } // end anonymous namespace
1135 
1136 /// \brief Write the stat() system call cache to the AST file.
1137 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
1138   // Build the on-disk hash table containing information about every
1139   // stat() call.
1140   OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
1141   unsigned NumStatEntries = 0;
1142   for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
1143                                 StatEnd = StatCalls.end();
1144        Stat != StatEnd; ++Stat, ++NumStatEntries) {
1145     const char *Filename = Stat->first();
1146     Generator.insert(Filename, Stat->second);
1147   }
1148 
1149   // Create the on-disk hash table in a buffer.
1150   llvm::SmallString<4096> StatCacheData;
1151   uint32_t BucketOffset;
1152   {
1153     llvm::raw_svector_ostream Out(StatCacheData);
1154     // Make sure that no bucket is at offset 0
1155     clang::io::Emit32(Out, 0);
1156     BucketOffset = Generator.Emit(Out);
1157   }
1158 
1159   // Create a blob abbreviation
1160   using namespace llvm;
1161   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1162   Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
1163   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1164   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1165   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1166   unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
1167 
1168   // Write the stat cache
1169   RecordData Record;
1170   Record.push_back(STAT_CACHE);
1171   Record.push_back(BucketOffset);
1172   Record.push_back(NumStatEntries);
1173   Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
1174 }
1175 
1176 //===----------------------------------------------------------------------===//
1177 // Source Manager Serialization
1178 //===----------------------------------------------------------------------===//
1179 
1180 /// \brief Create an abbreviation for the SLocEntry that refers to a
1181 /// file.
1182 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1183   using namespace llvm;
1184   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1185   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1186   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1187   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1188   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1189   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1190   // FileEntry fields.
1191   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1192   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1193   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1194   return Stream.EmitAbbrev(Abbrev);
1195 }
1196 
1197 /// \brief Create an abbreviation for the SLocEntry that refers to a
1198 /// buffer.
1199 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1200   using namespace llvm;
1201   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1202   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1203   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1204   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1205   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1206   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1207   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1208   return Stream.EmitAbbrev(Abbrev);
1209 }
1210 
1211 /// \brief Create an abbreviation for the SLocEntry that refers to a
1212 /// buffer's blob.
1213 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1214   using namespace llvm;
1215   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1216   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1217   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1218   return Stream.EmitAbbrev(Abbrev);
1219 }
1220 
1221 /// \brief Create an abbreviation for the SLocEntry that refers to an
1222 /// buffer.
1223 static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
1224   using namespace llvm;
1225   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1226   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_INSTANTIATION_ENTRY));
1227   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1228   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1229   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1230   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1231   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1232   return Stream.EmitAbbrev(Abbrev);
1233 }
1234 
1235 namespace {
1236   // Trait used for the on-disk hash table of header search information.
1237   class HeaderFileInfoTrait {
1238     ASTWriter &Writer;
1239     HeaderSearch &HS;
1240 
1241   public:
1242     HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)
1243       : Writer(Writer), HS(HS) { }
1244 
1245     typedef const char *key_type;
1246     typedef key_type key_type_ref;
1247 
1248     typedef HeaderFileInfo data_type;
1249     typedef const data_type &data_type_ref;
1250 
1251     static unsigned ComputeHash(const char *path) {
1252       // The hash is based only on the filename portion of the key, so that the
1253       // reader can match based on filenames when symlinking or excess path
1254       // elements ("foo/../", "../") change the form of the name. However,
1255       // complete path is still the key.
1256       return llvm::HashString(llvm::sys::path::filename(path));
1257     }
1258 
1259     std::pair<unsigned,unsigned>
1260     EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
1261                       data_type_ref Data) {
1262       unsigned StrLen = strlen(path);
1263       clang::io::Emit16(Out, StrLen);
1264       unsigned DataLen = 1 + 2 + 4;
1265       clang::io::Emit8(Out, DataLen);
1266       return std::make_pair(StrLen + 1, DataLen);
1267     }
1268 
1269     void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
1270       Out.write(path, KeyLen);
1271     }
1272 
1273     void EmitData(llvm::raw_ostream &Out, key_type_ref,
1274                   data_type_ref Data, unsigned DataLen) {
1275       using namespace clang::io;
1276       uint64_t Start = Out.tell(); (void)Start;
1277 
1278       unsigned char Flags = (Data.isImport << 3)
1279                           | (Data.DirInfo << 1)
1280                           | Data.Resolved;
1281       Emit8(Out, (uint8_t)Flags);
1282       Emit16(Out, (uint16_t) Data.NumIncludes);
1283 
1284       if (!Data.ControllingMacro)
1285         Emit32(Out, (uint32_t)Data.ControllingMacroID);
1286       else
1287         Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
1288       assert(Out.tell() - Start == DataLen && "Wrong data length");
1289     }
1290   };
1291 } // end anonymous namespace
1292 
1293 /// \brief Write the header search block for the list of files that
1294 ///
1295 /// \param HS The header search structure to save.
1296 ///
1297 /// \param Chain Whether we're creating a chained AST file.
1298 void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, const char* isysroot) {
1299   llvm::SmallVector<const FileEntry *, 16> FilesByUID;
1300   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1301 
1302   if (FilesByUID.size() > HS.header_file_size())
1303     FilesByUID.resize(HS.header_file_size());
1304 
1305   HeaderFileInfoTrait GeneratorTrait(*this, HS);
1306   OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1307   llvm::SmallVector<const char *, 4> SavedStrings;
1308   unsigned NumHeaderSearchEntries = 0;
1309   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1310     const FileEntry *File = FilesByUID[UID];
1311     if (!File)
1312       continue;
1313 
1314     const HeaderFileInfo &HFI = HS.header_file_begin()[UID];
1315     if (HFI.External && Chain)
1316       continue;
1317 
1318     // Turn the file name into an absolute path, if it isn't already.
1319     const char *Filename = File->getName();
1320     Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1321 
1322     // If we performed any translation on the file name at all, we need to
1323     // save this string, since the generator will refer to it later.
1324     if (Filename != File->getName()) {
1325       Filename = strdup(Filename);
1326       SavedStrings.push_back(Filename);
1327     }
1328 
1329     Generator.insert(Filename, HFI, GeneratorTrait);
1330     ++NumHeaderSearchEntries;
1331   }
1332 
1333   // Create the on-disk hash table in a buffer.
1334   llvm::SmallString<4096> TableData;
1335   uint32_t BucketOffset;
1336   {
1337     llvm::raw_svector_ostream Out(TableData);
1338     // Make sure that no bucket is at offset 0
1339     clang::io::Emit32(Out, 0);
1340     BucketOffset = Generator.Emit(Out, GeneratorTrait);
1341   }
1342 
1343   // Create a blob abbreviation
1344   using namespace llvm;
1345   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1346   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1347   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1348   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1349   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1350   unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1351 
1352   // Write the stat cache
1353   RecordData Record;
1354   Record.push_back(HEADER_SEARCH_TABLE);
1355   Record.push_back(BucketOffset);
1356   Record.push_back(NumHeaderSearchEntries);
1357   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1358 
1359   // Free all of the strings we had to duplicate.
1360   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1361     free((void*)SavedStrings[I]);
1362 }
1363 
1364 /// \brief Writes the block containing the serialized form of the
1365 /// source manager.
1366 ///
1367 /// TODO: We should probably use an on-disk hash table (stored in a
1368 /// blob), indexed based on the file name, so that we only create
1369 /// entries for files that we actually need. In the common case (no
1370 /// errors), we probably won't have to create file entries for any of
1371 /// the files in the AST.
1372 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1373                                         const Preprocessor &PP,
1374                                         const char *isysroot) {
1375   RecordData Record;
1376 
1377   // Enter the source manager block.
1378   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1379 
1380   // Abbreviations for the various kinds of source-location entries.
1381   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1382   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1383   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1384   unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
1385 
1386   // Write the line table.
1387   if (SourceMgr.hasLineTable()) {
1388     LineTableInfo &LineTable = SourceMgr.getLineTable();
1389 
1390     // Emit the file names
1391     Record.push_back(LineTable.getNumFilenames());
1392     for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1393       // Emit the file name
1394       const char *Filename = LineTable.getFilename(I);
1395       Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1396       unsigned FilenameLen = Filename? strlen(Filename) : 0;
1397       Record.push_back(FilenameLen);
1398       if (FilenameLen)
1399         Record.insert(Record.end(), Filename, Filename + FilenameLen);
1400     }
1401 
1402     // Emit the line entries
1403     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1404          L != LEnd; ++L) {
1405       // Emit the file ID
1406       Record.push_back(L->first);
1407 
1408       // Emit the line entries
1409       Record.push_back(L->second.size());
1410       for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1411                                          LEEnd = L->second.end();
1412            LE != LEEnd; ++LE) {
1413         Record.push_back(LE->FileOffset);
1414         Record.push_back(LE->LineNo);
1415         Record.push_back(LE->FilenameID);
1416         Record.push_back((unsigned)LE->FileKind);
1417         Record.push_back(LE->IncludeOffset);
1418       }
1419     }
1420     Stream.EmitRecord(SM_LINE_TABLE, Record);
1421   }
1422 
1423   // Write out the source location entry table. We skip the first
1424   // entry, which is always the same dummy entry.
1425   std::vector<uint32_t> SLocEntryOffsets;
1426   RecordData PreloadSLocs;
1427   unsigned BaseSLocID = Chain ? Chain->getTotalNumSLocs() : 0;
1428   SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1 - BaseSLocID);
1429   for (unsigned I = BaseSLocID + 1, N = SourceMgr.sloc_entry_size();
1430        I != N; ++I) {
1431     // Get this source location entry.
1432     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1433 
1434     // Record the offset of this source-location entry.
1435     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1436 
1437     // Figure out which record code to use.
1438     unsigned Code;
1439     if (SLoc->isFile()) {
1440       if (SLoc->getFile().getContentCache()->OrigEntry)
1441         Code = SM_SLOC_FILE_ENTRY;
1442       else
1443         Code = SM_SLOC_BUFFER_ENTRY;
1444     } else
1445       Code = SM_SLOC_INSTANTIATION_ENTRY;
1446     Record.clear();
1447     Record.push_back(Code);
1448 
1449     Record.push_back(SLoc->getOffset());
1450     if (SLoc->isFile()) {
1451       const SrcMgr::FileInfo &File = SLoc->getFile();
1452       Record.push_back(File.getIncludeLoc().getRawEncoding());
1453       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1454       Record.push_back(File.hasLineDirectives());
1455 
1456       const SrcMgr::ContentCache *Content = File.getContentCache();
1457       if (Content->OrigEntry) {
1458         assert(Content->OrigEntry == Content->ContentsEntry &&
1459                "Writing to AST an overriden file is not supported");
1460 
1461         // The source location entry is a file. The blob associated
1462         // with this entry is the file name.
1463 
1464         // Emit size/modification time for this file.
1465         Record.push_back(Content->OrigEntry->getSize());
1466         Record.push_back(Content->OrigEntry->getModificationTime());
1467 
1468         // Turn the file name into an absolute path, if it isn't already.
1469         const char *Filename = Content->OrigEntry->getName();
1470         llvm::SmallString<128> FilePath(Filename);
1471 
1472         // Ask the file manager to fixup the relative path for us. This will
1473         // honor the working directory.
1474         SourceMgr.getFileManager().FixupRelativePath(FilePath);
1475 
1476         // FIXME: This call to make_absolute shouldn't be necessary, the
1477         // call to FixupRelativePath should always return an absolute path.
1478         llvm::sys::fs::make_absolute(FilePath);
1479         Filename = FilePath.c_str();
1480 
1481         Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1482         Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1483       } else {
1484         // The source location entry is a buffer. The blob associated
1485         // with this entry contains the contents of the buffer.
1486 
1487         // We add one to the size so that we capture the trailing NULL
1488         // that is required by llvm::MemoryBuffer::getMemBuffer (on
1489         // the reader side).
1490         const llvm::MemoryBuffer *Buffer
1491           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1492         const char *Name = Buffer->getBufferIdentifier();
1493         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1494                                   llvm::StringRef(Name, strlen(Name) + 1));
1495         Record.clear();
1496         Record.push_back(SM_SLOC_BUFFER_BLOB);
1497         Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1498                                   llvm::StringRef(Buffer->getBufferStart(),
1499                                                   Buffer->getBufferSize() + 1));
1500 
1501         if (strcmp(Name, "<built-in>") == 0)
1502           PreloadSLocs.push_back(BaseSLocID + SLocEntryOffsets.size());
1503       }
1504     } else {
1505       // The source location entry is an instantiation.
1506       const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1507       Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1508       Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1509       Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1510 
1511       // Compute the token length for this macro expansion.
1512       unsigned NextOffset = SourceMgr.getNextOffset();
1513       if (I + 1 != N)
1514         NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1515       Record.push_back(NextOffset - SLoc->getOffset() - 1);
1516       Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1517     }
1518   }
1519 
1520   Stream.ExitBlock();
1521 
1522   if (SLocEntryOffsets.empty())
1523     return;
1524 
1525   // Write the source-location offsets table into the AST block. This
1526   // table is used for lazily loading source-location information.
1527   using namespace llvm;
1528   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1529   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1530   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1531   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1532   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1533   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1534 
1535   Record.clear();
1536   Record.push_back(SOURCE_LOCATION_OFFSETS);
1537   Record.push_back(SLocEntryOffsets.size());
1538   unsigned BaseOffset = Chain ? Chain->getNextSLocOffset() : 0;
1539   Record.push_back(SourceMgr.getNextOffset() - BaseOffset);
1540   Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1541                             (const char *)data(SLocEntryOffsets),
1542                            SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
1543 
1544   // Write the source location entry preloads array, telling the AST
1545   // reader which source locations entries it should load eagerly.
1546   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1547 }
1548 
1549 //===----------------------------------------------------------------------===//
1550 // Preprocessor Serialization
1551 //===----------------------------------------------------------------------===//
1552 
1553 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
1554   const std::pair<const IdentifierInfo *, MacroInfo *> &X =
1555     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
1556   const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
1557     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
1558   return X.first->getName().compare(Y.first->getName());
1559 }
1560 
1561 /// \brief Writes the block containing the serialized form of the
1562 /// preprocessor.
1563 ///
1564 void ASTWriter::WritePreprocessor(const Preprocessor &PP) {
1565   RecordData Record;
1566 
1567   // If the preprocessor __COUNTER__ value has been bumped, remember it.
1568   if (PP.getCounterValue() != 0) {
1569     Record.push_back(PP.getCounterValue());
1570     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1571     Record.clear();
1572   }
1573 
1574   // Enter the preprocessor block.
1575   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1576 
1577   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1578   // FIXME: use diagnostics subsystem for localization etc.
1579   if (PP.SawDateOrTime())
1580     fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1581 
1582 
1583   // Loop over all the macro definitions that are live at the end of the file,
1584   // emitting each to the PP section.
1585   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1586 
1587   // Construct the list of macro definitions that need to be serialized.
1588   llvm::SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2>
1589     MacrosToEmit;
1590   llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
1591   for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0),
1592                                     E = PP.macro_end(Chain == 0);
1593        I != E; ++I) {
1594     MacroDefinitionsSeen.insert(I->first);
1595     MacrosToEmit.push_back(std::make_pair(I->first, I->second));
1596   }
1597 
1598   // Sort the set of macro definitions that need to be serialized by the
1599   // name of the macro, to provide a stable ordering.
1600   llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(),
1601                        &compareMacroDefinitions);
1602 
1603   // Resolve any identifiers that defined macros at the time they were
1604   // deserialized, adding them to the list of macros to emit (if appropriate).
1605   for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
1606     IdentifierInfo *Name
1607       = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
1608     if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
1609       MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
1610   }
1611 
1612   for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
1613     const IdentifierInfo *Name = MacrosToEmit[I].first;
1614     MacroInfo *MI = MacrosToEmit[I].second;
1615     if (!MI)
1616       continue;
1617 
1618     // Don't emit builtin macros like __LINE__ to the AST file unless they have
1619     // been redefined by the header (in which case they are not isBuiltinMacro).
1620     // Also skip macros from a AST file if we're chaining.
1621 
1622     // FIXME: There is a (probably minor) optimization we could do here, if
1623     // the macro comes from the original PCH but the identifier comes from a
1624     // chained PCH, by storing the offset into the original PCH rather than
1625     // writing the macro definition a second time.
1626     if (MI->isBuiltinMacro() ||
1627         (Chain && Name->isFromAST() && MI->isFromAST()))
1628       continue;
1629 
1630     AddIdentifierRef(Name, Record);
1631     MacroOffsets[Name] = Stream.GetCurrentBitNo();
1632     Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1633     Record.push_back(MI->isUsed());
1634 
1635     unsigned Code;
1636     if (MI->isObjectLike()) {
1637       Code = PP_MACRO_OBJECT_LIKE;
1638     } else {
1639       Code = PP_MACRO_FUNCTION_LIKE;
1640 
1641       Record.push_back(MI->isC99Varargs());
1642       Record.push_back(MI->isGNUVarargs());
1643       Record.push_back(MI->getNumArgs());
1644       for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1645            I != E; ++I)
1646         AddIdentifierRef(*I, Record);
1647     }
1648 
1649     // If we have a detailed preprocessing record, record the macro definition
1650     // ID that corresponds to this macro.
1651     if (PPRec)
1652       Record.push_back(getMacroDefinitionID(PPRec->findMacroDefinition(MI)));
1653 
1654     Stream.EmitRecord(Code, Record);
1655     Record.clear();
1656 
1657     // Emit the tokens array.
1658     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1659       // Note that we know that the preprocessor does not have any annotation
1660       // tokens in it because they are created by the parser, and thus can't be
1661       // in a macro definition.
1662       const Token &Tok = MI->getReplacementToken(TokNo);
1663 
1664       Record.push_back(Tok.getLocation().getRawEncoding());
1665       Record.push_back(Tok.getLength());
1666 
1667       // FIXME: When reading literal tokens, reconstruct the literal pointer if
1668       // it is needed.
1669       AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1670       // FIXME: Should translate token kind to a stable encoding.
1671       Record.push_back(Tok.getKind());
1672       // FIXME: Should translate token flags to a stable encoding.
1673       Record.push_back(Tok.getFlags());
1674 
1675       Stream.EmitRecord(PP_TOKEN, Record);
1676       Record.clear();
1677     }
1678     ++NumMacros;
1679   }
1680   Stream.ExitBlock();
1681 
1682   if (PPRec)
1683     WritePreprocessorDetail(*PPRec);
1684 }
1685 
1686 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
1687   if (PPRec.begin(Chain) == PPRec.end(Chain))
1688     return;
1689 
1690   // Enter the preprocessor block.
1691   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
1692 
1693   // If the preprocessor has a preprocessing record, emit it.
1694   unsigned NumPreprocessingRecords = 0;
1695   using namespace llvm;
1696 
1697   // Set up the abbreviation for
1698   unsigned InclusionAbbrev = 0;
1699   {
1700     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1701     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
1702     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1703     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // start location
1704     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // end location
1705     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
1706     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
1707     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
1708     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1709     InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
1710   }
1711 
1712   unsigned IndexBase = Chain ? PPRec.getNumPreallocatedEntities() : 0;
1713   RecordData Record;
1714   for (PreprocessingRecord::iterator E = PPRec.begin(Chain),
1715                                   EEnd = PPRec.end(Chain);
1716        E != EEnd; ++E) {
1717     Record.clear();
1718 
1719     if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
1720       // Record this macro definition's location.
1721       MacroID ID = getMacroDefinitionID(MD);
1722 
1723       // Don't write the macro definition if it is from another AST file.
1724       if (ID < FirstMacroID)
1725         continue;
1726 
1727       // Notify the serialization listener that we're serializing this entity.
1728       if (SerializationListener)
1729         SerializationListener->SerializedPreprocessedEntity(*E,
1730                                                     Stream.GetCurrentBitNo());
1731 
1732       unsigned Position = ID - FirstMacroID;
1733       if (Position != MacroDefinitionOffsets.size()) {
1734         if (Position > MacroDefinitionOffsets.size())
1735           MacroDefinitionOffsets.resize(Position + 1);
1736 
1737         MacroDefinitionOffsets[Position] = Stream.GetCurrentBitNo();
1738       } else
1739         MacroDefinitionOffsets.push_back(Stream.GetCurrentBitNo());
1740 
1741       Record.push_back(IndexBase + NumPreprocessingRecords++);
1742       Record.push_back(ID);
1743       AddSourceLocation(MD->getSourceRange().getBegin(), Record);
1744       AddSourceLocation(MD->getSourceRange().getEnd(), Record);
1745       AddIdentifierRef(MD->getName(), Record);
1746       AddSourceLocation(MD->getLocation(), Record);
1747       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
1748       continue;
1749     }
1750 
1751     // Notify the serialization listener that we're serializing this entity.
1752     if (SerializationListener)
1753       SerializationListener->SerializedPreprocessedEntity(*E,
1754                                                     Stream.GetCurrentBitNo());
1755 
1756     if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
1757       Record.push_back(IndexBase + NumPreprocessingRecords++);
1758       AddSourceLocation(MI->getSourceRange().getBegin(), Record);
1759       AddSourceLocation(MI->getSourceRange().getEnd(), Record);
1760       AddIdentifierRef(MI->getName(), Record);
1761       Record.push_back(getMacroDefinitionID(MI->getDefinition()));
1762       Stream.EmitRecord(PPD_MACRO_INSTANTIATION, Record);
1763       continue;
1764     }
1765 
1766     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
1767       Record.push_back(PPD_INCLUSION_DIRECTIVE);
1768       Record.push_back(IndexBase + NumPreprocessingRecords++);
1769       AddSourceLocation(ID->getSourceRange().getBegin(), Record);
1770       AddSourceLocation(ID->getSourceRange().getEnd(), Record);
1771       Record.push_back(ID->getFileName().size());
1772       Record.push_back(ID->wasInQuotes());
1773       Record.push_back(static_cast<unsigned>(ID->getKind()));
1774       llvm::SmallString<64> Buffer;
1775       Buffer += ID->getFileName();
1776       Buffer += ID->getFile()->getName();
1777       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
1778       continue;
1779     }
1780 
1781     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
1782   }
1783   Stream.ExitBlock();
1784 
1785   // Write the offsets table for the preprocessing record.
1786   if (NumPreprocessingRecords > 0) {
1787     // Write the offsets table for identifier IDs.
1788     using namespace llvm;
1789     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1790     Abbrev->Add(BitCodeAbbrevOp(MACRO_DEFINITION_OFFSETS));
1791     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of records
1792     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macro defs
1793     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1794     unsigned MacroDefOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1795 
1796     Record.clear();
1797     Record.push_back(MACRO_DEFINITION_OFFSETS);
1798     Record.push_back(NumPreprocessingRecords);
1799     Record.push_back(MacroDefinitionOffsets.size());
1800     Stream.EmitRecordWithBlob(MacroDefOffsetAbbrev, Record,
1801                               (const char *)data(MacroDefinitionOffsets),
1802                               MacroDefinitionOffsets.size() * sizeof(uint32_t));
1803   }
1804 }
1805 
1806 void ASTWriter::WritePragmaDiagnosticMappings(const Diagnostic &Diag) {
1807   RecordData Record;
1808   for (Diagnostic::DiagStatePointsTy::const_iterator
1809          I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
1810          I != E; ++I) {
1811     const Diagnostic::DiagStatePoint &point = *I;
1812     if (point.Loc.isInvalid())
1813       continue;
1814 
1815     Record.push_back(point.Loc.getRawEncoding());
1816     for (Diagnostic::DiagState::iterator
1817            I = point.State->begin(), E = point.State->end(); I != E; ++I) {
1818       unsigned diag = I->first, map = I->second;
1819       if (map & 0x10) { // mapping from a diagnostic pragma.
1820         Record.push_back(diag);
1821         Record.push_back(map & 0x7);
1822       }
1823     }
1824     Record.push_back(-1); // mark the end of the diag/map pairs for this
1825                           // location.
1826   }
1827 
1828   if (!Record.empty())
1829     Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
1830 }
1831 
1832 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
1833   if (CXXBaseSpecifiersOffsets.empty())
1834     return;
1835 
1836   RecordData Record;
1837 
1838   // Create a blob abbreviation for the C++ base specifiers offsets.
1839   using namespace llvm;
1840 
1841   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1842   Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
1843   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
1844   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1845   unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1846 
1847   // Write the selector offsets table.
1848   Record.clear();
1849   Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
1850   Record.push_back(CXXBaseSpecifiersOffsets.size());
1851   Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
1852                             (const char *)CXXBaseSpecifiersOffsets.data(),
1853                             CXXBaseSpecifiersOffsets.size() * sizeof(uint32_t));
1854 }
1855 
1856 //===----------------------------------------------------------------------===//
1857 // Type Serialization
1858 //===----------------------------------------------------------------------===//
1859 
1860 /// \brief Write the representation of a type to the AST stream.
1861 void ASTWriter::WriteType(QualType T) {
1862   TypeIdx &Idx = TypeIdxs[T];
1863   if (Idx.getIndex() == 0) // we haven't seen this type before.
1864     Idx = TypeIdx(NextTypeID++);
1865 
1866   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
1867 
1868   // Record the offset for this type.
1869   unsigned Index = Idx.getIndex() - FirstTypeID;
1870   if (TypeOffsets.size() == Index)
1871     TypeOffsets.push_back(Stream.GetCurrentBitNo());
1872   else if (TypeOffsets.size() < Index) {
1873     TypeOffsets.resize(Index + 1);
1874     TypeOffsets[Index] = Stream.GetCurrentBitNo();
1875   }
1876 
1877   RecordData Record;
1878 
1879   // Emit the type's representation.
1880   ASTTypeWriter W(*this, Record);
1881 
1882   if (T.hasLocalNonFastQualifiers()) {
1883     Qualifiers Qs = T.getLocalQualifiers();
1884     AddTypeRef(T.getLocalUnqualifiedType(), Record);
1885     Record.push_back(Qs.getAsOpaqueValue());
1886     W.Code = TYPE_EXT_QUAL;
1887   } else {
1888     switch (T->getTypeClass()) {
1889       // For all of the concrete, non-dependent types, call the
1890       // appropriate visitor function.
1891 #define TYPE(Class, Base) \
1892     case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1893 #define ABSTRACT_TYPE(Class, Base)
1894 #include "clang/AST/TypeNodes.def"
1895     }
1896   }
1897 
1898   // Emit the serialized record.
1899   Stream.EmitRecord(W.Code, Record);
1900 
1901   // Flush any expressions that were written as part of this type.
1902   FlushStmts();
1903 }
1904 
1905 //===----------------------------------------------------------------------===//
1906 // Declaration Serialization
1907 //===----------------------------------------------------------------------===//
1908 
1909 /// \brief Write the block containing all of the declaration IDs
1910 /// lexically declared within the given DeclContext.
1911 ///
1912 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1913 /// bistream, or 0 if no block was written.
1914 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1915                                                  DeclContext *DC) {
1916   if (DC->decls_empty())
1917     return 0;
1918 
1919   uint64_t Offset = Stream.GetCurrentBitNo();
1920   RecordData Record;
1921   Record.push_back(DECL_CONTEXT_LEXICAL);
1922   llvm::SmallVector<KindDeclIDPair, 64> Decls;
1923   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1924          D != DEnd; ++D)
1925     Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
1926 
1927   ++NumLexicalDeclContexts;
1928   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
1929                             reinterpret_cast<char*>(Decls.data()),
1930                             Decls.size() * sizeof(KindDeclIDPair));
1931   return Offset;
1932 }
1933 
1934 void ASTWriter::WriteTypeDeclOffsets() {
1935   using namespace llvm;
1936   RecordData Record;
1937 
1938   // Write the type offsets array
1939   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1940   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
1941   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1942   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1943   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1944   Record.clear();
1945   Record.push_back(TYPE_OFFSET);
1946   Record.push_back(TypeOffsets.size());
1947   Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1948                             (const char *)data(TypeOffsets),
1949                             TypeOffsets.size() * sizeof(TypeOffsets[0]));
1950 
1951   // Write the declaration offsets array
1952   Abbrev = new BitCodeAbbrev();
1953   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
1954   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1955   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1956   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1957   Record.clear();
1958   Record.push_back(DECL_OFFSET);
1959   Record.push_back(DeclOffsets.size());
1960   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1961                             (const char *)data(DeclOffsets),
1962                             DeclOffsets.size() * sizeof(DeclOffsets[0]));
1963 }
1964 
1965 //===----------------------------------------------------------------------===//
1966 // Global Method Pool and Selector Serialization
1967 //===----------------------------------------------------------------------===//
1968 
1969 namespace {
1970 // Trait used for the on-disk hash table used in the method pool.
1971 class ASTMethodPoolTrait {
1972   ASTWriter &Writer;
1973 
1974 public:
1975   typedef Selector key_type;
1976   typedef key_type key_type_ref;
1977 
1978   struct data_type {
1979     SelectorID ID;
1980     ObjCMethodList Instance, Factory;
1981   };
1982   typedef const data_type& data_type_ref;
1983 
1984   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
1985 
1986   static unsigned ComputeHash(Selector Sel) {
1987     return serialization::ComputeHash(Sel);
1988   }
1989 
1990   std::pair<unsigned,unsigned>
1991     EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1992                       data_type_ref Methods) {
1993     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1994     clang::io::Emit16(Out, KeyLen);
1995     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
1996     for (const ObjCMethodList *Method = &Methods.Instance; Method;
1997          Method = Method->Next)
1998       if (Method->Method)
1999         DataLen += 4;
2000     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2001          Method = Method->Next)
2002       if (Method->Method)
2003         DataLen += 4;
2004     clang::io::Emit16(Out, DataLen);
2005     return std::make_pair(KeyLen, DataLen);
2006   }
2007 
2008   void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
2009     uint64_t Start = Out.tell();
2010     assert((Start >> 32) == 0 && "Selector key offset too large");
2011     Writer.SetSelectorOffset(Sel, Start);
2012     unsigned N = Sel.getNumArgs();
2013     clang::io::Emit16(Out, N);
2014     if (N == 0)
2015       N = 1;
2016     for (unsigned I = 0; I != N; ++I)
2017       clang::io::Emit32(Out,
2018                     Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2019   }
2020 
2021   void EmitData(llvm::raw_ostream& Out, key_type_ref,
2022                 data_type_ref Methods, unsigned DataLen) {
2023     uint64_t Start = Out.tell(); (void)Start;
2024     clang::io::Emit32(Out, Methods.ID);
2025     unsigned NumInstanceMethods = 0;
2026     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2027          Method = Method->Next)
2028       if (Method->Method)
2029         ++NumInstanceMethods;
2030 
2031     unsigned NumFactoryMethods = 0;
2032     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2033          Method = Method->Next)
2034       if (Method->Method)
2035         ++NumFactoryMethods;
2036 
2037     clang::io::Emit16(Out, NumInstanceMethods);
2038     clang::io::Emit16(Out, NumFactoryMethods);
2039     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2040          Method = Method->Next)
2041       if (Method->Method)
2042         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2043     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2044          Method = Method->Next)
2045       if (Method->Method)
2046         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
2047 
2048     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2049   }
2050 };
2051 } // end anonymous namespace
2052 
2053 /// \brief Write ObjC data: selectors and the method pool.
2054 ///
2055 /// The method pool contains both instance and factory methods, stored
2056 /// in an on-disk hash table indexed by the selector. The hash table also
2057 /// contains an empty entry for every other selector known to Sema.
2058 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2059   using namespace llvm;
2060 
2061   // Do we have to do anything at all?
2062   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2063     return;
2064   unsigned NumTableEntries = 0;
2065   // Create and write out the blob that contains selectors and the method pool.
2066   {
2067     OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2068     ASTMethodPoolTrait Trait(*this);
2069 
2070     // Create the on-disk hash table representation. We walk through every
2071     // selector we've seen and look it up in the method pool.
2072     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2073     for (llvm::DenseMap<Selector, SelectorID>::iterator
2074              I = SelectorIDs.begin(), E = SelectorIDs.end();
2075          I != E; ++I) {
2076       Selector S = I->first;
2077       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2078       ASTMethodPoolTrait::data_type Data = {
2079         I->second,
2080         ObjCMethodList(),
2081         ObjCMethodList()
2082       };
2083       if (F != SemaRef.MethodPool.end()) {
2084         Data.Instance = F->second.first;
2085         Data.Factory = F->second.second;
2086       }
2087       // Only write this selector if it's not in an existing AST or something
2088       // changed.
2089       if (Chain && I->second < FirstSelectorID) {
2090         // Selector already exists. Did it change?
2091         bool changed = false;
2092         for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2093              M = M->Next) {
2094           if (M->Method->getPCHLevel() == 0)
2095             changed = true;
2096         }
2097         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2098              M = M->Next) {
2099           if (M->Method->getPCHLevel() == 0)
2100             changed = true;
2101         }
2102         if (!changed)
2103           continue;
2104       } else if (Data.Instance.Method || Data.Factory.Method) {
2105         // A new method pool entry.
2106         ++NumTableEntries;
2107       }
2108       Generator.insert(S, Data, Trait);
2109     }
2110 
2111     // Create the on-disk hash table in a buffer.
2112     llvm::SmallString<4096> MethodPool;
2113     uint32_t BucketOffset;
2114     {
2115       ASTMethodPoolTrait Trait(*this);
2116       llvm::raw_svector_ostream Out(MethodPool);
2117       // Make sure that no bucket is at offset 0
2118       clang::io::Emit32(Out, 0);
2119       BucketOffset = Generator.Emit(Out, Trait);
2120     }
2121 
2122     // Create a blob abbreviation
2123     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2124     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2125     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2126     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2127     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2128     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2129 
2130     // Write the method pool
2131     RecordData Record;
2132     Record.push_back(METHOD_POOL);
2133     Record.push_back(BucketOffset);
2134     Record.push_back(NumTableEntries);
2135     Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2136 
2137     // Create a blob abbreviation for the selector table offsets.
2138     Abbrev = new BitCodeAbbrev();
2139     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2140     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2141     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2142     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2143 
2144     // Write the selector offsets table.
2145     Record.clear();
2146     Record.push_back(SELECTOR_OFFSETS);
2147     Record.push_back(SelectorOffsets.size());
2148     Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2149                               (const char *)data(SelectorOffsets),
2150                               SelectorOffsets.size() * 4);
2151   }
2152 }
2153 
2154 /// \brief Write the selectors referenced in @selector expression into AST file.
2155 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2156   using namespace llvm;
2157   if (SemaRef.ReferencedSelectors.empty())
2158     return;
2159 
2160   RecordData Record;
2161 
2162   // Note: this writes out all references even for a dependent AST. But it is
2163   // very tricky to fix, and given that @selector shouldn't really appear in
2164   // headers, probably not worth it. It's not a correctness issue.
2165   for (DenseMap<Selector, SourceLocation>::iterator S =
2166        SemaRef.ReferencedSelectors.begin(),
2167        E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2168     Selector Sel = (*S).first;
2169     SourceLocation Loc = (*S).second;
2170     AddSelectorRef(Sel, Record);
2171     AddSourceLocation(Loc, Record);
2172   }
2173   Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2174 }
2175 
2176 //===----------------------------------------------------------------------===//
2177 // Identifier Table Serialization
2178 //===----------------------------------------------------------------------===//
2179 
2180 namespace {
2181 class ASTIdentifierTableTrait {
2182   ASTWriter &Writer;
2183   Preprocessor &PP;
2184 
2185   /// \brief Determines whether this is an "interesting" identifier
2186   /// that needs a full IdentifierInfo structure written into the hash
2187   /// table.
2188   static bool isInterestingIdentifier(const IdentifierInfo *II) {
2189     return II->isPoisoned() ||
2190       II->isExtensionToken() ||
2191       II->hasMacroDefinition() ||
2192       II->getObjCOrBuiltinID() ||
2193       II->getFETokenInfo<void>();
2194   }
2195 
2196 public:
2197   typedef const IdentifierInfo* key_type;
2198   typedef key_type  key_type_ref;
2199 
2200   typedef IdentID data_type;
2201   typedef data_type data_type_ref;
2202 
2203   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP)
2204     : Writer(Writer), PP(PP) { }
2205 
2206   static unsigned ComputeHash(const IdentifierInfo* II) {
2207     return llvm::HashString(II->getName());
2208   }
2209 
2210   std::pair<unsigned,unsigned>
2211     EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
2212                       IdentID ID) {
2213     unsigned KeyLen = II->getLength() + 1;
2214     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
2215     if (isInterestingIdentifier(II)) {
2216       DataLen += 2; // 2 bytes for builtin ID, flags
2217       if (II->hasMacroDefinition() &&
2218           !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
2219         DataLen += 4;
2220       for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
2221                                      DEnd = IdentifierResolver::end();
2222            D != DEnd; ++D)
2223         DataLen += sizeof(DeclID);
2224     }
2225     clang::io::Emit16(Out, DataLen);
2226     // We emit the key length after the data length so that every
2227     // string is preceded by a 16-bit length. This matches the PTH
2228     // format for storing identifiers.
2229     clang::io::Emit16(Out, KeyLen);
2230     return std::make_pair(KeyLen, DataLen);
2231   }
2232 
2233   void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
2234                unsigned KeyLen) {
2235     // Record the location of the key data.  This is used when generating
2236     // the mapping from persistent IDs to strings.
2237     Writer.SetIdentifierOffset(II, Out.tell());
2238     Out.write(II->getNameStart(), KeyLen);
2239   }
2240 
2241   void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
2242                 IdentID ID, unsigned) {
2243     if (!isInterestingIdentifier(II)) {
2244       clang::io::Emit32(Out, ID << 1);
2245       return;
2246     }
2247 
2248     clang::io::Emit32(Out, (ID << 1) | 0x01);
2249     uint32_t Bits = 0;
2250     bool hasMacroDefinition =
2251       II->hasMacroDefinition() &&
2252       !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
2253     Bits = (uint32_t)II->getObjCOrBuiltinID();
2254     Bits = (Bits << 1) | unsigned(hasMacroDefinition);
2255     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
2256     Bits = (Bits << 1) | unsigned(II->isPoisoned());
2257     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
2258     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
2259     clang::io::Emit16(Out, Bits);
2260 
2261     if (hasMacroDefinition)
2262       clang::io::Emit32(Out, Writer.getMacroOffset(II));
2263 
2264     // Emit the declaration IDs in reverse order, because the
2265     // IdentifierResolver provides the declarations as they would be
2266     // visible (e.g., the function "stat" would come before the struct
2267     // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
2268     // adds declarations to the end of the list (so we need to see the
2269     // struct "status" before the function "status").
2270     // Only emit declarations that aren't from a chained PCH, though.
2271     llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
2272                                         IdentifierResolver::end());
2273     for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
2274                                                       DEnd = Decls.rend();
2275          D != DEnd; ++D)
2276       clang::io::Emit32(Out, Writer.getDeclID(*D));
2277   }
2278 };
2279 } // end anonymous namespace
2280 
2281 /// \brief Write the identifier table into the AST file.
2282 ///
2283 /// The identifier table consists of a blob containing string data
2284 /// (the actual identifiers themselves) and a separate "offsets" index
2285 /// that maps identifier IDs to locations within the blob.
2286 void ASTWriter::WriteIdentifierTable(Preprocessor &PP) {
2287   using namespace llvm;
2288 
2289   // Create and write out the blob that contains the identifier
2290   // strings.
2291   {
2292     OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
2293     ASTIdentifierTableTrait Trait(*this, PP);
2294 
2295     // Look for any identifiers that were named while processing the
2296     // headers, but are otherwise not needed. We add these to the hash
2297     // table to enable checking of the predefines buffer in the case
2298     // where the user adds new macro definitions when building the AST
2299     // file.
2300     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
2301                                 IDEnd = PP.getIdentifierTable().end();
2302          ID != IDEnd; ++ID)
2303       getIdentifierRef(ID->second);
2304 
2305     // Create the on-disk hash table representation. We only store offsets
2306     // for identifiers that appear here for the first time.
2307     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
2308     for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
2309            ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
2310          ID != IDEnd; ++ID) {
2311       assert(ID->first && "NULL identifier in identifier table");
2312       if (!Chain || !ID->first->isFromAST())
2313         Generator.insert(ID->first, ID->second, Trait);
2314     }
2315 
2316     // Create the on-disk hash table in a buffer.
2317     llvm::SmallString<4096> IdentifierTable;
2318     uint32_t BucketOffset;
2319     {
2320       ASTIdentifierTableTrait Trait(*this, PP);
2321       llvm::raw_svector_ostream Out(IdentifierTable);
2322       // Make sure that no bucket is at offset 0
2323       clang::io::Emit32(Out, 0);
2324       BucketOffset = Generator.Emit(Out, Trait);
2325     }
2326 
2327     // Create a blob abbreviation
2328     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2329     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
2330     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2331     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2332     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
2333 
2334     // Write the identifier table
2335     RecordData Record;
2336     Record.push_back(IDENTIFIER_TABLE);
2337     Record.push_back(BucketOffset);
2338     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
2339   }
2340 
2341   // Write the offsets table for identifier IDs.
2342   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2343   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
2344   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
2345   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2346   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2347 
2348   RecordData Record;
2349   Record.push_back(IDENTIFIER_OFFSET);
2350   Record.push_back(IdentifierOffsets.size());
2351   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
2352                             (const char *)data(IdentifierOffsets),
2353                             IdentifierOffsets.size() * sizeof(uint32_t));
2354 }
2355 
2356 //===----------------------------------------------------------------------===//
2357 // DeclContext's Name Lookup Table Serialization
2358 //===----------------------------------------------------------------------===//
2359 
2360 namespace {
2361 // Trait used for the on-disk hash table used in the method pool.
2362 class ASTDeclContextNameLookupTrait {
2363   ASTWriter &Writer;
2364 
2365 public:
2366   typedef DeclarationName key_type;
2367   typedef key_type key_type_ref;
2368 
2369   typedef DeclContext::lookup_result data_type;
2370   typedef const data_type& data_type_ref;
2371 
2372   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
2373 
2374   unsigned ComputeHash(DeclarationName Name) {
2375     llvm::FoldingSetNodeID ID;
2376     ID.AddInteger(Name.getNameKind());
2377 
2378     switch (Name.getNameKind()) {
2379     case DeclarationName::Identifier:
2380       ID.AddString(Name.getAsIdentifierInfo()->getName());
2381       break;
2382     case DeclarationName::ObjCZeroArgSelector:
2383     case DeclarationName::ObjCOneArgSelector:
2384     case DeclarationName::ObjCMultiArgSelector:
2385       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
2386       break;
2387     case DeclarationName::CXXConstructorName:
2388     case DeclarationName::CXXDestructorName:
2389     case DeclarationName::CXXConversionFunctionName:
2390       ID.AddInteger(Writer.GetOrCreateTypeID(Name.getCXXNameType()));
2391       break;
2392     case DeclarationName::CXXOperatorName:
2393       ID.AddInteger(Name.getCXXOverloadedOperator());
2394       break;
2395     case DeclarationName::CXXLiteralOperatorName:
2396       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
2397     case DeclarationName::CXXUsingDirective:
2398       break;
2399     }
2400 
2401     return ID.ComputeHash();
2402   }
2403 
2404   std::pair<unsigned,unsigned>
2405     EmitKeyDataLength(llvm::raw_ostream& Out, DeclarationName Name,
2406                       data_type_ref Lookup) {
2407     unsigned KeyLen = 1;
2408     switch (Name.getNameKind()) {
2409     case DeclarationName::Identifier:
2410     case DeclarationName::ObjCZeroArgSelector:
2411     case DeclarationName::ObjCOneArgSelector:
2412     case DeclarationName::ObjCMultiArgSelector:
2413     case DeclarationName::CXXConstructorName:
2414     case DeclarationName::CXXDestructorName:
2415     case DeclarationName::CXXConversionFunctionName:
2416     case DeclarationName::CXXLiteralOperatorName:
2417       KeyLen += 4;
2418       break;
2419     case DeclarationName::CXXOperatorName:
2420       KeyLen += 1;
2421       break;
2422     case DeclarationName::CXXUsingDirective:
2423       break;
2424     }
2425     clang::io::Emit16(Out, KeyLen);
2426 
2427     // 2 bytes for num of decls and 4 for each DeclID.
2428     unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
2429     clang::io::Emit16(Out, DataLen);
2430 
2431     return std::make_pair(KeyLen, DataLen);
2432   }
2433 
2434   void EmitKey(llvm::raw_ostream& Out, DeclarationName Name, unsigned) {
2435     using namespace clang::io;
2436 
2437     assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
2438     Emit8(Out, Name.getNameKind());
2439     switch (Name.getNameKind()) {
2440     case DeclarationName::Identifier:
2441       Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
2442       break;
2443     case DeclarationName::ObjCZeroArgSelector:
2444     case DeclarationName::ObjCOneArgSelector:
2445     case DeclarationName::ObjCMultiArgSelector:
2446       Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
2447       break;
2448     case DeclarationName::CXXConstructorName:
2449     case DeclarationName::CXXDestructorName:
2450     case DeclarationName::CXXConversionFunctionName:
2451       Emit32(Out, Writer.getTypeID(Name.getCXXNameType()));
2452       break;
2453     case DeclarationName::CXXOperatorName:
2454       assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
2455       Emit8(Out, Name.getCXXOverloadedOperator());
2456       break;
2457     case DeclarationName::CXXLiteralOperatorName:
2458       Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
2459       break;
2460     case DeclarationName::CXXUsingDirective:
2461       break;
2462     }
2463   }
2464 
2465   void EmitData(llvm::raw_ostream& Out, key_type_ref,
2466                 data_type Lookup, unsigned DataLen) {
2467     uint64_t Start = Out.tell(); (void)Start;
2468     clang::io::Emit16(Out, Lookup.second - Lookup.first);
2469     for (; Lookup.first != Lookup.second; ++Lookup.first)
2470       clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
2471 
2472     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2473   }
2474 };
2475 } // end anonymous namespace
2476 
2477 /// \brief Write the block containing all of the declaration IDs
2478 /// visible from the given DeclContext.
2479 ///
2480 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
2481 /// bitstream, or 0 if no block was written.
2482 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
2483                                                  DeclContext *DC) {
2484   if (DC->getPrimaryContext() != DC)
2485     return 0;
2486 
2487   // Since there is no name lookup into functions or methods, don't bother to
2488   // build a visible-declarations table for these entities.
2489   if (DC->isFunctionOrMethod())
2490     return 0;
2491 
2492   // If not in C++, we perform name lookup for the translation unit via the
2493   // IdentifierInfo chains, don't bother to build a visible-declarations table.
2494   // FIXME: In C++ we need the visible declarations in order to "see" the
2495   // friend declarations, is there a way to do this without writing the table ?
2496   if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
2497     return 0;
2498 
2499   // Force the DeclContext to build a its name-lookup table.
2500   if (DC->hasExternalVisibleStorage())
2501     DC->MaterializeVisibleDeclsFromExternalStorage();
2502   else
2503     DC->lookup(DeclarationName());
2504 
2505   // Serialize the contents of the mapping used for lookup. Note that,
2506   // although we have two very different code paths, the serialized
2507   // representation is the same for both cases: a declaration name,
2508   // followed by a size, followed by references to the visible
2509   // declarations that have that name.
2510   uint64_t Offset = Stream.GetCurrentBitNo();
2511   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2512   if (!Map || Map->empty())
2513     return 0;
2514 
2515   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2516   ASTDeclContextNameLookupTrait Trait(*this);
2517 
2518   // Create the on-disk hash table representation.
2519   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2520        D != DEnd; ++D) {
2521     DeclarationName Name = D->first;
2522     DeclContext::lookup_result Result = D->second.getLookupResult();
2523     Generator.insert(Name, Result, Trait);
2524   }
2525 
2526   // Create the on-disk hash table in a buffer.
2527   llvm::SmallString<4096> LookupTable;
2528   uint32_t BucketOffset;
2529   {
2530     llvm::raw_svector_ostream Out(LookupTable);
2531     // Make sure that no bucket is at offset 0
2532     clang::io::Emit32(Out, 0);
2533     BucketOffset = Generator.Emit(Out, Trait);
2534   }
2535 
2536   // Write the lookup table
2537   RecordData Record;
2538   Record.push_back(DECL_CONTEXT_VISIBLE);
2539   Record.push_back(BucketOffset);
2540   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
2541                             LookupTable.str());
2542 
2543   Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
2544   ++NumVisibleDeclContexts;
2545   return Offset;
2546 }
2547 
2548 /// \brief Write an UPDATE_VISIBLE block for the given context.
2549 ///
2550 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
2551 /// DeclContext in a dependent AST file. As such, they only exist for the TU
2552 /// (in C++) and for namespaces.
2553 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
2554   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
2555   if (!Map || Map->empty())
2556     return;
2557 
2558   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
2559   ASTDeclContextNameLookupTrait Trait(*this);
2560 
2561   // Create the hash table.
2562   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
2563        D != DEnd; ++D) {
2564     DeclarationName Name = D->first;
2565     DeclContext::lookup_result Result = D->second.getLookupResult();
2566     // For any name that appears in this table, the results are complete, i.e.
2567     // they overwrite results from previous PCHs. Merging is always a mess.
2568     Generator.insert(Name, Result, Trait);
2569   }
2570 
2571   // Create the on-disk hash table in a buffer.
2572   llvm::SmallString<4096> LookupTable;
2573   uint32_t BucketOffset;
2574   {
2575     llvm::raw_svector_ostream Out(LookupTable);
2576     // Make sure that no bucket is at offset 0
2577     clang::io::Emit32(Out, 0);
2578     BucketOffset = Generator.Emit(Out, Trait);
2579   }
2580 
2581   // Write the lookup table
2582   RecordData Record;
2583   Record.push_back(UPDATE_VISIBLE);
2584   Record.push_back(getDeclID(cast<Decl>(DC)));
2585   Record.push_back(BucketOffset);
2586   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
2587 }
2588 
2589 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
2590 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
2591   RecordData Record;
2592   Record.push_back(Opts.fp_contract);
2593   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
2594 }
2595 
2596 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
2597 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
2598   if (!SemaRef.Context.getLangOptions().OpenCL)
2599     return;
2600 
2601   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
2602   RecordData Record;
2603 #define OPENCLEXT(nm)  Record.push_back(Opts.nm);
2604 #include "clang/Basic/OpenCLExtensions.def"
2605   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
2606 }
2607 
2608 //===----------------------------------------------------------------------===//
2609 // General Serialization Routines
2610 //===----------------------------------------------------------------------===//
2611 
2612 /// \brief Write a record containing the given attributes.
2613 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
2614   Record.push_back(Attrs.size());
2615   for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
2616     const Attr * A = *i;
2617     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
2618     AddSourceLocation(A->getLocation(), Record);
2619 
2620 #include "clang/Serialization/AttrPCHWrite.inc"
2621 
2622   }
2623 }
2624 
2625 void ASTWriter::AddString(llvm::StringRef Str, RecordDataImpl &Record) {
2626   Record.push_back(Str.size());
2627   Record.insert(Record.end(), Str.begin(), Str.end());
2628 }
2629 
2630 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
2631                                 RecordDataImpl &Record) {
2632   Record.push_back(Version.getMajor());
2633   if (llvm::Optional<unsigned> Minor = Version.getMinor())
2634     Record.push_back(*Minor + 1);
2635   else
2636     Record.push_back(0);
2637   if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
2638     Record.push_back(*Subminor + 1);
2639   else
2640     Record.push_back(0);
2641 }
2642 
2643 /// \brief Note that the identifier II occurs at the given offset
2644 /// within the identifier table.
2645 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
2646   IdentID ID = IdentifierIDs[II];
2647   // Only store offsets new to this AST file. Other identifier names are looked
2648   // up earlier in the chain and thus don't need an offset.
2649   if (ID >= FirstIdentID)
2650     IdentifierOffsets[ID - FirstIdentID] = Offset;
2651 }
2652 
2653 /// \brief Note that the selector Sel occurs at the given offset
2654 /// within the method pool/selector table.
2655 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
2656   unsigned ID = SelectorIDs[Sel];
2657   assert(ID && "Unknown selector");
2658   // Don't record offsets for selectors that are also available in a different
2659   // file.
2660   if (ID < FirstSelectorID)
2661     return;
2662   SelectorOffsets[ID - FirstSelectorID] = Offset;
2663 }
2664 
2665 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
2666   : Stream(Stream), Chain(0), SerializationListener(0),
2667     FirstDeclID(1), NextDeclID(FirstDeclID),
2668     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
2669     FirstIdentID(1), NextIdentID(FirstIdentID), FirstSelectorID(1),
2670     NextSelectorID(FirstSelectorID), FirstMacroID(1), NextMacroID(FirstMacroID),
2671     CollectedStmts(&StmtsToEmit),
2672     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
2673     NumVisibleDeclContexts(0), FirstCXXBaseSpecifiersID(1),
2674     NextCXXBaseSpecifiersID(1)
2675 {
2676 }
2677 
2678 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2679                          const std::string &OutputFile,
2680                          const char *isysroot) {
2681   // Emit the file header.
2682   Stream.Emit((unsigned)'C', 8);
2683   Stream.Emit((unsigned)'P', 8);
2684   Stream.Emit((unsigned)'C', 8);
2685   Stream.Emit((unsigned)'H', 8);
2686 
2687   WriteBlockInfoBlock();
2688 
2689   if (Chain)
2690     WriteASTChain(SemaRef, StatCalls, isysroot);
2691   else
2692     WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile);
2693 }
2694 
2695 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2696                              const char *isysroot,
2697                              const std::string &OutputFile) {
2698   using namespace llvm;
2699 
2700   ASTContext &Context = SemaRef.Context;
2701   Preprocessor &PP = SemaRef.PP;
2702 
2703   // The translation unit is the first declaration we'll emit.
2704   DeclIDs[Context.getTranslationUnitDecl()] = 1;
2705   ++NextDeclID;
2706   DeclTypesToEmit.push(Context.getTranslationUnitDecl());
2707 
2708   // Make sure that we emit IdentifierInfos (and any attached
2709   // declarations) for builtins.
2710   {
2711     IdentifierTable &Table = PP.getIdentifierTable();
2712     llvm::SmallVector<const char *, 32> BuiltinNames;
2713     Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
2714                                         Context.getLangOptions().NoBuiltin);
2715     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
2716       getIdentifierRef(&Table.get(BuiltinNames[I]));
2717   }
2718 
2719   // Build a record containing all of the tentative definitions in this file, in
2720   // TentativeDefinitions order.  Generally, this record will be empty for
2721   // headers.
2722   RecordData TentativeDefinitions;
2723   for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2724     AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2725   }
2726 
2727   // Build a record containing all of the file scoped decls in this file.
2728   RecordData UnusedFileScopedDecls;
2729   for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i)
2730     AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2731 
2732   RecordData WeakUndeclaredIdentifiers;
2733   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2734     WeakUndeclaredIdentifiers.push_back(
2735                                       SemaRef.WeakUndeclaredIdentifiers.size());
2736     for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2737          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2738          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2739       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2740       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2741       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2742       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2743     }
2744   }
2745 
2746   // Build a record containing all of the locally-scoped external
2747   // declarations in this header file. Generally, this record will be
2748   // empty.
2749   RecordData LocallyScopedExternalDecls;
2750   // FIXME: This is filling in the AST file in densemap order which is
2751   // nondeterminstic!
2752   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
2753          TD = SemaRef.LocallyScopedExternalDecls.begin(),
2754          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
2755        TD != TDEnd; ++TD)
2756     AddDeclRef(TD->second, LocallyScopedExternalDecls);
2757 
2758   // Build a record containing all of the ext_vector declarations.
2759   RecordData ExtVectorDecls;
2760   for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
2761     AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2762 
2763   // Build a record containing all of the VTable uses information.
2764   RecordData VTableUses;
2765   if (!SemaRef.VTableUses.empty()) {
2766     VTableUses.push_back(SemaRef.VTableUses.size());
2767     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
2768       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
2769       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
2770       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
2771     }
2772   }
2773 
2774   // Build a record containing all of dynamic classes declarations.
2775   RecordData DynamicClasses;
2776   for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
2777     AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
2778 
2779   // Build a record containing all of pending implicit instantiations.
2780   RecordData PendingInstantiations;
2781   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
2782          I = SemaRef.PendingInstantiations.begin(),
2783          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
2784     AddDeclRef(I->first, PendingInstantiations);
2785     AddSourceLocation(I->second, PendingInstantiations);
2786   }
2787   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
2788          "There are local ones at end of translation unit!");
2789 
2790   // Build a record containing some declaration references.
2791   RecordData SemaDeclRefs;
2792   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
2793     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
2794     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
2795   }
2796 
2797   RecordData CUDASpecialDeclRefs;
2798   if (Context.getcudaConfigureCallDecl()) {
2799     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
2800   }
2801 
2802   // Write the remaining AST contents.
2803   RecordData Record;
2804   Stream.EnterSubblock(AST_BLOCK_ID, 5);
2805   WriteMetadata(Context, isysroot, OutputFile);
2806   WriteLanguageOptions(Context.getLangOptions());
2807   if (StatCalls && !isysroot)
2808     WriteStatCache(*StatCalls);
2809   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2810   // Write the record of special types.
2811   Record.clear();
2812 
2813   AddTypeRef(Context.getBuiltinVaListType(), Record);
2814   AddTypeRef(Context.getObjCIdType(), Record);
2815   AddTypeRef(Context.getObjCSelType(), Record);
2816   AddTypeRef(Context.getObjCProtoType(), Record);
2817   AddTypeRef(Context.getObjCClassType(), Record);
2818   AddTypeRef(Context.getRawCFConstantStringType(), Record);
2819   AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2820   AddTypeRef(Context.getFILEType(), Record);
2821   AddTypeRef(Context.getjmp_bufType(), Record);
2822   AddTypeRef(Context.getsigjmp_bufType(), Record);
2823   AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2824   AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2825   AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2826   AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2827   AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2828   AddTypeRef(Context.getRawNSConstantStringType(), Record);
2829   Record.push_back(Context.isInt128Installed());
2830   AddTypeRef(Context.AutoDeductTy, Record);
2831   AddTypeRef(Context.AutoRRefDeductTy, Record);
2832   Stream.EmitRecord(SPECIAL_TYPES, Record);
2833 
2834   // Keep writing types and declarations until all types and
2835   // declarations have been written.
2836   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
2837   WriteDeclsBlockAbbrevs();
2838   while (!DeclTypesToEmit.empty()) {
2839     DeclOrType DOT = DeclTypesToEmit.front();
2840     DeclTypesToEmit.pop();
2841     if (DOT.isType())
2842       WriteType(DOT.getType());
2843     else
2844       WriteDecl(Context, DOT.getDecl());
2845   }
2846   Stream.ExitBlock();
2847 
2848   WritePreprocessor(PP);
2849   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
2850   WriteSelectors(SemaRef);
2851   WriteReferencedSelectorsPool(SemaRef);
2852   WriteIdentifierTable(PP);
2853   WriteFPPragmaOptions(SemaRef.getFPOptions());
2854   WriteOpenCLExtensions(SemaRef);
2855 
2856   WriteTypeDeclOffsets();
2857   WritePragmaDiagnosticMappings(Context.getDiagnostics());
2858 
2859   WriteCXXBaseSpecifiersOffsets();
2860 
2861   // Write the record containing external, unnamed definitions.
2862   if (!ExternalDefinitions.empty())
2863     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
2864 
2865   // Write the record containing tentative definitions.
2866   if (!TentativeDefinitions.empty())
2867     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
2868 
2869   // Write the record containing unused file scoped decls.
2870   if (!UnusedFileScopedDecls.empty())
2871     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
2872 
2873   // Write the record containing weak undeclared identifiers.
2874   if (!WeakUndeclaredIdentifiers.empty())
2875     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
2876                       WeakUndeclaredIdentifiers);
2877 
2878   // Write the record containing locally-scoped external definitions.
2879   if (!LocallyScopedExternalDecls.empty())
2880     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
2881                       LocallyScopedExternalDecls);
2882 
2883   // Write the record containing ext_vector type names.
2884   if (!ExtVectorDecls.empty())
2885     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
2886 
2887   // Write the record containing VTable uses information.
2888   if (!VTableUses.empty())
2889     Stream.EmitRecord(VTABLE_USES, VTableUses);
2890 
2891   // Write the record containing dynamic classes declarations.
2892   if (!DynamicClasses.empty())
2893     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
2894 
2895   // Write the record containing pending implicit instantiations.
2896   if (!PendingInstantiations.empty())
2897     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
2898 
2899   // Write the record containing declaration references of Sema.
2900   if (!SemaDeclRefs.empty())
2901     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
2902 
2903   // Write the record containing CUDA-specific declaration references.
2904   if (!CUDASpecialDeclRefs.empty())
2905     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
2906 
2907   // Some simple statistics
2908   Record.clear();
2909   Record.push_back(NumStatements);
2910   Record.push_back(NumMacros);
2911   Record.push_back(NumLexicalDeclContexts);
2912   Record.push_back(NumVisibleDeclContexts);
2913   Stream.EmitRecord(STATISTICS, Record);
2914   Stream.ExitBlock();
2915 }
2916 
2917 void ASTWriter::WriteASTChain(Sema &SemaRef, MemorizeStatCalls *StatCalls,
2918                               const char *isysroot) {
2919   using namespace llvm;
2920 
2921   ASTContext &Context = SemaRef.Context;
2922   Preprocessor &PP = SemaRef.PP;
2923 
2924   RecordData Record;
2925   Stream.EnterSubblock(AST_BLOCK_ID, 5);
2926   WriteMetadata(Context, isysroot, "");
2927   if (StatCalls && !isysroot)
2928     WriteStatCache(*StatCalls);
2929   // FIXME: Source manager block should only write new stuff, which could be
2930   // done by tracking the largest ID in the chain
2931   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2932 
2933   // The special types are in the chained PCH.
2934 
2935   // We don't start with the translation unit, but with its decls that
2936   // don't come from the chained PCH.
2937   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
2938   llvm::SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
2939   for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
2940                                   E = TU->noload_decls_end();
2941        I != E; ++I) {
2942     if ((*I)->getPCHLevel() == 0)
2943       NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
2944     else if ((*I)->isChangedSinceDeserialization())
2945       (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
2946   }
2947   // We also need to write a lexical updates block for the TU.
2948   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
2949   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
2950   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2951   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
2952   Record.clear();
2953   Record.push_back(TU_UPDATE_LEXICAL);
2954   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
2955                           reinterpret_cast<const char*>(NewGlobalDecls.data()),
2956                           NewGlobalDecls.size() * sizeof(KindDeclIDPair));
2957   // And a visible updates block for the DeclContexts.
2958   Abv = new llvm::BitCodeAbbrev();
2959   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
2960   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
2961   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
2962   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
2963   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
2964   WriteDeclContextVisibleUpdate(TU);
2965 
2966   // Build a record containing all of the new tentative definitions in this
2967   // file, in TentativeDefinitions order.
2968   RecordData TentativeDefinitions;
2969   for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
2970     if (SemaRef.TentativeDefinitions[i]->getPCHLevel() == 0)
2971       AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
2972   }
2973 
2974   // Build a record containing all of the file scoped decls in this file.
2975   RecordData UnusedFileScopedDecls;
2976   for (unsigned i=0, e = SemaRef.UnusedFileScopedDecls.size(); i !=e; ++i) {
2977     if (SemaRef.UnusedFileScopedDecls[i]->getPCHLevel() == 0)
2978       AddDeclRef(SemaRef.UnusedFileScopedDecls[i], UnusedFileScopedDecls);
2979   }
2980 
2981   // We write the entire table, overwriting the tables from the chain.
2982   RecordData WeakUndeclaredIdentifiers;
2983   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
2984     WeakUndeclaredIdentifiers.push_back(
2985                                       SemaRef.WeakUndeclaredIdentifiers.size());
2986     for (llvm::DenseMap<IdentifierInfo*,Sema::WeakInfo>::iterator
2987          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
2988          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
2989       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
2990       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
2991       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
2992       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
2993     }
2994   }
2995 
2996   // Build a record containing all of the locally-scoped external
2997   // declarations in this header file. Generally, this record will be
2998   // empty.
2999   RecordData LocallyScopedExternalDecls;
3000   // FIXME: This is filling in the AST file in densemap order which is
3001   // nondeterminstic!
3002   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3003          TD = SemaRef.LocallyScopedExternalDecls.begin(),
3004          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
3005        TD != TDEnd; ++TD) {
3006     if (TD->second->getPCHLevel() == 0)
3007       AddDeclRef(TD->second, LocallyScopedExternalDecls);
3008   }
3009 
3010   // Build a record containing all of the ext_vector declarations.
3011   RecordData ExtVectorDecls;
3012   for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I) {
3013     if (SemaRef.ExtVectorDecls[I]->getPCHLevel() == 0)
3014       AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
3015   }
3016 
3017   // Build a record containing all of the VTable uses information.
3018   // We write everything here, because it's too hard to determine whether
3019   // a use is new to this part.
3020   RecordData VTableUses;
3021   if (!SemaRef.VTableUses.empty()) {
3022     VTableUses.push_back(SemaRef.VTableUses.size());
3023     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
3024       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
3025       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
3026       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
3027     }
3028   }
3029 
3030   // Build a record containing all of dynamic classes declarations.
3031   RecordData DynamicClasses;
3032   for (unsigned I = 0, N = SemaRef.DynamicClasses.size(); I != N; ++I)
3033     if (SemaRef.DynamicClasses[I]->getPCHLevel() == 0)
3034       AddDeclRef(SemaRef.DynamicClasses[I], DynamicClasses);
3035 
3036   // Build a record containing all of pending implicit instantiations.
3037   RecordData PendingInstantiations;
3038   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
3039          I = SemaRef.PendingInstantiations.begin(),
3040          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
3041     if (I->first->getPCHLevel() == 0) {
3042       AddDeclRef(I->first, PendingInstantiations);
3043       AddSourceLocation(I->second, PendingInstantiations);
3044     }
3045   }
3046   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
3047          "There are local ones at end of translation unit!");
3048 
3049   // Build a record containing some declaration references.
3050   // It's not worth the effort to avoid duplication here.
3051   RecordData SemaDeclRefs;
3052   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
3053     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
3054     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
3055   }
3056 
3057   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, 3);
3058   WriteDeclsBlockAbbrevs();
3059   for (DeclsToRewriteTy::iterator
3060          I = DeclsToRewrite.begin(), E = DeclsToRewrite.end(); I != E; ++I)
3061     DeclTypesToEmit.push(const_cast<Decl*>(*I));
3062   while (!DeclTypesToEmit.empty()) {
3063     DeclOrType DOT = DeclTypesToEmit.front();
3064     DeclTypesToEmit.pop();
3065     if (DOT.isType())
3066       WriteType(DOT.getType());
3067     else
3068       WriteDecl(Context, DOT.getDecl());
3069   }
3070   Stream.ExitBlock();
3071 
3072   WritePreprocessor(PP);
3073   WriteSelectors(SemaRef);
3074   WriteReferencedSelectorsPool(SemaRef);
3075   WriteIdentifierTable(PP);
3076   WriteFPPragmaOptions(SemaRef.getFPOptions());
3077   WriteOpenCLExtensions(SemaRef);
3078 
3079   WriteTypeDeclOffsets();
3080   // FIXME: For chained PCH only write the new mappings (we currently
3081   // write all of them again).
3082   WritePragmaDiagnosticMappings(Context.getDiagnostics());
3083 
3084   WriteCXXBaseSpecifiersOffsets();
3085 
3086   /// Build a record containing first declarations from a chained PCH and the
3087   /// most recent declarations in this AST that they point to.
3088   RecordData FirstLatestDeclIDs;
3089   for (FirstLatestDeclMap::iterator
3090         I = FirstLatestDecls.begin(), E = FirstLatestDecls.end(); I != E; ++I) {
3091     assert(I->first->getPCHLevel() > I->second->getPCHLevel() &&
3092            "Expected first & second to be in different PCHs");
3093     AddDeclRef(I->first, FirstLatestDeclIDs);
3094     AddDeclRef(I->second, FirstLatestDeclIDs);
3095   }
3096   if (!FirstLatestDeclIDs.empty())
3097     Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
3098 
3099   // Write the record containing external, unnamed definitions.
3100   if (!ExternalDefinitions.empty())
3101     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
3102 
3103   // Write the record containing tentative definitions.
3104   if (!TentativeDefinitions.empty())
3105     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
3106 
3107   // Write the record containing unused file scoped decls.
3108   if (!UnusedFileScopedDecls.empty())
3109     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
3110 
3111   // Write the record containing weak undeclared identifiers.
3112   if (!WeakUndeclaredIdentifiers.empty())
3113     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
3114                       WeakUndeclaredIdentifiers);
3115 
3116   // Write the record containing locally-scoped external definitions.
3117   if (!LocallyScopedExternalDecls.empty())
3118     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
3119                       LocallyScopedExternalDecls);
3120 
3121   // Write the record containing ext_vector type names.
3122   if (!ExtVectorDecls.empty())
3123     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
3124 
3125   // Write the record containing VTable uses information.
3126   if (!VTableUses.empty())
3127     Stream.EmitRecord(VTABLE_USES, VTableUses);
3128 
3129   // Write the record containing dynamic classes declarations.
3130   if (!DynamicClasses.empty())
3131     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
3132 
3133   // Write the record containing pending implicit instantiations.
3134   if (!PendingInstantiations.empty())
3135     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
3136 
3137   // Write the record containing declaration references of Sema.
3138   if (!SemaDeclRefs.empty())
3139     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
3140 
3141   // Write the updates to DeclContexts.
3142   for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
3143            I = UpdatedDeclContexts.begin(),
3144            E = UpdatedDeclContexts.end();
3145          I != E; ++I)
3146     WriteDeclContextVisibleUpdate(*I);
3147 
3148   WriteDeclUpdatesBlocks();
3149 
3150   Record.clear();
3151   Record.push_back(NumStatements);
3152   Record.push_back(NumMacros);
3153   Record.push_back(NumLexicalDeclContexts);
3154   Record.push_back(NumVisibleDeclContexts);
3155   WriteDeclReplacementsBlock();
3156   Stream.EmitRecord(STATISTICS, Record);
3157   Stream.ExitBlock();
3158 }
3159 
3160 void ASTWriter::WriteDeclUpdatesBlocks() {
3161   if (DeclUpdates.empty())
3162     return;
3163 
3164   RecordData OffsetsRecord;
3165   Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, 3);
3166   for (DeclUpdateMap::iterator
3167          I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
3168     const Decl *D = I->first;
3169     UpdateRecord &URec = I->second;
3170 
3171     if (DeclsToRewrite.count(D))
3172       continue; // The decl will be written completely,no need to store updates.
3173 
3174     uint64_t Offset = Stream.GetCurrentBitNo();
3175     Stream.EmitRecord(DECL_UPDATES, URec);
3176 
3177     OffsetsRecord.push_back(GetDeclRef(D));
3178     OffsetsRecord.push_back(Offset);
3179   }
3180   Stream.ExitBlock();
3181   Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
3182 }
3183 
3184 void ASTWriter::WriteDeclReplacementsBlock() {
3185   if (ReplacedDecls.empty())
3186     return;
3187 
3188   RecordData Record;
3189   for (llvm::SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
3190            I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
3191     Record.push_back(I->first);
3192     Record.push_back(I->second);
3193   }
3194   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
3195 }
3196 
3197 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
3198   Record.push_back(Loc.getRawEncoding());
3199 }
3200 
3201 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
3202   AddSourceLocation(Range.getBegin(), Record);
3203   AddSourceLocation(Range.getEnd(), Record);
3204 }
3205 
3206 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
3207   Record.push_back(Value.getBitWidth());
3208   const uint64_t *Words = Value.getRawData();
3209   Record.append(Words, Words + Value.getNumWords());
3210 }
3211 
3212 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
3213   Record.push_back(Value.isUnsigned());
3214   AddAPInt(Value, Record);
3215 }
3216 
3217 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
3218   AddAPInt(Value.bitcastToAPInt(), Record);
3219 }
3220 
3221 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
3222   Record.push_back(getIdentifierRef(II));
3223 }
3224 
3225 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
3226   if (II == 0)
3227     return 0;
3228 
3229   IdentID &ID = IdentifierIDs[II];
3230   if (ID == 0)
3231     ID = NextIdentID++;
3232   return ID;
3233 }
3234 
3235 MacroID ASTWriter::getMacroDefinitionID(MacroDefinition *MD) {
3236   if (MD == 0)
3237     return 0;
3238 
3239   MacroID &ID = MacroDefinitions[MD];
3240   if (ID == 0)
3241     ID = NextMacroID++;
3242   return ID;
3243 }
3244 
3245 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
3246   Record.push_back(getSelectorRef(SelRef));
3247 }
3248 
3249 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
3250   if (Sel.getAsOpaquePtr() == 0) {
3251     return 0;
3252   }
3253 
3254   SelectorID &SID = SelectorIDs[Sel];
3255   if (SID == 0 && Chain) {
3256     // This might trigger a ReadSelector callback, which will set the ID for
3257     // this selector.
3258     Chain->LoadSelector(Sel);
3259   }
3260   if (SID == 0) {
3261     SID = NextSelectorID++;
3262   }
3263   return SID;
3264 }
3265 
3266 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
3267   AddDeclRef(Temp->getDestructor(), Record);
3268 }
3269 
3270 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
3271                                       CXXBaseSpecifier const *BasesEnd,
3272                                         RecordDataImpl &Record) {
3273   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
3274   CXXBaseSpecifiersToWrite.push_back(
3275                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
3276                                                         Bases, BasesEnd));
3277   Record.push_back(NextCXXBaseSpecifiersID++);
3278 }
3279 
3280 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3281                                            const TemplateArgumentLocInfo &Arg,
3282                                            RecordDataImpl &Record) {
3283   switch (Kind) {
3284   case TemplateArgument::Expression:
3285     AddStmt(Arg.getAsExpr());
3286     break;
3287   case TemplateArgument::Type:
3288     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
3289     break;
3290   case TemplateArgument::Template:
3291     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3292     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3293     break;
3294   case TemplateArgument::TemplateExpansion:
3295     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
3296     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
3297     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
3298     break;
3299   case TemplateArgument::Null:
3300   case TemplateArgument::Integral:
3301   case TemplateArgument::Declaration:
3302   case TemplateArgument::Pack:
3303     break;
3304   }
3305 }
3306 
3307 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
3308                                        RecordDataImpl &Record) {
3309   AddTemplateArgument(Arg.getArgument(), Record);
3310 
3311   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
3312     bool InfoHasSameExpr
3313       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
3314     Record.push_back(InfoHasSameExpr);
3315     if (InfoHasSameExpr)
3316       return; // Avoid storing the same expr twice.
3317   }
3318   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
3319                              Record);
3320 }
3321 
3322 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
3323                                   RecordDataImpl &Record) {
3324   if (TInfo == 0) {
3325     AddTypeRef(QualType(), Record);
3326     return;
3327   }
3328 
3329   AddTypeLoc(TInfo->getTypeLoc(), Record);
3330 }
3331 
3332 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
3333   AddTypeRef(TL.getType(), Record);
3334 
3335   TypeLocWriter TLW(*this, Record);
3336   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
3337     TLW.Visit(TL);
3338 }
3339 
3340 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
3341   Record.push_back(GetOrCreateTypeID(T));
3342 }
3343 
3344 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
3345   return MakeTypeID(T,
3346               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
3347 }
3348 
3349 TypeID ASTWriter::getTypeID(QualType T) const {
3350   return MakeTypeID(T,
3351               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
3352 }
3353 
3354 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
3355   if (T.isNull())
3356     return TypeIdx();
3357   assert(!T.getLocalFastQualifiers());
3358 
3359   TypeIdx &Idx = TypeIdxs[T];
3360   if (Idx.getIndex() == 0) {
3361     // We haven't seen this type before. Assign it a new ID and put it
3362     // into the queue of types to emit.
3363     Idx = TypeIdx(NextTypeID++);
3364     DeclTypesToEmit.push(T);
3365   }
3366   return Idx;
3367 }
3368 
3369 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
3370   if (T.isNull())
3371     return TypeIdx();
3372   assert(!T.getLocalFastQualifiers());
3373 
3374   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3375   assert(I != TypeIdxs.end() && "Type not emitted!");
3376   return I->second;
3377 }
3378 
3379 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
3380   Record.push_back(GetDeclRef(D));
3381 }
3382 
3383 DeclID ASTWriter::GetDeclRef(const Decl *D) {
3384   if (D == 0) {
3385     return 0;
3386   }
3387   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
3388   DeclID &ID = DeclIDs[D];
3389   if (ID == 0) {
3390     // We haven't seen this declaration before. Give it a new ID and
3391     // enqueue it in the list of declarations to emit.
3392     ID = NextDeclID++;
3393     DeclTypesToEmit.push(const_cast<Decl *>(D));
3394   } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
3395     // We don't add it to the replacement collection here, because we don't
3396     // have the offset yet.
3397     DeclTypesToEmit.push(const_cast<Decl *>(D));
3398     // Reset the flag, so that we don't add this decl multiple times.
3399     const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
3400   }
3401 
3402   return ID;
3403 }
3404 
3405 DeclID ASTWriter::getDeclID(const Decl *D) {
3406   if (D == 0)
3407     return 0;
3408 
3409   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
3410   return DeclIDs[D];
3411 }
3412 
3413 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
3414   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
3415   Record.push_back(Name.getNameKind());
3416   switch (Name.getNameKind()) {
3417   case DeclarationName::Identifier:
3418     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
3419     break;
3420 
3421   case DeclarationName::ObjCZeroArgSelector:
3422   case DeclarationName::ObjCOneArgSelector:
3423   case DeclarationName::ObjCMultiArgSelector:
3424     AddSelectorRef(Name.getObjCSelector(), Record);
3425     break;
3426 
3427   case DeclarationName::CXXConstructorName:
3428   case DeclarationName::CXXDestructorName:
3429   case DeclarationName::CXXConversionFunctionName:
3430     AddTypeRef(Name.getCXXNameType(), Record);
3431     break;
3432 
3433   case DeclarationName::CXXOperatorName:
3434     Record.push_back(Name.getCXXOverloadedOperator());
3435     break;
3436 
3437   case DeclarationName::CXXLiteralOperatorName:
3438     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
3439     break;
3440 
3441   case DeclarationName::CXXUsingDirective:
3442     // No extra data to emit
3443     break;
3444   }
3445 }
3446 
3447 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
3448                                      DeclarationName Name, RecordDataImpl &Record) {
3449   switch (Name.getNameKind()) {
3450   case DeclarationName::CXXConstructorName:
3451   case DeclarationName::CXXDestructorName:
3452   case DeclarationName::CXXConversionFunctionName:
3453     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
3454     break;
3455 
3456   case DeclarationName::CXXOperatorName:
3457     AddSourceLocation(
3458        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
3459        Record);
3460     AddSourceLocation(
3461         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
3462         Record);
3463     break;
3464 
3465   case DeclarationName::CXXLiteralOperatorName:
3466     AddSourceLocation(
3467      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
3468      Record);
3469     break;
3470 
3471   case DeclarationName::Identifier:
3472   case DeclarationName::ObjCZeroArgSelector:
3473   case DeclarationName::ObjCOneArgSelector:
3474   case DeclarationName::ObjCMultiArgSelector:
3475   case DeclarationName::CXXUsingDirective:
3476     break;
3477   }
3478 }
3479 
3480 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3481                                        RecordDataImpl &Record) {
3482   AddDeclarationName(NameInfo.getName(), Record);
3483   AddSourceLocation(NameInfo.getLoc(), Record);
3484   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
3485 }
3486 
3487 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
3488                                  RecordDataImpl &Record) {
3489   AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
3490   Record.push_back(Info.NumTemplParamLists);
3491   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
3492     AddTemplateParameterList(Info.TemplParamLists[i], Record);
3493 }
3494 
3495 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
3496                                        RecordDataImpl &Record) {
3497   // Nested name specifiers usually aren't too long. I think that 8 would
3498   // typically accommodate the vast majority.
3499   llvm::SmallVector<NestedNameSpecifier *, 8> NestedNames;
3500 
3501   // Push each of the NNS's onto a stack for serialization in reverse order.
3502   while (NNS) {
3503     NestedNames.push_back(NNS);
3504     NNS = NNS->getPrefix();
3505   }
3506 
3507   Record.push_back(NestedNames.size());
3508   while(!NestedNames.empty()) {
3509     NNS = NestedNames.pop_back_val();
3510     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
3511     Record.push_back(Kind);
3512     switch (Kind) {
3513     case NestedNameSpecifier::Identifier:
3514       AddIdentifierRef(NNS->getAsIdentifier(), Record);
3515       break;
3516 
3517     case NestedNameSpecifier::Namespace:
3518       AddDeclRef(NNS->getAsNamespace(), Record);
3519       break;
3520 
3521     case NestedNameSpecifier::NamespaceAlias:
3522       AddDeclRef(NNS->getAsNamespaceAlias(), Record);
3523       break;
3524 
3525     case NestedNameSpecifier::TypeSpec:
3526     case NestedNameSpecifier::TypeSpecWithTemplate:
3527       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
3528       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3529       break;
3530 
3531     case NestedNameSpecifier::Global:
3532       // Don't need to write an associated value.
3533       break;
3534     }
3535   }
3536 }
3537 
3538 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3539                                           RecordDataImpl &Record) {
3540   // Nested name specifiers usually aren't too long. I think that 8 would
3541   // typically accommodate the vast majority.
3542   llvm::SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
3543 
3544   // Push each of the nested-name-specifiers's onto a stack for
3545   // serialization in reverse order.
3546   while (NNS) {
3547     NestedNames.push_back(NNS);
3548     NNS = NNS.getPrefix();
3549   }
3550 
3551   Record.push_back(NestedNames.size());
3552   while(!NestedNames.empty()) {
3553     NNS = NestedNames.pop_back_val();
3554     NestedNameSpecifier::SpecifierKind Kind
3555       = NNS.getNestedNameSpecifier()->getKind();
3556     Record.push_back(Kind);
3557     switch (Kind) {
3558     case NestedNameSpecifier::Identifier:
3559       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
3560       AddSourceRange(NNS.getLocalSourceRange(), Record);
3561       break;
3562 
3563     case NestedNameSpecifier::Namespace:
3564       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
3565       AddSourceRange(NNS.getLocalSourceRange(), Record);
3566       break;
3567 
3568     case NestedNameSpecifier::NamespaceAlias:
3569       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
3570       AddSourceRange(NNS.getLocalSourceRange(), Record);
3571       break;
3572 
3573     case NestedNameSpecifier::TypeSpec:
3574     case NestedNameSpecifier::TypeSpecWithTemplate:
3575       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
3576       AddTypeLoc(NNS.getTypeLoc(), Record);
3577       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3578       break;
3579 
3580     case NestedNameSpecifier::Global:
3581       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
3582       break;
3583     }
3584   }
3585 }
3586 
3587 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
3588   TemplateName::NameKind Kind = Name.getKind();
3589   Record.push_back(Kind);
3590   switch (Kind) {
3591   case TemplateName::Template:
3592     AddDeclRef(Name.getAsTemplateDecl(), Record);
3593     break;
3594 
3595   case TemplateName::OverloadedTemplate: {
3596     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
3597     Record.push_back(OvT->size());
3598     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
3599            I != E; ++I)
3600       AddDeclRef(*I, Record);
3601     break;
3602   }
3603 
3604   case TemplateName::QualifiedTemplate: {
3605     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
3606     AddNestedNameSpecifier(QualT->getQualifier(), Record);
3607     Record.push_back(QualT->hasTemplateKeyword());
3608     AddDeclRef(QualT->getTemplateDecl(), Record);
3609     break;
3610   }
3611 
3612   case TemplateName::DependentTemplate: {
3613     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
3614     AddNestedNameSpecifier(DepT->getQualifier(), Record);
3615     Record.push_back(DepT->isIdentifier());
3616     if (DepT->isIdentifier())
3617       AddIdentifierRef(DepT->getIdentifier(), Record);
3618     else
3619       Record.push_back(DepT->getOperator());
3620     break;
3621   }
3622 
3623   case TemplateName::SubstTemplateTemplateParmPack: {
3624     SubstTemplateTemplateParmPackStorage *SubstPack
3625       = Name.getAsSubstTemplateTemplateParmPack();
3626     AddDeclRef(SubstPack->getParameterPack(), Record);
3627     AddTemplateArgument(SubstPack->getArgumentPack(), Record);
3628     break;
3629   }
3630   }
3631 }
3632 
3633 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
3634                                     RecordDataImpl &Record) {
3635   Record.push_back(Arg.getKind());
3636   switch (Arg.getKind()) {
3637   case TemplateArgument::Null:
3638     break;
3639   case TemplateArgument::Type:
3640     AddTypeRef(Arg.getAsType(), Record);
3641     break;
3642   case TemplateArgument::Declaration:
3643     AddDeclRef(Arg.getAsDecl(), Record);
3644     break;
3645   case TemplateArgument::Integral:
3646     AddAPSInt(*Arg.getAsIntegral(), Record);
3647     AddTypeRef(Arg.getIntegralType(), Record);
3648     break;
3649   case TemplateArgument::Template:
3650     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3651     break;
3652   case TemplateArgument::TemplateExpansion:
3653     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
3654     if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
3655       Record.push_back(*NumExpansions + 1);
3656     else
3657       Record.push_back(0);
3658     break;
3659   case TemplateArgument::Expression:
3660     AddStmt(Arg.getAsExpr());
3661     break;
3662   case TemplateArgument::Pack:
3663     Record.push_back(Arg.pack_size());
3664     for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
3665            I != E; ++I)
3666       AddTemplateArgument(*I, Record);
3667     break;
3668   }
3669 }
3670 
3671 void
3672 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
3673                                     RecordDataImpl &Record) {
3674   assert(TemplateParams && "No TemplateParams!");
3675   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
3676   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
3677   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
3678   Record.push_back(TemplateParams->size());
3679   for (TemplateParameterList::const_iterator
3680          P = TemplateParams->begin(), PEnd = TemplateParams->end();
3681          P != PEnd; ++P)
3682     AddDeclRef(*P, Record);
3683 }
3684 
3685 /// \brief Emit a template argument list.
3686 void
3687 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
3688                                    RecordDataImpl &Record) {
3689   assert(TemplateArgs && "No TemplateArgs!");
3690   Record.push_back(TemplateArgs->size());
3691   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
3692     AddTemplateArgument(TemplateArgs->get(i), Record);
3693 }
3694 
3695 
3696 void
3697 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
3698   Record.push_back(Set.size());
3699   for (UnresolvedSetImpl::const_iterator
3700          I = Set.begin(), E = Set.end(); I != E; ++I) {
3701     AddDeclRef(I.getDecl(), Record);
3702     Record.push_back(I.getAccess());
3703   }
3704 }
3705 
3706 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
3707                                     RecordDataImpl &Record) {
3708   Record.push_back(Base.isVirtual());
3709   Record.push_back(Base.isBaseOfClass());
3710   Record.push_back(Base.getAccessSpecifierAsWritten());
3711   Record.push_back(Base.getInheritConstructors());
3712   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
3713   AddSourceRange(Base.getSourceRange(), Record);
3714   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
3715                                           : SourceLocation(),
3716                     Record);
3717 }
3718 
3719 void ASTWriter::FlushCXXBaseSpecifiers() {
3720   RecordData Record;
3721   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
3722     Record.clear();
3723 
3724     // Record the offset of this base-specifier set.
3725     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - FirstCXXBaseSpecifiersID;
3726     if (Index == CXXBaseSpecifiersOffsets.size())
3727       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
3728     else {
3729       if (Index > CXXBaseSpecifiersOffsets.size())
3730         CXXBaseSpecifiersOffsets.resize(Index + 1);
3731       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
3732     }
3733 
3734     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
3735                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
3736     Record.push_back(BEnd - B);
3737     for (; B != BEnd; ++B)
3738       AddCXXBaseSpecifier(*B, Record);
3739     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
3740 
3741     // Flush any expressions that were written as part of the base specifiers.
3742     FlushStmts();
3743   }
3744 
3745   CXXBaseSpecifiersToWrite.clear();
3746 }
3747 
3748 void ASTWriter::AddCXXCtorInitializers(
3749                              const CXXCtorInitializer * const *CtorInitializers,
3750                              unsigned NumCtorInitializers,
3751                              RecordDataImpl &Record) {
3752   Record.push_back(NumCtorInitializers);
3753   for (unsigned i=0; i != NumCtorInitializers; ++i) {
3754     const CXXCtorInitializer *Init = CtorInitializers[i];
3755 
3756     Record.push_back(Init->isBaseInitializer());
3757     if (Init->isBaseInitializer()) {
3758       AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
3759       Record.push_back(Init->isBaseVirtual());
3760     } else {
3761       Record.push_back(Init->isIndirectMemberInitializer());
3762       if (Init->isIndirectMemberInitializer())
3763         AddDeclRef(Init->getIndirectMember(), Record);
3764       else
3765         AddDeclRef(Init->getMember(), Record);
3766     }
3767 
3768     AddSourceLocation(Init->getMemberLocation(), Record);
3769     AddStmt(Init->getInit());
3770     AddSourceLocation(Init->getLParenLoc(), Record);
3771     AddSourceLocation(Init->getRParenLoc(), Record);
3772     Record.push_back(Init->isWritten());
3773     if (Init->isWritten()) {
3774       Record.push_back(Init->getSourceOrder());
3775     } else {
3776       Record.push_back(Init->getNumArrayIndices());
3777       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
3778         AddDeclRef(Init->getArrayIndex(i), Record);
3779     }
3780   }
3781 }
3782 
3783 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
3784   assert(D->DefinitionData);
3785   struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
3786   Record.push_back(Data.UserDeclaredConstructor);
3787   Record.push_back(Data.UserDeclaredCopyConstructor);
3788   Record.push_back(Data.UserDeclaredCopyAssignment);
3789   Record.push_back(Data.UserDeclaredDestructor);
3790   Record.push_back(Data.Aggregate);
3791   Record.push_back(Data.PlainOldData);
3792   Record.push_back(Data.Empty);
3793   Record.push_back(Data.Polymorphic);
3794   Record.push_back(Data.Abstract);
3795   Record.push_back(Data.HasTrivialConstructor);
3796   Record.push_back(Data.HasTrivialCopyConstructor);
3797   Record.push_back(Data.HasTrivialCopyAssignment);
3798   Record.push_back(Data.HasTrivialDestructor);
3799   Record.push_back(Data.ComputedVisibleConversions);
3800   Record.push_back(Data.DeclaredDefaultConstructor);
3801   Record.push_back(Data.DeclaredCopyConstructor);
3802   Record.push_back(Data.DeclaredCopyAssignment);
3803   Record.push_back(Data.DeclaredDestructor);
3804 
3805   Record.push_back(Data.NumBases);
3806   if (Data.NumBases > 0)
3807     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
3808                             Record);
3809 
3810   // FIXME: Make VBases lazily computed when needed to avoid storing them.
3811   Record.push_back(Data.NumVBases);
3812   if (Data.NumVBases > 0)
3813     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
3814                             Record);
3815 
3816   AddUnresolvedSet(Data.Conversions, Record);
3817   AddUnresolvedSet(Data.VisibleConversions, Record);
3818   // Data.Definition is the owning decl, no need to write it.
3819   AddDeclRef(Data.FirstFriend, Record);
3820 }
3821 
3822 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
3823   assert(Reader && "Cannot remove chain");
3824   assert(!Chain && "Cannot replace chain");
3825   assert(FirstDeclID == NextDeclID &&
3826          FirstTypeID == NextTypeID &&
3827          FirstIdentID == NextIdentID &&
3828          FirstSelectorID == NextSelectorID &&
3829          FirstMacroID == NextMacroID &&
3830          FirstCXXBaseSpecifiersID == NextCXXBaseSpecifiersID &&
3831          "Setting chain after writing has started.");
3832   Chain = Reader;
3833 
3834   FirstDeclID += Chain->getTotalNumDecls();
3835   FirstTypeID += Chain->getTotalNumTypes();
3836   FirstIdentID += Chain->getTotalNumIdentifiers();
3837   FirstSelectorID += Chain->getTotalNumSelectors();
3838   FirstMacroID += Chain->getTotalNumMacroDefinitions();
3839   FirstCXXBaseSpecifiersID += Chain->getTotalNumCXXBaseSpecifiers();
3840   NextDeclID = FirstDeclID;
3841   NextTypeID = FirstTypeID;
3842   NextIdentID = FirstIdentID;
3843   NextSelectorID = FirstSelectorID;
3844   NextMacroID = FirstMacroID;
3845   NextCXXBaseSpecifiersID = FirstCXXBaseSpecifiersID;
3846 }
3847 
3848 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
3849   IdentifierIDs[II] = ID;
3850   if (II->hasMacroDefinition())
3851     DeserializedMacroNames.push_back(II);
3852 }
3853 
3854 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
3855   // Always take the highest-numbered type index. This copes with an interesting
3856   // case for chained AST writing where we schedule writing the type and then,
3857   // later, deserialize the type from another AST. In this case, we want to
3858   // keep the higher-numbered entry so that we can properly write it out to
3859   // the AST file.
3860   TypeIdx &StoredIdx = TypeIdxs[T];
3861   if (Idx.getIndex() >= StoredIdx.getIndex())
3862     StoredIdx = Idx;
3863 }
3864 
3865 void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
3866   DeclIDs[D] = ID;
3867 }
3868 
3869 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
3870   SelectorIDs[S] = ID;
3871 }
3872 
3873 void ASTWriter::MacroDefinitionRead(serialization::MacroID ID,
3874                                     MacroDefinition *MD) {
3875   MacroDefinitions[MD] = ID;
3876 }
3877 
3878 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
3879   assert(D->isDefinition());
3880   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
3881     // We are interested when a PCH decl is modified.
3882     if (RD->getPCHLevel() > 0) {
3883       // A forward reference was mutated into a definition. Rewrite it.
3884       // FIXME: This happens during template instantiation, should we
3885       // have created a new definition decl instead ?
3886       RewriteDecl(RD);
3887     }
3888 
3889     for (CXXRecordDecl::redecl_iterator
3890            I = RD->redecls_begin(), E = RD->redecls_end(); I != E; ++I) {
3891       CXXRecordDecl *Redecl = cast<CXXRecordDecl>(*I);
3892       if (Redecl == RD)
3893         continue;
3894 
3895       // We are interested when a PCH decl is modified.
3896       if (Redecl->getPCHLevel() > 0) {
3897         UpdateRecord &Record = DeclUpdates[Redecl];
3898         Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
3899         assert(Redecl->DefinitionData);
3900         assert(Redecl->DefinitionData->Definition == D);
3901         AddDeclRef(D, Record); // the DefinitionDecl
3902       }
3903     }
3904   }
3905 }
3906 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
3907   // TU and namespaces are handled elsewhere.
3908   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
3909     return;
3910 
3911   if (!(D->getPCHLevel() == 0 && cast<Decl>(DC)->getPCHLevel() > 0))
3912     return; // Not a source decl added to a DeclContext from PCH.
3913 
3914   AddUpdatedDeclContext(DC);
3915 }
3916 
3917 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
3918   assert(D->isImplicit());
3919   if (!(D->getPCHLevel() == 0 && RD->getPCHLevel() > 0))
3920     return; // Not a source member added to a class from PCH.
3921   if (!isa<CXXMethodDecl>(D))
3922     return; // We are interested in lazily declared implicit methods.
3923 
3924   // A decl coming from PCH was modified.
3925   assert(RD->isDefinition());
3926   UpdateRecord &Record = DeclUpdates[RD];
3927   Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
3928   AddDeclRef(D, Record);
3929 }
3930 
3931 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
3932                                      const ClassTemplateSpecializationDecl *D) {
3933   // The specializations set is kept in the canonical template.
3934   TD = TD->getCanonicalDecl();
3935   if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
3936     return; // Not a source specialization added to a template from PCH.
3937 
3938   UpdateRecord &Record = DeclUpdates[TD];
3939   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
3940   AddDeclRef(D, Record);
3941 }
3942 
3943 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
3944                                                const FunctionDecl *D) {
3945   // The specializations set is kept in the canonical template.
3946   TD = TD->getCanonicalDecl();
3947   if (!(D->getPCHLevel() == 0 && TD->getPCHLevel() > 0))
3948     return; // Not a source specialization added to a template from PCH.
3949 
3950   UpdateRecord &Record = DeclUpdates[TD];
3951   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
3952   AddDeclRef(D, Record);
3953 }
3954 
3955 ASTSerializationListener::~ASTSerializationListener() { }
3956