blob: 1cf98cea9ca89ec0c6e454c30a244ac43ee39e45 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
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 PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclContextInternals.h"
18#include "clang/AST/DeclVisitor.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/StmtVisitor.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000024#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000028#include "llvm/Bitcode/BitstreamWriter.h"
29#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000030#include "llvm/Support/MemoryBuffer.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000031#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000032using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Type serialization
36//===----------------------------------------------------------------------===//
37namespace {
38 class VISIBILITY_HIDDEN PCHTypeWriter {
39 PCHWriter &Writer;
40 PCHWriter::RecordData &Record;
41
42 public:
43 /// \brief Type code that corresponds to the record generated.
44 pch::TypeCode Code;
45
46 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
47 : Writer(Writer), Record(Record) { }
48
49 void VisitArrayType(const ArrayType *T);
50 void VisitFunctionType(const FunctionType *T);
51 void VisitTagType(const TagType *T);
52
53#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
54#define ABSTRACT_TYPE(Class, Base)
55#define DEPENDENT_TYPE(Class, Base)
56#include "clang/AST/TypeNodes.def"
57 };
58}
59
60void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
61 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
62 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
63 Record.push_back(T->getAddressSpace());
64 Code = pch::TYPE_EXT_QUAL;
65}
66
67void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
68 assert(false && "Built-in types are never serialized");
69}
70
71void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
72 Record.push_back(T->getWidth());
73 Record.push_back(T->isSigned());
74 Code = pch::TYPE_FIXED_WIDTH_INT;
75}
76
77void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
78 Writer.AddTypeRef(T->getElementType(), Record);
79 Code = pch::TYPE_COMPLEX;
80}
81
82void PCHTypeWriter::VisitPointerType(const PointerType *T) {
83 Writer.AddTypeRef(T->getPointeeType(), Record);
84 Code = pch::TYPE_POINTER;
85}
86
87void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
88 Writer.AddTypeRef(T->getPointeeType(), Record);
89 Code = pch::TYPE_BLOCK_POINTER;
90}
91
92void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_LVALUE_REFERENCE;
95}
96
97void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Code = pch::TYPE_RVALUE_REFERENCE;
100}
101
102void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
105 Code = pch::TYPE_MEMBER_POINTER;
106}
107
108void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
109 Writer.AddTypeRef(T->getElementType(), Record);
110 Record.push_back(T->getSizeModifier()); // FIXME: stable values
111 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
112}
113
114void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
115 VisitArrayType(T);
116 Writer.AddAPInt(T->getSize(), Record);
117 Code = pch::TYPE_CONSTANT_ARRAY;
118}
119
120void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
121 VisitArrayType(T);
122 Code = pch::TYPE_INCOMPLETE_ARRAY;
123}
124
125void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
126 VisitArrayType(T);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000127 Writer.AddExpr(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000128 Code = pch::TYPE_VARIABLE_ARRAY;
129}
130
131void PCHTypeWriter::VisitVectorType(const VectorType *T) {
132 Writer.AddTypeRef(T->getElementType(), Record);
133 Record.push_back(T->getNumElements());
134 Code = pch::TYPE_VECTOR;
135}
136
137void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
138 VisitVectorType(T);
139 Code = pch::TYPE_EXT_VECTOR;
140}
141
142void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
143 Writer.AddTypeRef(T->getResultType(), Record);
144}
145
146void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
147 VisitFunctionType(T);
148 Code = pch::TYPE_FUNCTION_NO_PROTO;
149}
150
151void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
152 VisitFunctionType(T);
153 Record.push_back(T->getNumArgs());
154 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
155 Writer.AddTypeRef(T->getArgType(I), Record);
156 Record.push_back(T->isVariadic());
157 Record.push_back(T->getTypeQuals());
158 Code = pch::TYPE_FUNCTION_PROTO;
159}
160
161void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
162 Writer.AddDeclRef(T->getDecl(), Record);
163 Code = pch::TYPE_TYPEDEF;
164}
165
166void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000167 Writer.AddExpr(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000168 Code = pch::TYPE_TYPEOF_EXPR;
169}
170
171void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
172 Writer.AddTypeRef(T->getUnderlyingType(), Record);
173 Code = pch::TYPE_TYPEOF;
174}
175
176void PCHTypeWriter::VisitTagType(const TagType *T) {
177 Writer.AddDeclRef(T->getDecl(), Record);
178 assert(!T->isBeingDefined() &&
179 "Cannot serialize in the middle of a type definition");
180}
181
182void PCHTypeWriter::VisitRecordType(const RecordType *T) {
183 VisitTagType(T);
184 Code = pch::TYPE_RECORD;
185}
186
187void PCHTypeWriter::VisitEnumType(const EnumType *T) {
188 VisitTagType(T);
189 Code = pch::TYPE_ENUM;
190}
191
192void
193PCHTypeWriter::VisitTemplateSpecializationType(
194 const TemplateSpecializationType *T) {
195 // FIXME: Serialize this type
196 assert(false && "Cannot serialize template specialization types");
197}
198
199void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
200 // FIXME: Serialize this type
201 assert(false && "Cannot serialize qualified name types");
202}
203
204void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
205 Writer.AddDeclRef(T->getDecl(), Record);
206 Code = pch::TYPE_OBJC_INTERFACE;
207}
208
209void
210PCHTypeWriter::VisitObjCQualifiedInterfaceType(
211 const ObjCQualifiedInterfaceType *T) {
212 VisitObjCInterfaceType(T);
213 Record.push_back(T->getNumProtocols());
214 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
215 Writer.AddDeclRef(T->getProtocol(I), Record);
216 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
217}
218
219void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
220 Record.push_back(T->getNumProtocols());
221 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
222 Writer.AddDeclRef(T->getProtocols(I), Record);
223 Code = pch::TYPE_OBJC_QUALIFIED_ID;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
228 Record.push_back(T->getNumProtocols());
229 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
230 Writer.AddDeclRef(T->getProtocols(I), Record);
231 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
232}
233
234//===----------------------------------------------------------------------===//
235// Declaration serialization
236//===----------------------------------------------------------------------===//
237namespace {
238 class VISIBILITY_HIDDEN PCHDeclWriter
239 : public DeclVisitor<PCHDeclWriter, void> {
240
241 PCHWriter &Writer;
242 PCHWriter::RecordData &Record;
243
244 public:
245 pch::DeclCode Code;
246
247 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
248 : Writer(Writer), Record(Record) { }
249
250 void VisitDecl(Decl *D);
251 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
252 void VisitNamedDecl(NamedDecl *D);
253 void VisitTypeDecl(TypeDecl *D);
254 void VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000255 void VisitTagDecl(TagDecl *D);
256 void VisitEnumDecl(EnumDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000257 void VisitRecordDecl(RecordDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000258 void VisitValueDecl(ValueDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000259 void VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000260 void VisitFunctionDecl(FunctionDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000261 void VisitFieldDecl(FieldDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000262 void VisitVarDecl(VarDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000263 void VisitParmVarDecl(ParmVarDecl *D);
264 void VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor2a491792009-04-13 22:49:25 +0000265 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
266 void VisitBlockDecl(BlockDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000267 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
268 uint64_t VisibleOffset);
269 };
270}
271
272void PCHDeclWriter::VisitDecl(Decl *D) {
273 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
274 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
275 Writer.AddSourceLocation(D->getLocation(), Record);
276 Record.push_back(D->isInvalidDecl());
277 // FIXME: hasAttrs
278 Record.push_back(D->isImplicit());
279 Record.push_back(D->getAccess());
280}
281
282void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
283 VisitDecl(D);
284 Code = pch::DECL_TRANSLATION_UNIT;
285}
286
287void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
288 VisitDecl(D);
289 Writer.AddDeclarationName(D->getDeclName(), Record);
290}
291
292void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
293 VisitNamedDecl(D);
294 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
295}
296
297void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
298 VisitTypeDecl(D);
299 Writer.AddTypeRef(D->getUnderlyingType(), Record);
300 Code = pch::DECL_TYPEDEF;
301}
302
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000303void PCHDeclWriter::VisitTagDecl(TagDecl *D) {
304 VisitTypeDecl(D);
305 Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
306 Record.push_back(D->isDefinition());
307 Writer.AddDeclRef(D->getTypedefForAnonDecl(), Record);
308}
309
310void PCHDeclWriter::VisitEnumDecl(EnumDecl *D) {
311 VisitTagDecl(D);
312 Writer.AddTypeRef(D->getIntegerType(), Record);
313 Code = pch::DECL_ENUM;
314}
315
Douglas Gregor982365e2009-04-13 21:20:57 +0000316void PCHDeclWriter::VisitRecordDecl(RecordDecl *D) {
317 VisitTagDecl(D);
318 Record.push_back(D->hasFlexibleArrayMember());
319 Record.push_back(D->isAnonymousStructOrUnion());
320 Code = pch::DECL_RECORD;
321}
322
Douglas Gregorc34897d2009-04-09 22:27:44 +0000323void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
324 VisitNamedDecl(D);
325 Writer.AddTypeRef(D->getType(), Record);
326}
327
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000328void PCHDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
329 VisitValueDecl(D);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000330 Record.push_back(D->getInitExpr()? 1 : 0);
331 if (D->getInitExpr())
332 Writer.AddExpr(D->getInitExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000333 Writer.AddAPSInt(D->getInitVal(), Record);
334 Code = pch::DECL_ENUM_CONSTANT;
335}
336
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000337void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
338 VisitValueDecl(D);
339 // FIXME: function body
340 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
341 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
342 Record.push_back(D->isInline());
343 Record.push_back(D->isVirtual());
344 Record.push_back(D->isPure());
345 Record.push_back(D->inheritedPrototype());
346 Record.push_back(D->hasPrototype() && !D->inheritedPrototype());
347 Record.push_back(D->isDeleted());
348 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
349 Record.push_back(D->param_size());
350 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
351 P != PEnd; ++P)
352 Writer.AddDeclRef(*P, Record);
353 Code = pch::DECL_FUNCTION;
354}
355
Douglas Gregor982365e2009-04-13 21:20:57 +0000356void PCHDeclWriter::VisitFieldDecl(FieldDecl *D) {
357 VisitValueDecl(D);
358 Record.push_back(D->isMutable());
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000359 Record.push_back(D->getBitWidth()? 1 : 0);
360 if (D->getBitWidth())
361 Writer.AddExpr(D->getBitWidth());
Douglas Gregor982365e2009-04-13 21:20:57 +0000362 Code = pch::DECL_FIELD;
363}
364
Douglas Gregorc34897d2009-04-09 22:27:44 +0000365void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
366 VisitValueDecl(D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000367 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
Douglas Gregorc34897d2009-04-09 22:27:44 +0000368 Record.push_back(D->isThreadSpecified());
369 Record.push_back(D->hasCXXDirectInitializer());
370 Record.push_back(D->isDeclaredInCondition());
371 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
372 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000373 Record.push_back(D->getInit()? 1 : 0);
374 if (D->getInit())
375 Writer.AddExpr(D->getInit());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000376 Code = pch::DECL_VAR;
377}
378
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000379void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
380 VisitVarDecl(D);
381 Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
382 // FIXME: emit default argument
383 // FIXME: why isn't the "default argument" just stored as the initializer
384 // in VarDecl?
385 Code = pch::DECL_PARM_VAR;
386}
387
388void PCHDeclWriter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
389 VisitParmVarDecl(D);
390 Writer.AddTypeRef(D->getOriginalType(), Record);
391 Code = pch::DECL_ORIGINAL_PARM_VAR;
392}
393
Douglas Gregor2a491792009-04-13 22:49:25 +0000394void PCHDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
395 VisitDecl(D);
396 // FIXME: Emit the string literal
397 Code = pch::DECL_FILE_SCOPE_ASM;
398}
399
400void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) {
401 VisitDecl(D);
402 // FIXME: emit block body
403 Record.push_back(D->param_size());
404 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
405 P != PEnd; ++P)
406 Writer.AddDeclRef(*P, Record);
407 Code = pch::DECL_BLOCK;
408}
409
Douglas Gregorc34897d2009-04-09 22:27:44 +0000410/// \brief Emit the DeclContext part of a declaration context decl.
411///
412/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
413/// block for this declaration context is stored. May be 0 to indicate
414/// that there are no declarations stored within this context.
415///
416/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
417/// block for this declaration context is stored. May be 0 to indicate
418/// that there are no declarations visible from this context. Note
419/// that this value will not be emitted for non-primary declaration
420/// contexts.
421void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
422 uint64_t VisibleOffset) {
423 Record.push_back(LexicalOffset);
424 if (DC->getPrimaryContext() == DC)
425 Record.push_back(VisibleOffset);
426}
427
428//===----------------------------------------------------------------------===//
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000429// Statement/expression serialization
430//===----------------------------------------------------------------------===//
431namespace {
432 class VISIBILITY_HIDDEN PCHStmtWriter
433 : public StmtVisitor<PCHStmtWriter, void> {
434
435 PCHWriter &Writer;
436 PCHWriter::RecordData &Record;
437
438 public:
439 pch::StmtCode Code;
440
441 PCHStmtWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
442 : Writer(Writer), Record(Record) { }
443
444 void VisitExpr(Expr *E);
445 void VisitDeclRefExpr(DeclRefExpr *E);
446 void VisitIntegerLiteral(IntegerLiteral *E);
447 void VisitCharacterLiteral(CharacterLiteral *E);
448 };
449}
450
451void PCHStmtWriter::VisitExpr(Expr *E) {
452 Writer.AddTypeRef(E->getType(), Record);
453 Record.push_back(E->isTypeDependent());
454 Record.push_back(E->isValueDependent());
455}
456
457void PCHStmtWriter::VisitDeclRefExpr(DeclRefExpr *E) {
458 VisitExpr(E);
459 Writer.AddDeclRef(E->getDecl(), Record);
460 Writer.AddSourceLocation(E->getLocation(), Record);
461 Code = pch::EXPR_DECL_REF;
462}
463
464void PCHStmtWriter::VisitIntegerLiteral(IntegerLiteral *E) {
465 VisitExpr(E);
466 Writer.AddSourceLocation(E->getLocation(), Record);
467 Writer.AddAPInt(E->getValue(), Record);
468 Code = pch::EXPR_INTEGER_LITERAL;
469}
470
471void PCHStmtWriter::VisitCharacterLiteral(CharacterLiteral *E) {
472 VisitExpr(E);
473 Record.push_back(E->getValue());
474 Writer.AddSourceLocation(E->getLoc(), Record);
475 Record.push_back(E->isWide());
476 Code = pch::EXPR_CHARACTER_LITERAL;
477}
478
479//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000480// PCHWriter Implementation
481//===----------------------------------------------------------------------===//
482
Douglas Gregorb5887f32009-04-10 21:16:55 +0000483/// \brief Write the target triple (e.g., i686-apple-darwin9).
484void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
485 using namespace llvm;
486 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
487 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
488 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
489 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
490
491 RecordData Record;
492 Record.push_back(pch::TARGET_TRIPLE);
493 const char *Triple = Target.getTargetTriple();
494 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
495}
496
497/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000498void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
499 RecordData Record;
500 Record.push_back(LangOpts.Trigraphs);
501 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
502 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
503 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
504 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
505 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
506 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
507 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
508 Record.push_back(LangOpts.C99); // C99 Support
509 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
510 Record.push_back(LangOpts.CPlusPlus); // C++ Support
511 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
512 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
513 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
514
515 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
516 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
517 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
518
519 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
520 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
521 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
522 Record.push_back(LangOpts.LaxVectorConversions);
523 Record.push_back(LangOpts.Exceptions); // Support exception handling.
524
525 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
526 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
527 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
528
529 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
530 // by locks.
531 Record.push_back(LangOpts.Blocks); // block extension to C
532 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
533 // they are unused.
534 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
535 // (modulo the platform support).
536
537 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
538 // signed integer arithmetic overflows.
539
540 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
541 // may be ripped out at any time.
542
543 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
544 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
545 // defined.
546 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
547 // opposed to __DYNAMIC__).
548 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
549
550 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
551 // used (instead of C99 semantics).
552 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
553 Record.push_back(LangOpts.getGCMode());
554 Record.push_back(LangOpts.getVisibilityMode());
555 Record.push_back(LangOpts.InstantiationDepth);
556 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
557}
558
Douglas Gregorab1cef72009-04-10 03:52:48 +0000559//===----------------------------------------------------------------------===//
560// Source Manager Serialization
561//===----------------------------------------------------------------------===//
562
563/// \brief Create an abbreviation for the SLocEntry that refers to a
564/// file.
565static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
566 using namespace llvm;
567 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
568 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
572 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000573 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
574 return S.EmitAbbrev(Abbrev);
575}
576
577/// \brief Create an abbreviation for the SLocEntry that refers to a
578/// buffer.
579static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
580 using namespace llvm;
581 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
582 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
583 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
585 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
586 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
587 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
588 return S.EmitAbbrev(Abbrev);
589}
590
591/// \brief Create an abbreviation for the SLocEntry that refers to a
592/// buffer's blob.
593static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
594 using namespace llvm;
595 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
596 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
598 return S.EmitAbbrev(Abbrev);
599}
600
601/// \brief Create an abbreviation for the SLocEntry that refers to an
602/// buffer.
603static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
604 using namespace llvm;
605 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
606 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
609 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
611 return S.EmitAbbrev(Abbrev);
612}
613
614/// \brief Writes the block containing the serialized form of the
615/// source manager.
616///
617/// TODO: We should probably use an on-disk hash table (stored in a
618/// blob), indexed based on the file name, so that we only create
619/// entries for files that we actually need. In the common case (no
620/// errors), we probably won't have to create file entries for any of
621/// the files in the AST.
622void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000623 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000624 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
625
626 // Abbreviations for the various kinds of source-location entries.
627 int SLocFileAbbrv = -1;
628 int SLocBufferAbbrv = -1;
629 int SLocBufferBlobAbbrv = -1;
630 int SLocInstantiationAbbrv = -1;
631
632 // Write out the source location entry table. We skip the first
633 // entry, which is always the same dummy entry.
634 RecordData Record;
635 for (SourceManager::sloc_entry_iterator
636 SLoc = SourceMgr.sloc_entry_begin() + 1,
637 SLocEnd = SourceMgr.sloc_entry_end();
638 SLoc != SLocEnd; ++SLoc) {
639 // Figure out which record code to use.
640 unsigned Code;
641 if (SLoc->isFile()) {
642 if (SLoc->getFile().getContentCache()->Entry)
643 Code = pch::SM_SLOC_FILE_ENTRY;
644 else
645 Code = pch::SM_SLOC_BUFFER_ENTRY;
646 } else
647 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
648 Record.push_back(Code);
649
650 Record.push_back(SLoc->getOffset());
651 if (SLoc->isFile()) {
652 const SrcMgr::FileInfo &File = SLoc->getFile();
653 Record.push_back(File.getIncludeLoc().getRawEncoding());
654 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
Douglas Gregor635f97f2009-04-13 16:31:14 +0000655 Record.push_back(File.hasLineDirectives());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000656
657 const SrcMgr::ContentCache *Content = File.getContentCache();
658 if (Content->Entry) {
659 // The source location entry is a file. The blob associated
660 // with this entry is the file name.
661 if (SLocFileAbbrv == -1)
662 SLocFileAbbrv = CreateSLocFileAbbrev(S);
663 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
664 Content->Entry->getName(),
665 strlen(Content->Entry->getName()));
666 } else {
667 // The source location entry is a buffer. The blob associated
668 // with this entry contains the contents of the buffer.
669 if (SLocBufferAbbrv == -1) {
670 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
671 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
672 }
673
674 // We add one to the size so that we capture the trailing NULL
675 // that is required by llvm::MemoryBuffer::getMemBuffer (on
676 // the reader side).
677 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
678 const char *Name = Buffer->getBufferIdentifier();
679 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
680 Record.clear();
681 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
682 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
683 Buffer->getBufferStart(),
684 Buffer->getBufferSize() + 1);
685 }
686 } else {
687 // The source location entry is an instantiation.
688 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
689 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
690 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
691 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
692
693 if (SLocInstantiationAbbrv == -1)
694 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
695 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
696 }
697
698 Record.clear();
699 }
700
Douglas Gregor635f97f2009-04-13 16:31:14 +0000701 // Write the line table.
702 if (SourceMgr.hasLineTable()) {
703 LineTableInfo &LineTable = SourceMgr.getLineTable();
704
705 // Emit the file names
706 Record.push_back(LineTable.getNumFilenames());
707 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
708 // Emit the file name
709 const char *Filename = LineTable.getFilename(I);
710 unsigned FilenameLen = Filename? strlen(Filename) : 0;
711 Record.push_back(FilenameLen);
712 if (FilenameLen)
713 Record.insert(Record.end(), Filename, Filename + FilenameLen);
714 }
715
716 // Emit the line entries
717 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
718 L != LEnd; ++L) {
719 // Emit the file ID
720 Record.push_back(L->first);
721
722 // Emit the line entries
723 Record.push_back(L->second.size());
724 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
725 LEEnd = L->second.end();
726 LE != LEEnd; ++LE) {
727 Record.push_back(LE->FileOffset);
728 Record.push_back(LE->LineNo);
729 Record.push_back(LE->FilenameID);
730 Record.push_back((unsigned)LE->FileKind);
731 Record.push_back(LE->IncludeOffset);
732 }
733 S.EmitRecord(pch::SM_LINE_TABLE, Record);
734 }
735 }
736
Douglas Gregorab1cef72009-04-10 03:52:48 +0000737 S.ExitBlock();
738}
739
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000740/// \brief Writes the block containing the serialized form of the
741/// preprocessor.
742///
Chris Lattner850eabd2009-04-10 18:08:30 +0000743void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000744 // Enter the preprocessor block.
745 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
746
Chris Lattner1b094952009-04-10 18:00:12 +0000747 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
748 // FIXME: use diagnostics subsystem for localization etc.
749 if (PP.SawDateOrTime())
750 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000751
Chris Lattner1b094952009-04-10 18:00:12 +0000752 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000753
Chris Lattner4b21c202009-04-13 01:29:17 +0000754 // If the preprocessor __COUNTER__ value has been bumped, remember it.
755 if (PP.getCounterValue() != 0) {
756 Record.push_back(PP.getCounterValue());
757 S.EmitRecord(pch::PP_COUNTER_VALUE, Record);
758 Record.clear();
759 }
760
Chris Lattner1b094952009-04-10 18:00:12 +0000761 // Loop over all the macro definitions that are live at the end of the file,
762 // emitting each to the PP section.
763 // FIXME: Eventually we want to emit an index so that we can lazily load
764 // macros.
765 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
766 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000767 // FIXME: This emits macros in hash table order, we should do it in a stable
768 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000769 MacroInfo *MI = I->second;
770
771 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
772 // been redefined by the header (in which case they are not isBuiltinMacro).
773 if (MI->isBuiltinMacro())
774 continue;
775
Chris Lattner29241862009-04-11 21:15:38 +0000776 AddIdentifierRef(I->first, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000777 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
778 Record.push_back(MI->isUsed());
779
780 unsigned Code;
781 if (MI->isObjectLike()) {
782 Code = pch::PP_MACRO_OBJECT_LIKE;
783 } else {
784 Code = pch::PP_MACRO_FUNCTION_LIKE;
785
786 Record.push_back(MI->isC99Varargs());
787 Record.push_back(MI->isGNUVarargs());
788 Record.push_back(MI->getNumArgs());
789 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
790 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000791 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000792 }
793 S.EmitRecord(Code, Record);
794 Record.clear();
795
Chris Lattner850eabd2009-04-10 18:08:30 +0000796 // Emit the tokens array.
797 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
798 // Note that we know that the preprocessor does not have any annotation
799 // tokens in it because they are created by the parser, and thus can't be
800 // in a macro definition.
801 const Token &Tok = MI->getReplacementToken(TokNo);
802
803 Record.push_back(Tok.getLocation().getRawEncoding());
804 Record.push_back(Tok.getLength());
805
Chris Lattner850eabd2009-04-10 18:08:30 +0000806 // FIXME: When reading literal tokens, reconstruct the literal pointer if
807 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000808 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000809
810 // FIXME: Should translate token kind to a stable encoding.
811 Record.push_back(Tok.getKind());
812 // FIXME: Should translate token flags to a stable encoding.
813 Record.push_back(Tok.getFlags());
814
815 S.EmitRecord(pch::PP_TOKEN, Record);
816 Record.clear();
817 }
Chris Lattner1b094952009-04-10 18:00:12 +0000818
819 }
820
Chris Lattner84b04f12009-04-10 17:16:57 +0000821 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000822}
823
824
Douglas Gregorc34897d2009-04-09 22:27:44 +0000825/// \brief Write the representation of a type to the PCH stream.
826void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000827 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000828 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000829 ID = NextTypeID++;
830
831 // Record the offset for this type.
832 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
833 TypeOffsets.push_back(S.GetCurrentBitNo());
834 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
835 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
836 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
837 }
838
839 RecordData Record;
840
841 // Emit the type's representation.
842 PCHTypeWriter W(*this, Record);
843 switch (T->getTypeClass()) {
844 // For all of the concrete, non-dependent types, call the
845 // appropriate visitor function.
846#define TYPE(Class, Base) \
847 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
848#define ABSTRACT_TYPE(Class, Base)
849#define DEPENDENT_TYPE(Class, Base)
850#include "clang/AST/TypeNodes.def"
851
852 // For all of the dependent type nodes (which only occur in C++
853 // templates), produce an error.
854#define TYPE(Class, Base)
855#define DEPENDENT_TYPE(Class, Base) case Type::Class:
856#include "clang/AST/TypeNodes.def"
857 assert(false && "Cannot serialize dependent type nodes");
858 break;
859 }
860
861 // Emit the serialized record.
862 S.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000863
864 // Flush any expressions that were written as part of this type.
865 FlushExprs();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000866}
867
868/// \brief Write a block containing all of the types.
869void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000870 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000871 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
872
873 // Emit all of the types in the ASTContext
874 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
875 TEnd = Context.getTypes().end();
876 T != TEnd; ++T) {
877 // Builtin types are never serialized.
878 if (isa<BuiltinType>(*T))
879 continue;
880
881 WriteType(*T);
882 }
883
884 // Exit the types block
885 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000886}
887
888/// \brief Write the block containing all of the declaration IDs
889/// lexically declared within the given DeclContext.
890///
891/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
892/// bistream, or 0 if no block was written.
893uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
894 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000895 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000896 return 0;
897
898 uint64_t Offset = S.GetCurrentBitNo();
899 RecordData Record;
900 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
901 DEnd = DC->decls_end(Context);
902 D != DEnd; ++D)
903 AddDeclRef(*D, Record);
904
905 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
906 return Offset;
907}
908
909/// \brief Write the block containing all of the declaration IDs
910/// visible from the given DeclContext.
911///
912/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
913/// bistream, or 0 if no block was written.
914uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
915 DeclContext *DC) {
916 if (DC->getPrimaryContext() != DC)
917 return 0;
918
919 // Force the DeclContext to build a its name-lookup table.
920 DC->lookup(Context, DeclarationName());
921
922 // Serialize the contents of the mapping used for lookup. Note that,
923 // although we have two very different code paths, the serialized
924 // representation is the same for both cases: a declaration name,
925 // followed by a size, followed by references to the visible
926 // declarations that have that name.
927 uint64_t Offset = S.GetCurrentBitNo();
928 RecordData Record;
929 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000930 if (!Map)
931 return 0;
932
Douglas Gregorc34897d2009-04-09 22:27:44 +0000933 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
934 D != DEnd; ++D) {
935 AddDeclarationName(D->first, Record);
936 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
937 Record.push_back(Result.second - Result.first);
938 for(; Result.first != Result.second; ++Result.first)
939 AddDeclRef(*Result.first, Record);
940 }
941
942 if (Record.size() == 0)
943 return 0;
944
945 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
946 return Offset;
947}
948
949/// \brief Write a block containing all of the declarations.
950void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000951 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000952 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
953
954 // Emit all of the declarations.
955 RecordData Record;
956 PCHDeclWriter W(*this, Record);
957 while (!DeclsToEmit.empty()) {
958 // Pull the next declaration off the queue
959 Decl *D = DeclsToEmit.front();
960 DeclsToEmit.pop();
961
962 // If this declaration is also a DeclContext, write blocks for the
963 // declarations that lexically stored inside its context and those
964 // declarations that are visible from its context. These blocks
965 // are written before the declaration itself so that we can put
966 // their offsets into the record for the declaration.
967 uint64_t LexicalOffset = 0;
968 uint64_t VisibleOffset = 0;
969 DeclContext *DC = dyn_cast<DeclContext>(D);
970 if (DC) {
971 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
972 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
973 }
974
975 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +0000976 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +0000977 if (ID == 0)
978 ID = DeclIDs.size();
979
980 unsigned Index = ID - 1;
981
982 // Record the offset for this declaration
983 if (DeclOffsets.size() == Index)
984 DeclOffsets.push_back(S.GetCurrentBitNo());
985 else if (DeclOffsets.size() < Index) {
986 DeclOffsets.resize(Index+1);
987 DeclOffsets[Index] = S.GetCurrentBitNo();
988 }
989
990 // Build and emit a record for this declaration
991 Record.clear();
992 W.Code = (pch::DeclCode)0;
993 W.Visit(D);
994 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
Douglas Gregor631f6c62009-04-14 00:24:19 +0000995 assert(W.Code && "Unhandled declaration kind while generating PCH");
Douglas Gregorc34897d2009-04-09 22:27:44 +0000996 S.EmitRecord(W.Code, Record);
Douglas Gregor631f6c62009-04-14 00:24:19 +0000997
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000998 // Flush any expressions that were written as part of this declaration.
999 FlushExprs();
1000
Douglas Gregor631f6c62009-04-14 00:24:19 +00001001 // Note external declarations so that we can add them to a record
1002 // in the PCH file later.
1003 if (isa<FileScopeAsmDecl>(D))
1004 ExternalDefinitions.push_back(ID);
1005 else if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
1006 if (// Non-static file-scope variables with initializers or that
1007 // are tentative definitions.
1008 (Var->isFileVarDecl() &&
1009 (Var->getInit() || Var->getStorageClass() == VarDecl::None)) ||
1010 // Out-of-line definitions of static data members (C++).
1011 (Var->getDeclContext()->isRecord() &&
1012 !Var->getLexicalDeclContext()->isRecord() &&
1013 Var->getStorageClass() == VarDecl::Static))
1014 ExternalDefinitions.push_back(ID);
1015 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1016 if (Func->isThisDeclarationADefinition() &&
1017 Func->getStorageClass() != FunctionDecl::Static &&
1018 !Func->isInline())
1019 ExternalDefinitions.push_back(ID);
1020 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001021 }
1022
1023 // Exit the declarations block
1024 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001025}
1026
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001027/// \brief Write the identifier table into the PCH file.
1028///
1029/// The identifier table consists of a blob containing string data
1030/// (the actual identifiers themselves) and a separate "offsets" index
1031/// that maps identifier IDs to locations within the blob.
1032void PCHWriter::WriteIdentifierTable() {
1033 using namespace llvm;
1034
1035 // Create and write out the blob that contains the identifier
1036 // strings.
1037 RecordData IdentOffsets;
1038 IdentOffsets.resize(IdentifierIDs.size());
1039 {
1040 // Create the identifier string data.
1041 std::vector<char> Data;
1042 Data.push_back(0); // Data must not be empty.
1043 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1044 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1045 ID != IDEnd; ++ID) {
1046 assert(ID->first && "NULL identifier in identifier table");
1047
1048 // Make sure we're starting on an odd byte. The PCH reader
1049 // expects the low bit to be set on all of the offsets.
1050 if ((Data.size() & 0x01) == 0)
1051 Data.push_back((char)0);
1052
1053 IdentOffsets[ID->second - 1] = Data.size();
1054 Data.insert(Data.end(),
1055 ID->first->getName(),
1056 ID->first->getName() + ID->first->getLength());
1057 Data.push_back((char)0);
1058 }
1059
1060 // Create a blob abbreviation
1061 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1062 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
1063 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
1064 unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev);
1065
1066 // Write the identifier table
1067 RecordData Record;
1068 Record.push_back(pch::IDENTIFIER_TABLE);
1069 S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size());
1070 }
1071
1072 // Write the offsets table for identifier IDs.
1073 S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets);
1074}
1075
Douglas Gregorc34897d2009-04-09 22:27:44 +00001076PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
1077 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
1078
Chris Lattner850eabd2009-04-10 18:08:30 +00001079void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001080 // Emit the file header.
1081 S.Emit((unsigned)'C', 8);
1082 S.Emit((unsigned)'P', 8);
1083 S.Emit((unsigned)'C', 8);
1084 S.Emit((unsigned)'H', 8);
1085
1086 // The translation unit is the first declaration we'll emit.
1087 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1088 DeclsToEmit.push(Context.getTranslationUnitDecl());
1089
1090 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +00001091 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
1092 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001093 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001094 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001095 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001096 WriteTypesBlock(Context);
1097 WriteDeclsBlock(Context);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001098 WriteIdentifierTable();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001099 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
1100 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001101 if (!ExternalDefinitions.empty())
1102 S.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001103 S.ExitBlock();
1104}
1105
1106void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1107 Record.push_back(Loc.getRawEncoding());
1108}
1109
1110void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1111 Record.push_back(Value.getBitWidth());
1112 unsigned N = Value.getNumWords();
1113 const uint64_t* Words = Value.getRawData();
1114 for (unsigned I = 0; I != N; ++I)
1115 Record.push_back(Words[I]);
1116}
1117
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001118void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1119 Record.push_back(Value.isUnsigned());
1120 AddAPInt(Value, Record);
1121}
1122
Douglas Gregorc34897d2009-04-09 22:27:44 +00001123void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001124 if (II == 0) {
1125 Record.push_back(0);
1126 return;
1127 }
1128
1129 pch::IdentID &ID = IdentifierIDs[II];
1130 if (ID == 0)
1131 ID = IdentifierIDs.size();
1132
1133 Record.push_back(ID);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001134}
1135
1136void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1137 if (T.isNull()) {
1138 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1139 return;
1140 }
1141
1142 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001143 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001144 switch (BT->getKind()) {
1145 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1146 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1147 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1148 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1149 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1150 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1151 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1152 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1153 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1154 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1155 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1156 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1157 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1158 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1159 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1160 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1161 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1162 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1163 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1164 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1165 }
1166
1167 Record.push_back((ID << 3) | T.getCVRQualifiers());
1168 return;
1169 }
1170
Douglas Gregorac8f2802009-04-10 17:25:41 +00001171 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001172 if (ID == 0) // we haven't seen this type before
1173 ID = NextTypeID++;
1174
1175 // Encode the type qualifiers in the type reference.
1176 Record.push_back((ID << 3) | T.getCVRQualifiers());
1177}
1178
1179void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1180 if (D == 0) {
1181 Record.push_back(0);
1182 return;
1183 }
1184
Douglas Gregorac8f2802009-04-10 17:25:41 +00001185 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001186 if (ID == 0) {
1187 // We haven't seen this declaration before. Give it a new ID and
1188 // enqueue it in the list of declarations to emit.
1189 ID = DeclIDs.size();
1190 DeclsToEmit.push(const_cast<Decl *>(D));
1191 }
1192
1193 Record.push_back(ID);
1194}
1195
1196void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
1197 Record.push_back(Name.getNameKind());
1198 switch (Name.getNameKind()) {
1199 case DeclarationName::Identifier:
1200 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1201 break;
1202
1203 case DeclarationName::ObjCZeroArgSelector:
1204 case DeclarationName::ObjCOneArgSelector:
1205 case DeclarationName::ObjCMultiArgSelector:
1206 assert(false && "Serialization of Objective-C selectors unavailable");
1207 break;
1208
1209 case DeclarationName::CXXConstructorName:
1210 case DeclarationName::CXXDestructorName:
1211 case DeclarationName::CXXConversionFunctionName:
1212 AddTypeRef(Name.getCXXNameType(), Record);
1213 break;
1214
1215 case DeclarationName::CXXOperatorName:
1216 Record.push_back(Name.getCXXOverloadedOperator());
1217 break;
1218
1219 case DeclarationName::CXXUsingDirective:
1220 // No extra data to emit
1221 break;
1222 }
1223}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001224
1225/// \brief Flush all of the expressions that have been added to the
1226/// queue via AddExpr().
1227void PCHWriter::FlushExprs() {
1228 RecordData Record;
1229 PCHStmtWriter Writer(*this, Record);
1230 while (!ExprsToEmit.empty()) {
1231 Expr *E = ExprsToEmit.front();
1232 ExprsToEmit.pop();
1233
1234 Record.clear();
1235 if (!E) {
1236 S.EmitRecord(pch::EXPR_NULL, Record);
1237 continue;
1238 }
1239
1240 Writer.Code = pch::EXPR_NULL;
1241 Writer.Visit(E);
1242 assert(Writer.Code != pch::EXPR_NULL &&
1243 "Unhandled expression writing PCH file");
1244 S.EmitRecord(Writer.Code, Record);
1245 }
1246}