blob: 4963ea1160862ef8eb33a54418bc5463c53cfb96 [file] [log] [blame]
Douglas Gregor2cf26342009-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"
19#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000020#include "clang/Lex/MacroInfo.h"
21#include "clang/Lex/Preprocessor.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Basic/FileManager.h"
23#include "clang/Basic/SourceManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000024#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000025#include "llvm/Bitcode/BitstreamWriter.h"
26#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000028
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Type serialization
33//===----------------------------------------------------------------------===//
34namespace {
35 class VISIBILITY_HIDDEN PCHTypeWriter {
36 PCHWriter &Writer;
37 PCHWriter::RecordData &Record;
38
39 public:
40 /// \brief Type code that corresponds to the record generated.
41 pch::TypeCode Code;
42
43 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
44 : Writer(Writer), Record(Record) { }
45
46 void VisitArrayType(const ArrayType *T);
47 void VisitFunctionType(const FunctionType *T);
48 void VisitTagType(const TagType *T);
49
50#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
51#define ABSTRACT_TYPE(Class, Base)
52#define DEPENDENT_TYPE(Class, Base)
53#include "clang/AST/TypeNodes.def"
54 };
55}
56
57void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
58 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
59 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
60 Record.push_back(T->getAddressSpace());
61 Code = pch::TYPE_EXT_QUAL;
62}
63
64void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
65 assert(false && "Built-in types are never serialized");
66}
67
68void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
69 Record.push_back(T->getWidth());
70 Record.push_back(T->isSigned());
71 Code = pch::TYPE_FIXED_WIDTH_INT;
72}
73
74void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
75 Writer.AddTypeRef(T->getElementType(), Record);
76 Code = pch::TYPE_COMPLEX;
77}
78
79void PCHTypeWriter::VisitPointerType(const PointerType *T) {
80 Writer.AddTypeRef(T->getPointeeType(), Record);
81 Code = pch::TYPE_POINTER;
82}
83
84void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
85 Writer.AddTypeRef(T->getPointeeType(), Record);
86 Code = pch::TYPE_BLOCK_POINTER;
87}
88
89void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_LVALUE_REFERENCE;
92}
93
94void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_RVALUE_REFERENCE;
97}
98
99void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
102 Code = pch::TYPE_MEMBER_POINTER;
103}
104
105void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
106 Writer.AddTypeRef(T->getElementType(), Record);
107 Record.push_back(T->getSizeModifier()); // FIXME: stable values
108 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
109}
110
111void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
112 VisitArrayType(T);
113 Writer.AddAPInt(T->getSize(), Record);
114 Code = pch::TYPE_CONSTANT_ARRAY;
115}
116
117void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
118 VisitArrayType(T);
119 Code = pch::TYPE_INCOMPLETE_ARRAY;
120}
121
122void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
123 VisitArrayType(T);
124 // FIXME: Serialize array size expression.
125 assert(false && "Cannot serialize variable-length arrays");
126 Code = pch::TYPE_VARIABLE_ARRAY;
127}
128
129void PCHTypeWriter::VisitVectorType(const VectorType *T) {
130 Writer.AddTypeRef(T->getElementType(), Record);
131 Record.push_back(T->getNumElements());
132 Code = pch::TYPE_VECTOR;
133}
134
135void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
136 VisitVectorType(T);
137 Code = pch::TYPE_EXT_VECTOR;
138}
139
140void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
141 Writer.AddTypeRef(T->getResultType(), Record);
142}
143
144void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
145 VisitFunctionType(T);
146 Code = pch::TYPE_FUNCTION_NO_PROTO;
147}
148
149void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
150 VisitFunctionType(T);
151 Record.push_back(T->getNumArgs());
152 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
153 Writer.AddTypeRef(T->getArgType(I), Record);
154 Record.push_back(T->isVariadic());
155 Record.push_back(T->getTypeQuals());
156 Code = pch::TYPE_FUNCTION_PROTO;
157}
158
159void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
160 Writer.AddDeclRef(T->getDecl(), Record);
161 Code = pch::TYPE_TYPEDEF;
162}
163
164void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
165 // FIXME: serialize the typeof expression
166 assert(false && "Cannot serialize typeof(expr)");
167 Code = pch::TYPE_TYPEOF_EXPR;
168}
169
170void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
171 Writer.AddTypeRef(T->getUnderlyingType(), Record);
172 Code = pch::TYPE_TYPEOF;
173}
174
175void PCHTypeWriter::VisitTagType(const TagType *T) {
176 Writer.AddDeclRef(T->getDecl(), Record);
177 assert(!T->isBeingDefined() &&
178 "Cannot serialize in the middle of a type definition");
179}
180
181void PCHTypeWriter::VisitRecordType(const RecordType *T) {
182 VisitTagType(T);
183 Code = pch::TYPE_RECORD;
184}
185
186void PCHTypeWriter::VisitEnumType(const EnumType *T) {
187 VisitTagType(T);
188 Code = pch::TYPE_ENUM;
189}
190
191void
192PCHTypeWriter::VisitTemplateSpecializationType(
193 const TemplateSpecializationType *T) {
194 // FIXME: Serialize this type
195 assert(false && "Cannot serialize template specialization types");
196}
197
198void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
199 // FIXME: Serialize this type
200 assert(false && "Cannot serialize qualified name types");
201}
202
203void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
204 Writer.AddDeclRef(T->getDecl(), Record);
205 Code = pch::TYPE_OBJC_INTERFACE;
206}
207
208void
209PCHTypeWriter::VisitObjCQualifiedInterfaceType(
210 const ObjCQualifiedInterfaceType *T) {
211 VisitObjCInterfaceType(T);
212 Record.push_back(T->getNumProtocols());
213 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
214 Writer.AddDeclRef(T->getProtocol(I), Record);
215 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
216}
217
218void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
219 Record.push_back(T->getNumProtocols());
220 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
221 Writer.AddDeclRef(T->getProtocols(I), Record);
222 Code = pch::TYPE_OBJC_QUALIFIED_ID;
223}
224
225void
226PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
227 Record.push_back(T->getNumProtocols());
228 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
229 Writer.AddDeclRef(T->getProtocols(I), Record);
230 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
231}
232
233//===----------------------------------------------------------------------===//
234// Declaration serialization
235//===----------------------------------------------------------------------===//
236namespace {
237 class VISIBILITY_HIDDEN PCHDeclWriter
238 : public DeclVisitor<PCHDeclWriter, void> {
239
240 PCHWriter &Writer;
241 PCHWriter::RecordData &Record;
242
243 public:
244 pch::DeclCode Code;
245
246 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
247 : Writer(Writer), Record(Record) { }
248
249 void VisitDecl(Decl *D);
250 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
251 void VisitNamedDecl(NamedDecl *D);
252 void VisitTypeDecl(TypeDecl *D);
253 void VisitTypedefDecl(TypedefDecl *D);
254 void VisitValueDecl(ValueDecl *D);
255 void VisitVarDecl(VarDecl *D);
256
257 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
258 uint64_t VisibleOffset);
259 };
260}
261
262void PCHDeclWriter::VisitDecl(Decl *D) {
263 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
264 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
265 Writer.AddSourceLocation(D->getLocation(), Record);
266 Record.push_back(D->isInvalidDecl());
267 // FIXME: hasAttrs
268 Record.push_back(D->isImplicit());
269 Record.push_back(D->getAccess());
270}
271
272void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
273 VisitDecl(D);
274 Code = pch::DECL_TRANSLATION_UNIT;
275}
276
277void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
278 VisitDecl(D);
279 Writer.AddDeclarationName(D->getDeclName(), Record);
280}
281
282void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
283 VisitNamedDecl(D);
284 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
285}
286
287void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
288 VisitTypeDecl(D);
289 Writer.AddTypeRef(D->getUnderlyingType(), Record);
290 Code = pch::DECL_TYPEDEF;
291}
292
293void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
294 VisitNamedDecl(D);
295 Writer.AddTypeRef(D->getType(), Record);
296}
297
298void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
299 VisitValueDecl(D);
300 Record.push_back(D->getStorageClass());
301 Record.push_back(D->isThreadSpecified());
302 Record.push_back(D->hasCXXDirectInitializer());
303 Record.push_back(D->isDeclaredInCondition());
304 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
305 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
306 // FIXME: emit initializer
307 Code = pch::DECL_VAR;
308}
309
310/// \brief Emit the DeclContext part of a declaration context decl.
311///
312/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
313/// block for this declaration context is stored. May be 0 to indicate
314/// that there are no declarations stored within this context.
315///
316/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
317/// block for this declaration context is stored. May be 0 to indicate
318/// that there are no declarations visible from this context. Note
319/// that this value will not be emitted for non-primary declaration
320/// contexts.
321void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
322 uint64_t VisibleOffset) {
323 Record.push_back(LexicalOffset);
324 if (DC->getPrimaryContext() == DC)
325 Record.push_back(VisibleOffset);
326}
327
328//===----------------------------------------------------------------------===//
329// PCHWriter Implementation
330//===----------------------------------------------------------------------===//
331
Douglas Gregor2bec0412009-04-10 21:16:55 +0000332/// \brief Write the target triple (e.g., i686-apple-darwin9).
333void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
334 using namespace llvm;
335 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
336 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
338 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
339
340 RecordData Record;
341 Record.push_back(pch::TARGET_TRIPLE);
342 const char *Triple = Target.getTargetTriple();
343 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
344}
345
346/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000347void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
348 RecordData Record;
349 Record.push_back(LangOpts.Trigraphs);
350 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
351 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
352 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
353 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
354 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
355 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
356 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
357 Record.push_back(LangOpts.C99); // C99 Support
358 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
359 Record.push_back(LangOpts.CPlusPlus); // C++ Support
360 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
361 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
362 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
363
364 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
365 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
366 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
367
368 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
369 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
370 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
371 Record.push_back(LangOpts.LaxVectorConversions);
372 Record.push_back(LangOpts.Exceptions); // Support exception handling.
373
374 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
375 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
376 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
377
378 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
379 // by locks.
380 Record.push_back(LangOpts.Blocks); // block extension to C
381 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
382 // they are unused.
383 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
384 // (modulo the platform support).
385
386 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
387 // signed integer arithmetic overflows.
388
389 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
390 // may be ripped out at any time.
391
392 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
393 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
394 // defined.
395 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
396 // opposed to __DYNAMIC__).
397 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
398
399 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
400 // used (instead of C99 semantics).
401 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
402 Record.push_back(LangOpts.getGCMode());
403 Record.push_back(LangOpts.getVisibilityMode());
404 Record.push_back(LangOpts.InstantiationDepth);
405 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
406}
407
Douglas Gregor14f79002009-04-10 03:52:48 +0000408//===----------------------------------------------------------------------===//
409// Source Manager Serialization
410//===----------------------------------------------------------------------===//
411
412/// \brief Create an abbreviation for the SLocEntry that refers to a
413/// file.
414static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
415 using namespace llvm;
416 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
417 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
422 // FIXME: Need an actual encoding for the line directives; maybe
423 // this should be an array?
424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
425 return S.EmitAbbrev(Abbrev);
426}
427
428/// \brief Create an abbreviation for the SLocEntry that refers to a
429/// buffer.
430static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
431 using namespace llvm;
432 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
433 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
437 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
438 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
439 return S.EmitAbbrev(Abbrev);
440}
441
442/// \brief Create an abbreviation for the SLocEntry that refers to a
443/// buffer's blob.
444static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
445 using namespace llvm;
446 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
447 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
449 return S.EmitAbbrev(Abbrev);
450}
451
452/// \brief Create an abbreviation for the SLocEntry that refers to an
453/// buffer.
454static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
455 using namespace llvm;
456 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
457 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
462 return S.EmitAbbrev(Abbrev);
463}
464
465/// \brief Writes the block containing the serialized form of the
466/// source manager.
467///
468/// TODO: We should probably use an on-disk hash table (stored in a
469/// blob), indexed based on the file name, so that we only create
470/// entries for files that we actually need. In the common case (no
471/// errors), we probably won't have to create file entries for any of
472/// the files in the AST.
473void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000474 // Enter the source manager block.
Douglas Gregor14f79002009-04-10 03:52:48 +0000475 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
476
477 // Abbreviations for the various kinds of source-location entries.
478 int SLocFileAbbrv = -1;
479 int SLocBufferAbbrv = -1;
480 int SLocBufferBlobAbbrv = -1;
481 int SLocInstantiationAbbrv = -1;
482
483 // Write out the source location entry table. We skip the first
484 // entry, which is always the same dummy entry.
485 RecordData Record;
486 for (SourceManager::sloc_entry_iterator
487 SLoc = SourceMgr.sloc_entry_begin() + 1,
488 SLocEnd = SourceMgr.sloc_entry_end();
489 SLoc != SLocEnd; ++SLoc) {
490 // Figure out which record code to use.
491 unsigned Code;
492 if (SLoc->isFile()) {
493 if (SLoc->getFile().getContentCache()->Entry)
494 Code = pch::SM_SLOC_FILE_ENTRY;
495 else
496 Code = pch::SM_SLOC_BUFFER_ENTRY;
497 } else
498 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
499 Record.push_back(Code);
500
501 Record.push_back(SLoc->getOffset());
502 if (SLoc->isFile()) {
503 const SrcMgr::FileInfo &File = SLoc->getFile();
504 Record.push_back(File.getIncludeLoc().getRawEncoding());
505 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
506 Record.push_back(File.hasLineDirectives()); // FIXME: encode the
507 // line directives?
508
509 const SrcMgr::ContentCache *Content = File.getContentCache();
510 if (Content->Entry) {
511 // The source location entry is a file. The blob associated
512 // with this entry is the file name.
513 if (SLocFileAbbrv == -1)
514 SLocFileAbbrv = CreateSLocFileAbbrev(S);
515 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
516 Content->Entry->getName(),
517 strlen(Content->Entry->getName()));
518 } else {
519 // The source location entry is a buffer. The blob associated
520 // with this entry contains the contents of the buffer.
521 if (SLocBufferAbbrv == -1) {
522 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
523 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
524 }
525
526 // We add one to the size so that we capture the trailing NULL
527 // that is required by llvm::MemoryBuffer::getMemBuffer (on
528 // the reader side).
529 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
530 const char *Name = Buffer->getBufferIdentifier();
531 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
532 Record.clear();
533 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
534 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
535 Buffer->getBufferStart(),
536 Buffer->getBufferSize() + 1);
537 }
538 } else {
539 // The source location entry is an instantiation.
540 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
541 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
542 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
543 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
544
545 if (SLocInstantiationAbbrv == -1)
546 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
547 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
548 }
549
550 Record.clear();
551 }
552
553 S.ExitBlock();
554}
555
Chris Lattner0b1fb982009-04-10 17:15:23 +0000556/// \brief Writes the block containing the serialized form of the
557/// preprocessor.
558///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000559void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000560 // Enter the preprocessor block.
561 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
562
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000563 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
564 // FIXME: use diagnostics subsystem for localization etc.
565 if (PP.SawDateOrTime())
566 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattnerf04ad692009-04-10 17:16:57 +0000567
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000568 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000569
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000570 // Loop over all the macro definitions that are live at the end of the file,
571 // emitting each to the PP section.
572 // FIXME: Eventually we want to emit an index so that we can lazily load
573 // macros.
574 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
575 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000576 // FIXME: This emits macros in hash table order, we should do it in a stable
577 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000578 MacroInfo *MI = I->second;
579
580 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
581 // been redefined by the header (in which case they are not isBuiltinMacro).
582 if (MI->isBuiltinMacro())
583 continue;
584
585 IdentifierInfo *II = I->first;
586
Chris Lattnerd14f2702009-04-10 18:22:18 +0000587 // FIXME: Emit a PP_MACRO_NAME for testing. This should be removed when we
588 // have identifierinfo id's.
589 for (unsigned i = 0, e = II->getLength(); i != e; ++i)
590 Record.push_back(II->getName()[i]);
591 S.EmitRecord(pch::PP_MACRO_NAME, Record);
592 Record.clear();
593
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000594 // FIXME: Output the identifier Info ID #!
595 Record.push_back((intptr_t)II);
596 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
597 Record.push_back(MI->isUsed());
598
599 unsigned Code;
600 if (MI->isObjectLike()) {
601 Code = pch::PP_MACRO_OBJECT_LIKE;
602 } else {
603 Code = pch::PP_MACRO_FUNCTION_LIKE;
604
605 Record.push_back(MI->isC99Varargs());
606 Record.push_back(MI->isGNUVarargs());
607 Record.push_back(MI->getNumArgs());
608 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
609 I != E; ++I)
610 // FIXME: Output the identifier Info ID #!
611 Record.push_back((intptr_t)II);
612 }
613 S.EmitRecord(Code, Record);
614 Record.clear();
615
Chris Lattnerdf961c22009-04-10 18:08:30 +0000616 // Emit the tokens array.
617 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
618 // Note that we know that the preprocessor does not have any annotation
619 // tokens in it because they are created by the parser, and thus can't be
620 // in a macro definition.
621 const Token &Tok = MI->getReplacementToken(TokNo);
622
623 Record.push_back(Tok.getLocation().getRawEncoding());
624 Record.push_back(Tok.getLength());
625
626 // FIXME: Output the identifier Info ID #!
627 // FIXME: When reading literal tokens, reconstruct the literal pointer if
628 // it is needed.
629 Record.push_back((intptr_t)Tok.getIdentifierInfo());
630
631 // FIXME: Should translate token kind to a stable encoding.
632 Record.push_back(Tok.getKind());
633 // FIXME: Should translate token flags to a stable encoding.
634 Record.push_back(Tok.getFlags());
635
636 S.EmitRecord(pch::PP_TOKEN, Record);
637 Record.clear();
638 }
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000639
640 }
641
642 // TODO: someday when PP supports __COUNTER__, emit a record for its value if
643 // non-zero.
Chris Lattnerf04ad692009-04-10 17:16:57 +0000644
645 S.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000646}
647
648
Douglas Gregor2cf26342009-04-09 22:27:44 +0000649/// \brief Write the representation of a type to the PCH stream.
650void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000651 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000652 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000653 ID = NextTypeID++;
654
655 // Record the offset for this type.
656 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
657 TypeOffsets.push_back(S.GetCurrentBitNo());
658 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
659 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
660 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
661 }
662
663 RecordData Record;
664
665 // Emit the type's representation.
666 PCHTypeWriter W(*this, Record);
667 switch (T->getTypeClass()) {
668 // For all of the concrete, non-dependent types, call the
669 // appropriate visitor function.
670#define TYPE(Class, Base) \
671 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
672#define ABSTRACT_TYPE(Class, Base)
673#define DEPENDENT_TYPE(Class, Base)
674#include "clang/AST/TypeNodes.def"
675
676 // For all of the dependent type nodes (which only occur in C++
677 // templates), produce an error.
678#define TYPE(Class, Base)
679#define DEPENDENT_TYPE(Class, Base) case Type::Class:
680#include "clang/AST/TypeNodes.def"
681 assert(false && "Cannot serialize dependent type nodes");
682 break;
683 }
684
685 // Emit the serialized record.
686 S.EmitRecord(W.Code, Record);
687}
688
689/// \brief Write a block containing all of the types.
690void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000691 // Enter the types block.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000692 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
693
694 // Emit all of the types in the ASTContext
695 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
696 TEnd = Context.getTypes().end();
697 T != TEnd; ++T) {
698 // Builtin types are never serialized.
699 if (isa<BuiltinType>(*T))
700 continue;
701
702 WriteType(*T);
703 }
704
705 // Exit the types block
706 S.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000707}
708
709/// \brief Write the block containing all of the declaration IDs
710/// lexically declared within the given DeclContext.
711///
712/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
713/// bistream, or 0 if no block was written.
714uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
715 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000716 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +0000717 return 0;
718
719 uint64_t Offset = S.GetCurrentBitNo();
720 RecordData Record;
721 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
722 DEnd = DC->decls_end(Context);
723 D != DEnd; ++D)
724 AddDeclRef(*D, Record);
725
726 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
727 return Offset;
728}
729
730/// \brief Write the block containing all of the declaration IDs
731/// visible from the given DeclContext.
732///
733/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
734/// bistream, or 0 if no block was written.
735uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
736 DeclContext *DC) {
737 if (DC->getPrimaryContext() != DC)
738 return 0;
739
740 // Force the DeclContext to build a its name-lookup table.
741 DC->lookup(Context, DeclarationName());
742
743 // Serialize the contents of the mapping used for lookup. Note that,
744 // although we have two very different code paths, the serialized
745 // representation is the same for both cases: a declaration name,
746 // followed by a size, followed by references to the visible
747 // declarations that have that name.
748 uint64_t Offset = S.GetCurrentBitNo();
749 RecordData Record;
750 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
751 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
752 D != DEnd; ++D) {
753 AddDeclarationName(D->first, Record);
754 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
755 Record.push_back(Result.second - Result.first);
756 for(; Result.first != Result.second; ++Result.first)
757 AddDeclRef(*Result.first, Record);
758 }
759
760 if (Record.size() == 0)
761 return 0;
762
763 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
764 return Offset;
765}
766
767/// \brief Write a block containing all of the declarations.
768void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000769 // Enter the declarations block.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000770 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
771
772 // Emit all of the declarations.
773 RecordData Record;
774 PCHDeclWriter W(*this, Record);
775 while (!DeclsToEmit.empty()) {
776 // Pull the next declaration off the queue
777 Decl *D = DeclsToEmit.front();
778 DeclsToEmit.pop();
779
780 // If this declaration is also a DeclContext, write blocks for the
781 // declarations that lexically stored inside its context and those
782 // declarations that are visible from its context. These blocks
783 // are written before the declaration itself so that we can put
784 // their offsets into the record for the declaration.
785 uint64_t LexicalOffset = 0;
786 uint64_t VisibleOffset = 0;
787 DeclContext *DC = dyn_cast<DeclContext>(D);
788 if (DC) {
789 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
790 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
791 }
792
793 // Determine the ID for this declaration
Douglas Gregor8038d512009-04-10 17:25:41 +0000794 pch::DeclID ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +0000795 if (ID == 0)
796 ID = DeclIDs.size();
797
798 unsigned Index = ID - 1;
799
800 // Record the offset for this declaration
801 if (DeclOffsets.size() == Index)
802 DeclOffsets.push_back(S.GetCurrentBitNo());
803 else if (DeclOffsets.size() < Index) {
804 DeclOffsets.resize(Index+1);
805 DeclOffsets[Index] = S.GetCurrentBitNo();
806 }
807
808 // Build and emit a record for this declaration
809 Record.clear();
810 W.Code = (pch::DeclCode)0;
811 W.Visit(D);
812 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
813 assert(W.Code && "Visitor did not set record code");
814 S.EmitRecord(W.Code, Record);
815 }
816
817 // Exit the declarations block
818 S.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000819}
820
821PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
822 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
823
Chris Lattnerdf961c22009-04-10 18:08:30 +0000824void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000825 // Emit the file header.
826 S.Emit((unsigned)'C', 8);
827 S.Emit((unsigned)'P', 8);
828 S.Emit((unsigned)'C', 8);
829 S.Emit((unsigned)'H', 8);
830
831 // The translation unit is the first declaration we'll emit.
832 DeclIDs[Context.getTranslationUnitDecl()] = 1;
833 DeclsToEmit.push(Context.getTranslationUnitDecl());
834
835 // Write the remaining PCH contents.
Douglas Gregor2bec0412009-04-10 21:16:55 +0000836 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
837 WriteTargetTriple(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000838 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattner0b1fb982009-04-10 17:15:23 +0000840 WritePreprocessor(PP);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000841 WriteTypesBlock(Context);
842 WriteDeclsBlock(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000843 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
844 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000845 S.ExitBlock();
846}
847
848void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
849 Record.push_back(Loc.getRawEncoding());
850}
851
852void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
853 Record.push_back(Value.getBitWidth());
854 unsigned N = Value.getNumWords();
855 const uint64_t* Words = Value.getRawData();
856 for (unsigned I = 0; I != N; ++I)
857 Record.push_back(Words[I]);
858}
859
860void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
861 // FIXME: Emit an identifier ID, not the actual string!
862 const char *Name = II->getName();
863 unsigned Len = strlen(Name);
864 Record.push_back(Len);
865 Record.insert(Record.end(), Name, Name + Len);
866}
867
868void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
869 if (T.isNull()) {
870 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
871 return;
872 }
873
874 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000875 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000876 switch (BT->getKind()) {
877 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
878 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
879 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
880 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
881 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
882 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
883 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
884 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
885 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
886 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
887 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
888 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
889 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
890 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
891 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
892 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
893 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
894 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
895 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
896 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
897 }
898
899 Record.push_back((ID << 3) | T.getCVRQualifiers());
900 return;
901 }
902
Douglas Gregor8038d512009-04-10 17:25:41 +0000903 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor2cf26342009-04-09 22:27:44 +0000904 if (ID == 0) // we haven't seen this type before
905 ID = NextTypeID++;
906
907 // Encode the type qualifiers in the type reference.
908 Record.push_back((ID << 3) | T.getCVRQualifiers());
909}
910
911void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
912 if (D == 0) {
913 Record.push_back(0);
914 return;
915 }
916
Douglas Gregor8038d512009-04-10 17:25:41 +0000917 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +0000918 if (ID == 0) {
919 // We haven't seen this declaration before. Give it a new ID and
920 // enqueue it in the list of declarations to emit.
921 ID = DeclIDs.size();
922 DeclsToEmit.push(const_cast<Decl *>(D));
923 }
924
925 Record.push_back(ID);
926}
927
928void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
929 Record.push_back(Name.getNameKind());
930 switch (Name.getNameKind()) {
931 case DeclarationName::Identifier:
932 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
933 break;
934
935 case DeclarationName::ObjCZeroArgSelector:
936 case DeclarationName::ObjCOneArgSelector:
937 case DeclarationName::ObjCMultiArgSelector:
938 assert(false && "Serialization of Objective-C selectors unavailable");
939 break;
940
941 case DeclarationName::CXXConstructorName:
942 case DeclarationName::CXXDestructorName:
943 case DeclarationName::CXXConversionFunctionName:
944 AddTypeRef(Name.getCXXNameType(), Record);
945 break;
946
947 case DeclarationName::CXXOperatorName:
948 Record.push_back(Name.getCXXOverloadedOperator());
949 break;
950
951 case DeclarationName::CXXUsingDirective:
952 // No extra data to emit
953 break;
954 }
955}