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