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