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