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