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