blob: dc23fb9d81659f0941ba8ba8fae8b47f1b02a888 [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 Gregore2f37202009-04-14 21:55:33 +000028#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000030#include "llvm/Bitcode/BitstreamWriter.h"
31#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000032#include "llvm/Support/MemoryBuffer.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000033#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Type serialization
38//===----------------------------------------------------------------------===//
39namespace {
40 class VISIBILITY_HIDDEN PCHTypeWriter {
41 PCHWriter &Writer;
42 PCHWriter::RecordData &Record;
43
44 public:
45 /// \brief Type code that corresponds to the record generated.
46 pch::TypeCode Code;
47
48 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
49 : Writer(Writer), Record(Record) { }
50
51 void VisitArrayType(const ArrayType *T);
52 void VisitFunctionType(const FunctionType *T);
53 void VisitTagType(const TagType *T);
54
55#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
56#define ABSTRACT_TYPE(Class, Base)
57#define DEPENDENT_TYPE(Class, Base)
58#include "clang/AST/TypeNodes.def"
59 };
60}
61
62void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
63 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
64 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
65 Record.push_back(T->getAddressSpace());
66 Code = pch::TYPE_EXT_QUAL;
67}
68
69void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
70 assert(false && "Built-in types are never serialized");
71}
72
73void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
74 Record.push_back(T->getWidth());
75 Record.push_back(T->isSigned());
76 Code = pch::TYPE_FIXED_WIDTH_INT;
77}
78
79void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
80 Writer.AddTypeRef(T->getElementType(), Record);
81 Code = pch::TYPE_COMPLEX;
82}
83
84void PCHTypeWriter::VisitPointerType(const PointerType *T) {
85 Writer.AddTypeRef(T->getPointeeType(), Record);
86 Code = pch::TYPE_POINTER;
87}
88
89void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_BLOCK_POINTER;
92}
93
94void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_LVALUE_REFERENCE;
97}
98
99void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_RVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
107 Code = pch::TYPE_MEMBER_POINTER;
108}
109
110void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
111 Writer.AddTypeRef(T->getElementType(), Record);
112 Record.push_back(T->getSizeModifier()); // FIXME: stable values
113 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
114}
115
116void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
117 VisitArrayType(T);
118 Writer.AddAPInt(T->getSize(), Record);
119 Code = pch::TYPE_CONSTANT_ARRAY;
120}
121
122void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
123 VisitArrayType(T);
124 Code = pch::TYPE_INCOMPLETE_ARRAY;
125}
126
127void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
128 VisitArrayType(T);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000129 Writer.AddExpr(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000130 Code = pch::TYPE_VARIABLE_ARRAY;
131}
132
133void PCHTypeWriter::VisitVectorType(const VectorType *T) {
134 Writer.AddTypeRef(T->getElementType(), Record);
135 Record.push_back(T->getNumElements());
136 Code = pch::TYPE_VECTOR;
137}
138
139void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
140 VisitVectorType(T);
141 Code = pch::TYPE_EXT_VECTOR;
142}
143
144void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
145 Writer.AddTypeRef(T->getResultType(), Record);
146}
147
148void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
149 VisitFunctionType(T);
150 Code = pch::TYPE_FUNCTION_NO_PROTO;
151}
152
153void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
154 VisitFunctionType(T);
155 Record.push_back(T->getNumArgs());
156 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
157 Writer.AddTypeRef(T->getArgType(I), Record);
158 Record.push_back(T->isVariadic());
159 Record.push_back(T->getTypeQuals());
160 Code = pch::TYPE_FUNCTION_PROTO;
161}
162
163void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
164 Writer.AddDeclRef(T->getDecl(), Record);
165 Code = pch::TYPE_TYPEDEF;
166}
167
168void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000169 Writer.AddExpr(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_TYPEOF_EXPR;
171}
172
173void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
174 Writer.AddTypeRef(T->getUnderlyingType(), Record);
175 Code = pch::TYPE_TYPEOF;
176}
177
178void PCHTypeWriter::VisitTagType(const TagType *T) {
179 Writer.AddDeclRef(T->getDecl(), Record);
180 assert(!T->isBeingDefined() &&
181 "Cannot serialize in the middle of a type definition");
182}
183
184void PCHTypeWriter::VisitRecordType(const RecordType *T) {
185 VisitTagType(T);
186 Code = pch::TYPE_RECORD;
187}
188
189void PCHTypeWriter::VisitEnumType(const EnumType *T) {
190 VisitTagType(T);
191 Code = pch::TYPE_ENUM;
192}
193
194void
195PCHTypeWriter::VisitTemplateSpecializationType(
196 const TemplateSpecializationType *T) {
197 // FIXME: Serialize this type
198 assert(false && "Cannot serialize template specialization types");
199}
200
201void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
202 // FIXME: Serialize this type
203 assert(false && "Cannot serialize qualified name types");
204}
205
206void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
207 Writer.AddDeclRef(T->getDecl(), Record);
208 Code = pch::TYPE_OBJC_INTERFACE;
209}
210
211void
212PCHTypeWriter::VisitObjCQualifiedInterfaceType(
213 const ObjCQualifiedInterfaceType *T) {
214 VisitObjCInterfaceType(T);
215 Record.push_back(T->getNumProtocols());
216 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
217 Writer.AddDeclRef(T->getProtocol(I), Record);
218 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
219}
220
221void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
222 Record.push_back(T->getNumProtocols());
223 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
224 Writer.AddDeclRef(T->getProtocols(I), Record);
225 Code = pch::TYPE_OBJC_QUALIFIED_ID;
226}
227
228void
229PCHTypeWriter::VisitObjCQualifiedClassType(const ObjCQualifiedClassType *T) {
230 Record.push_back(T->getNumProtocols());
231 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
232 Writer.AddDeclRef(T->getProtocols(I), Record);
233 Code = pch::TYPE_OBJC_QUALIFIED_CLASS;
234}
235
236//===----------------------------------------------------------------------===//
237// Declaration serialization
238//===----------------------------------------------------------------------===//
239namespace {
240 class VISIBILITY_HIDDEN PCHDeclWriter
241 : public DeclVisitor<PCHDeclWriter, void> {
242
243 PCHWriter &Writer;
244 PCHWriter::RecordData &Record;
245
246 public:
247 pch::DeclCode Code;
248
249 PCHDeclWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
250 : Writer(Writer), Record(Record) { }
251
252 void VisitDecl(Decl *D);
253 void VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 void VisitNamedDecl(NamedDecl *D);
255 void VisitTypeDecl(TypeDecl *D);
256 void VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000257 void VisitTagDecl(TagDecl *D);
258 void VisitEnumDecl(EnumDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000259 void VisitRecordDecl(RecordDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000260 void VisitValueDecl(ValueDecl *D);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000261 void VisitEnumConstantDecl(EnumConstantDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000262 void VisitFunctionDecl(FunctionDecl *D);
Douglas Gregor982365e2009-04-13 21:20:57 +0000263 void VisitFieldDecl(FieldDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000264 void VisitVarDecl(VarDecl *D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000265 void VisitParmVarDecl(ParmVarDecl *D);
266 void VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
Douglas Gregor2a491792009-04-13 22:49:25 +0000267 void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
268 void VisitBlockDecl(BlockDecl *D);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000269 void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
270 uint64_t VisibleOffset);
271 };
272}
273
274void PCHDeclWriter::VisitDecl(Decl *D) {
275 Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
276 Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
277 Writer.AddSourceLocation(D->getLocation(), Record);
278 Record.push_back(D->isInvalidDecl());
279 // FIXME: hasAttrs
280 Record.push_back(D->isImplicit());
281 Record.push_back(D->getAccess());
282}
283
284void PCHDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
285 VisitDecl(D);
286 Code = pch::DECL_TRANSLATION_UNIT;
287}
288
289void PCHDeclWriter::VisitNamedDecl(NamedDecl *D) {
290 VisitDecl(D);
291 Writer.AddDeclarationName(D->getDeclName(), Record);
292}
293
294void PCHDeclWriter::VisitTypeDecl(TypeDecl *D) {
295 VisitNamedDecl(D);
296 Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
297}
298
299void PCHDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
300 VisitTypeDecl(D);
301 Writer.AddTypeRef(D->getUnderlyingType(), Record);
302 Code = pch::DECL_TYPEDEF;
303}
304
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000305void PCHDeclWriter::VisitTagDecl(TagDecl *D) {
306 VisitTypeDecl(D);
307 Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
308 Record.push_back(D->isDefinition());
309 Writer.AddDeclRef(D->getTypedefForAnonDecl(), Record);
310}
311
312void PCHDeclWriter::VisitEnumDecl(EnumDecl *D) {
313 VisitTagDecl(D);
314 Writer.AddTypeRef(D->getIntegerType(), Record);
315 Code = pch::DECL_ENUM;
316}
317
Douglas Gregor982365e2009-04-13 21:20:57 +0000318void PCHDeclWriter::VisitRecordDecl(RecordDecl *D) {
319 VisitTagDecl(D);
320 Record.push_back(D->hasFlexibleArrayMember());
321 Record.push_back(D->isAnonymousStructOrUnion());
322 Code = pch::DECL_RECORD;
323}
324
Douglas Gregorc34897d2009-04-09 22:27:44 +0000325void PCHDeclWriter::VisitValueDecl(ValueDecl *D) {
326 VisitNamedDecl(D);
327 Writer.AddTypeRef(D->getType(), Record);
328}
329
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000330void PCHDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
331 VisitValueDecl(D);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000332 Record.push_back(D->getInitExpr()? 1 : 0);
333 if (D->getInitExpr())
334 Writer.AddExpr(D->getInitExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000335 Writer.AddAPSInt(D->getInitVal(), Record);
336 Code = pch::DECL_ENUM_CONSTANT;
337}
338
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000339void PCHDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
340 VisitValueDecl(D);
341 // FIXME: function body
342 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
343 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
344 Record.push_back(D->isInline());
345 Record.push_back(D->isVirtual());
346 Record.push_back(D->isPure());
347 Record.push_back(D->inheritedPrototype());
348 Record.push_back(D->hasPrototype() && !D->inheritedPrototype());
349 Record.push_back(D->isDeleted());
350 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
351 Record.push_back(D->param_size());
352 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
353 P != PEnd; ++P)
354 Writer.AddDeclRef(*P, Record);
355 Code = pch::DECL_FUNCTION;
356}
357
Douglas Gregor982365e2009-04-13 21:20:57 +0000358void PCHDeclWriter::VisitFieldDecl(FieldDecl *D) {
359 VisitValueDecl(D);
360 Record.push_back(D->isMutable());
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000361 Record.push_back(D->getBitWidth()? 1 : 0);
362 if (D->getBitWidth())
363 Writer.AddExpr(D->getBitWidth());
Douglas Gregor982365e2009-04-13 21:20:57 +0000364 Code = pch::DECL_FIELD;
365}
366
Douglas Gregorc34897d2009-04-09 22:27:44 +0000367void PCHDeclWriter::VisitVarDecl(VarDecl *D) {
368 VisitValueDecl(D);
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000369 Record.push_back(D->getStorageClass()); // FIXME: stable encoding
Douglas Gregorc34897d2009-04-09 22:27:44 +0000370 Record.push_back(D->isThreadSpecified());
371 Record.push_back(D->hasCXXDirectInitializer());
372 Record.push_back(D->isDeclaredInCondition());
373 Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
374 Writer.AddSourceLocation(D->getTypeSpecStartLoc(), Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000375 Record.push_back(D->getInit()? 1 : 0);
376 if (D->getInit())
377 Writer.AddExpr(D->getInit());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000378 Code = pch::DECL_VAR;
379}
380
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000381void PCHDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
382 VisitVarDecl(D);
383 Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
384 // FIXME: emit default argument
385 // FIXME: why isn't the "default argument" just stored as the initializer
386 // in VarDecl?
387 Code = pch::DECL_PARM_VAR;
388}
389
390void PCHDeclWriter::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
391 VisitParmVarDecl(D);
392 Writer.AddTypeRef(D->getOriginalType(), Record);
393 Code = pch::DECL_ORIGINAL_PARM_VAR;
394}
395
Douglas Gregor2a491792009-04-13 22:49:25 +0000396void PCHDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
397 VisitDecl(D);
398 // FIXME: Emit the string literal
399 Code = pch::DECL_FILE_SCOPE_ASM;
400}
401
402void PCHDeclWriter::VisitBlockDecl(BlockDecl *D) {
403 VisitDecl(D);
404 // FIXME: emit block body
405 Record.push_back(D->param_size());
406 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
407 P != PEnd; ++P)
408 Writer.AddDeclRef(*P, Record);
409 Code = pch::DECL_BLOCK;
410}
411
Douglas Gregorc34897d2009-04-09 22:27:44 +0000412/// \brief Emit the DeclContext part of a declaration context decl.
413///
414/// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
415/// block for this declaration context is stored. May be 0 to indicate
416/// that there are no declarations stored within this context.
417///
418/// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
419/// block for this declaration context is stored. May be 0 to indicate
420/// that there are no declarations visible from this context. Note
421/// that this value will not be emitted for non-primary declaration
422/// contexts.
423void PCHDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
424 uint64_t VisibleOffset) {
425 Record.push_back(LexicalOffset);
426 if (DC->getPrimaryContext() == DC)
427 Record.push_back(VisibleOffset);
428}
429
430//===----------------------------------------------------------------------===//
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000431// Statement/expression serialization
432//===----------------------------------------------------------------------===//
433namespace {
434 class VISIBILITY_HIDDEN PCHStmtWriter
435 : public StmtVisitor<PCHStmtWriter, void> {
436
437 PCHWriter &Writer;
438 PCHWriter::RecordData &Record;
439
440 public:
441 pch::StmtCode Code;
442
443 PCHStmtWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
444 : Writer(Writer), Record(Record) { }
445
446 void VisitExpr(Expr *E);
Douglas Gregore2f37202009-04-14 21:55:33 +0000447 void VisitPredefinedExpr(PredefinedExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000448 void VisitDeclRefExpr(DeclRefExpr *E);
449 void VisitIntegerLiteral(IntegerLiteral *E);
Douglas Gregore2f37202009-04-14 21:55:33 +0000450 void VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000451 void VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000452 void VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000453 void VisitUnaryOperator(UnaryOperator *E);
454 void VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000455 void VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000456 void VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000457 void VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000458 void VisitExplicitCastExpr(ExplicitCastExpr *E);
459 void VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000460 };
461}
462
463void PCHStmtWriter::VisitExpr(Expr *E) {
464 Writer.AddTypeRef(E->getType(), Record);
465 Record.push_back(E->isTypeDependent());
466 Record.push_back(E->isValueDependent());
467}
468
Douglas Gregore2f37202009-04-14 21:55:33 +0000469void PCHStmtWriter::VisitPredefinedExpr(PredefinedExpr *E) {
470 VisitExpr(E);
471 Writer.AddSourceLocation(E->getLocation(), Record);
472 Record.push_back(E->getIdentType()); // FIXME: stable encoding
473 Code = pch::EXPR_PREDEFINED;
474}
475
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000476void PCHStmtWriter::VisitDeclRefExpr(DeclRefExpr *E) {
477 VisitExpr(E);
478 Writer.AddDeclRef(E->getDecl(), Record);
479 Writer.AddSourceLocation(E->getLocation(), Record);
480 Code = pch::EXPR_DECL_REF;
481}
482
483void PCHStmtWriter::VisitIntegerLiteral(IntegerLiteral *E) {
484 VisitExpr(E);
485 Writer.AddSourceLocation(E->getLocation(), Record);
486 Writer.AddAPInt(E->getValue(), Record);
487 Code = pch::EXPR_INTEGER_LITERAL;
488}
489
Douglas Gregore2f37202009-04-14 21:55:33 +0000490void PCHStmtWriter::VisitFloatingLiteral(FloatingLiteral *E) {
491 VisitExpr(E);
492 Writer.AddAPFloat(E->getValue(), Record);
493 Record.push_back(E->isExact());
494 Writer.AddSourceLocation(E->getLocation(), Record);
495 Code = pch::EXPR_FLOATING_LITERAL;
496}
497
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000498void PCHStmtWriter::VisitCharacterLiteral(CharacterLiteral *E) {
499 VisitExpr(E);
500 Record.push_back(E->getValue());
501 Writer.AddSourceLocation(E->getLoc(), Record);
502 Record.push_back(E->isWide());
503 Code = pch::EXPR_CHARACTER_LITERAL;
504}
505
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000506void PCHStmtWriter::VisitParenExpr(ParenExpr *E) {
507 VisitExpr(E);
508 Writer.AddSourceLocation(E->getLParen(), Record);
509 Writer.AddSourceLocation(E->getRParen(), Record);
510 Writer.WriteSubExpr(E->getSubExpr());
511 Code = pch::EXPR_PAREN;
512}
513
Douglas Gregor12d74052009-04-15 15:58:59 +0000514void PCHStmtWriter::VisitUnaryOperator(UnaryOperator *E) {
515 VisitExpr(E);
516 Writer.WriteSubExpr(E->getSubExpr());
517 Record.push_back(E->getOpcode()); // FIXME: stable encoding
518 Writer.AddSourceLocation(E->getOperatorLoc(), Record);
519 Code = pch::EXPR_UNARY_OPERATOR;
520}
521
522void PCHStmtWriter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
523 VisitExpr(E);
524 Record.push_back(E->isSizeOf());
525 if (E->isArgumentType())
526 Writer.AddTypeRef(E->getArgumentType(), Record);
527 else {
528 Record.push_back(0);
529 Writer.WriteSubExpr(E->getArgumentExpr());
530 }
531 Writer.AddSourceLocation(E->getOperatorLoc(), Record);
532 Writer.AddSourceLocation(E->getRParenLoc(), Record);
533 Code = pch::EXPR_SIZEOF_ALIGN_OF;
534}
535
Douglas Gregora151ba42009-04-14 23:32:43 +0000536void PCHStmtWriter::VisitCastExpr(CastExpr *E) {
537 VisitExpr(E);
538 Writer.WriteSubExpr(E->getSubExpr());
539}
540
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000541void PCHStmtWriter::VisitBinaryOperator(BinaryOperator *E) {
542 VisitExpr(E);
543 Writer.WriteSubExpr(E->getLHS());
544 Writer.WriteSubExpr(E->getRHS());
545 Record.push_back(E->getOpcode()); // FIXME: stable encoding
546 Writer.AddSourceLocation(E->getOperatorLoc(), Record);
547 Code = pch::EXPR_BINARY_OPERATOR;
548}
549
Douglas Gregora151ba42009-04-14 23:32:43 +0000550void PCHStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
551 VisitCastExpr(E);
552 Record.push_back(E->isLvalueCast());
553 Code = pch::EXPR_IMPLICIT_CAST;
554}
555
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000556void PCHStmtWriter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
557 VisitCastExpr(E);
558 Writer.AddTypeRef(E->getTypeAsWritten(), Record);
559}
560
561void PCHStmtWriter::VisitCStyleCastExpr(CStyleCastExpr *E) {
562 VisitExplicitCastExpr(E);
563 Writer.AddSourceLocation(E->getLParenLoc(), Record);
564 Writer.AddSourceLocation(E->getRParenLoc(), Record);
565 Code = pch::EXPR_CSTYLE_CAST;
566}
567
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000568//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000569// PCHWriter Implementation
570//===----------------------------------------------------------------------===//
571
Douglas Gregorb5887f32009-04-10 21:16:55 +0000572/// \brief Write the target triple (e.g., i686-apple-darwin9).
573void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
574 using namespace llvm;
575 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
576 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
577 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
578 unsigned TripleAbbrev = S.EmitAbbrev(Abbrev);
579
580 RecordData Record;
581 Record.push_back(pch::TARGET_TRIPLE);
582 const char *Triple = Target.getTargetTriple();
583 S.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
584}
585
586/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000587void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
588 RecordData Record;
589 Record.push_back(LangOpts.Trigraphs);
590 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
591 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
592 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
593 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
594 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
595 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
596 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
597 Record.push_back(LangOpts.C99); // C99 Support
598 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
599 Record.push_back(LangOpts.CPlusPlus); // C++ Support
600 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
601 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
602 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
603
604 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
605 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
606 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
607
608 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
609 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
610 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
611 Record.push_back(LangOpts.LaxVectorConversions);
612 Record.push_back(LangOpts.Exceptions); // Support exception handling.
613
614 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
615 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
616 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
617
618 Record.push_back(LangOpts.ThreadsafeStatics); // Whether static initializers are protected
619 // by locks.
620 Record.push_back(LangOpts.Blocks); // block extension to C
621 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
622 // they are unused.
623 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
624 // (modulo the platform support).
625
626 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
627 // signed integer arithmetic overflows.
628
629 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
630 // may be ripped out at any time.
631
632 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
633 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
634 // defined.
635 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
636 // opposed to __DYNAMIC__).
637 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
638
639 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
640 // used (instead of C99 semantics).
641 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
642 Record.push_back(LangOpts.getGCMode());
643 Record.push_back(LangOpts.getVisibilityMode());
644 Record.push_back(LangOpts.InstantiationDepth);
645 S.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
646}
647
Douglas Gregorab1cef72009-04-10 03:52:48 +0000648//===----------------------------------------------------------------------===//
649// Source Manager Serialization
650//===----------------------------------------------------------------------===//
651
652/// \brief Create an abbreviation for the SLocEntry that refers to a
653/// file.
654static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &S) {
655 using namespace llvm;
656 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
657 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
663 return S.EmitAbbrev(Abbrev);
664}
665
666/// \brief Create an abbreviation for the SLocEntry that refers to a
667/// buffer.
668static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &S) {
669 using namespace llvm;
670 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
671 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
677 return S.EmitAbbrev(Abbrev);
678}
679
680/// \brief Create an abbreviation for the SLocEntry that refers to a
681/// buffer's blob.
682static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &S) {
683 using namespace llvm;
684 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
685 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
687 return S.EmitAbbrev(Abbrev);
688}
689
690/// \brief Create an abbreviation for the SLocEntry that refers to an
691/// buffer.
692static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &S) {
693 using namespace llvm;
694 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
695 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
700 return S.EmitAbbrev(Abbrev);
701}
702
703/// \brief Writes the block containing the serialized form of the
704/// source manager.
705///
706/// TODO: We should probably use an on-disk hash table (stored in a
707/// blob), indexed based on the file name, so that we only create
708/// entries for files that we actually need. In the common case (no
709/// errors), we probably won't have to create file entries for any of
710/// the files in the AST.
711void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000712 // Enter the source manager block.
Douglas Gregorab1cef72009-04-10 03:52:48 +0000713 S.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
714
715 // Abbreviations for the various kinds of source-location entries.
716 int SLocFileAbbrv = -1;
717 int SLocBufferAbbrv = -1;
718 int SLocBufferBlobAbbrv = -1;
719 int SLocInstantiationAbbrv = -1;
720
721 // Write out the source location entry table. We skip the first
722 // entry, which is always the same dummy entry.
723 RecordData Record;
724 for (SourceManager::sloc_entry_iterator
725 SLoc = SourceMgr.sloc_entry_begin() + 1,
726 SLocEnd = SourceMgr.sloc_entry_end();
727 SLoc != SLocEnd; ++SLoc) {
728 // Figure out which record code to use.
729 unsigned Code;
730 if (SLoc->isFile()) {
731 if (SLoc->getFile().getContentCache()->Entry)
732 Code = pch::SM_SLOC_FILE_ENTRY;
733 else
734 Code = pch::SM_SLOC_BUFFER_ENTRY;
735 } else
736 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
737 Record.push_back(Code);
738
739 Record.push_back(SLoc->getOffset());
740 if (SLoc->isFile()) {
741 const SrcMgr::FileInfo &File = SLoc->getFile();
742 Record.push_back(File.getIncludeLoc().getRawEncoding());
743 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
Douglas Gregor635f97f2009-04-13 16:31:14 +0000744 Record.push_back(File.hasLineDirectives());
Douglas Gregorab1cef72009-04-10 03:52:48 +0000745
746 const SrcMgr::ContentCache *Content = File.getContentCache();
747 if (Content->Entry) {
748 // The source location entry is a file. The blob associated
749 // with this entry is the file name.
750 if (SLocFileAbbrv == -1)
751 SLocFileAbbrv = CreateSLocFileAbbrev(S);
752 S.EmitRecordWithBlob(SLocFileAbbrv, Record,
753 Content->Entry->getName(),
754 strlen(Content->Entry->getName()));
755 } else {
756 // The source location entry is a buffer. The blob associated
757 // with this entry contains the contents of the buffer.
758 if (SLocBufferAbbrv == -1) {
759 SLocBufferAbbrv = CreateSLocBufferAbbrev(S);
760 SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(S);
761 }
762
763 // We add one to the size so that we capture the trailing NULL
764 // that is required by llvm::MemoryBuffer::getMemBuffer (on
765 // the reader side).
766 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
767 const char *Name = Buffer->getBufferIdentifier();
768 S.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
769 Record.clear();
770 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
771 S.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
772 Buffer->getBufferStart(),
773 Buffer->getBufferSize() + 1);
774 }
775 } else {
776 // The source location entry is an instantiation.
777 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
778 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
779 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
780 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
781
782 if (SLocInstantiationAbbrv == -1)
783 SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(S);
784 S.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
785 }
786
787 Record.clear();
788 }
789
Douglas Gregor635f97f2009-04-13 16:31:14 +0000790 // Write the line table.
791 if (SourceMgr.hasLineTable()) {
792 LineTableInfo &LineTable = SourceMgr.getLineTable();
793
794 // Emit the file names
795 Record.push_back(LineTable.getNumFilenames());
796 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
797 // Emit the file name
798 const char *Filename = LineTable.getFilename(I);
799 unsigned FilenameLen = Filename? strlen(Filename) : 0;
800 Record.push_back(FilenameLen);
801 if (FilenameLen)
802 Record.insert(Record.end(), Filename, Filename + FilenameLen);
803 }
804
805 // Emit the line entries
806 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
807 L != LEnd; ++L) {
808 // Emit the file ID
809 Record.push_back(L->first);
810
811 // Emit the line entries
812 Record.push_back(L->second.size());
813 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
814 LEEnd = L->second.end();
815 LE != LEEnd; ++LE) {
816 Record.push_back(LE->FileOffset);
817 Record.push_back(LE->LineNo);
818 Record.push_back(LE->FilenameID);
819 Record.push_back((unsigned)LE->FileKind);
820 Record.push_back(LE->IncludeOffset);
821 }
822 S.EmitRecord(pch::SM_LINE_TABLE, Record);
823 }
824 }
825
Douglas Gregorab1cef72009-04-10 03:52:48 +0000826 S.ExitBlock();
827}
828
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000829/// \brief Writes the block containing the serialized form of the
830/// preprocessor.
831///
Chris Lattner850eabd2009-04-10 18:08:30 +0000832void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000833 // Enter the preprocessor block.
834 S.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 3);
835
Chris Lattner1b094952009-04-10 18:00:12 +0000836 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
837 // FIXME: use diagnostics subsystem for localization etc.
838 if (PP.SawDateOrTime())
839 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Chris Lattner84b04f12009-04-10 17:16:57 +0000840
Chris Lattner1b094952009-04-10 18:00:12 +0000841 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000842
Chris Lattner4b21c202009-04-13 01:29:17 +0000843 // If the preprocessor __COUNTER__ value has been bumped, remember it.
844 if (PP.getCounterValue() != 0) {
845 Record.push_back(PP.getCounterValue());
846 S.EmitRecord(pch::PP_COUNTER_VALUE, Record);
847 Record.clear();
848 }
849
Chris Lattner1b094952009-04-10 18:00:12 +0000850 // Loop over all the macro definitions that are live at the end of the file,
851 // emitting each to the PP section.
852 // FIXME: Eventually we want to emit an index so that we can lazily load
853 // macros.
854 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
855 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000856 // FIXME: This emits macros in hash table order, we should do it in a stable
857 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000858 MacroInfo *MI = I->second;
859
860 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
861 // been redefined by the header (in which case they are not isBuiltinMacro).
862 if (MI->isBuiltinMacro())
863 continue;
864
Chris Lattner29241862009-04-11 21:15:38 +0000865 AddIdentifierRef(I->first, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000866 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
867 Record.push_back(MI->isUsed());
868
869 unsigned Code;
870 if (MI->isObjectLike()) {
871 Code = pch::PP_MACRO_OBJECT_LIKE;
872 } else {
873 Code = pch::PP_MACRO_FUNCTION_LIKE;
874
875 Record.push_back(MI->isC99Varargs());
876 Record.push_back(MI->isGNUVarargs());
877 Record.push_back(MI->getNumArgs());
878 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
879 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000880 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000881 }
882 S.EmitRecord(Code, Record);
883 Record.clear();
884
Chris Lattner850eabd2009-04-10 18:08:30 +0000885 // Emit the tokens array.
886 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
887 // Note that we know that the preprocessor does not have any annotation
888 // tokens in it because they are created by the parser, and thus can't be
889 // in a macro definition.
890 const Token &Tok = MI->getReplacementToken(TokNo);
891
892 Record.push_back(Tok.getLocation().getRawEncoding());
893 Record.push_back(Tok.getLength());
894
Chris Lattner850eabd2009-04-10 18:08:30 +0000895 // FIXME: When reading literal tokens, reconstruct the literal pointer if
896 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000897 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000898
899 // FIXME: Should translate token kind to a stable encoding.
900 Record.push_back(Tok.getKind());
901 // FIXME: Should translate token flags to a stable encoding.
902 Record.push_back(Tok.getFlags());
903
904 S.EmitRecord(pch::PP_TOKEN, Record);
905 Record.clear();
906 }
Chris Lattner1b094952009-04-10 18:00:12 +0000907
908 }
909
Chris Lattner84b04f12009-04-10 17:16:57 +0000910 S.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000911}
912
913
Douglas Gregorc34897d2009-04-09 22:27:44 +0000914/// \brief Write the representation of a type to the PCH stream.
915void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000916 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000917 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000918 ID = NextTypeID++;
919
920 // Record the offset for this type.
921 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
922 TypeOffsets.push_back(S.GetCurrentBitNo());
923 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
924 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
925 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = S.GetCurrentBitNo();
926 }
927
928 RecordData Record;
929
930 // Emit the type's representation.
931 PCHTypeWriter W(*this, Record);
932 switch (T->getTypeClass()) {
933 // For all of the concrete, non-dependent types, call the
934 // appropriate visitor function.
935#define TYPE(Class, Base) \
936 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
937#define ABSTRACT_TYPE(Class, Base)
938#define DEPENDENT_TYPE(Class, Base)
939#include "clang/AST/TypeNodes.def"
940
941 // For all of the dependent type nodes (which only occur in C++
942 // templates), produce an error.
943#define TYPE(Class, Base)
944#define DEPENDENT_TYPE(Class, Base) case Type::Class:
945#include "clang/AST/TypeNodes.def"
946 assert(false && "Cannot serialize dependent type nodes");
947 break;
948 }
949
950 // Emit the serialized record.
951 S.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000952
953 // Flush any expressions that were written as part of this type.
954 FlushExprs();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000955}
956
957/// \brief Write a block containing all of the types.
958void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +0000959 // Enter the types block.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000960 S.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
961
962 // Emit all of the types in the ASTContext
963 for (std::vector<Type*>::const_iterator T = Context.getTypes().begin(),
964 TEnd = Context.getTypes().end();
965 T != TEnd; ++T) {
966 // Builtin types are never serialized.
967 if (isa<BuiltinType>(*T))
968 continue;
969
970 WriteType(*T);
971 }
972
973 // Exit the types block
974 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000975}
976
977/// \brief Write the block containing all of the declaration IDs
978/// lexically declared within the given DeclContext.
979///
980/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
981/// bistream, or 0 if no block was written.
982uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
983 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000984 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +0000985 return 0;
986
987 uint64_t Offset = S.GetCurrentBitNo();
988 RecordData Record;
989 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
990 DEnd = DC->decls_end(Context);
991 D != DEnd; ++D)
992 AddDeclRef(*D, Record);
993
994 S.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
995 return Offset;
996}
997
998/// \brief Write the block containing all of the declaration IDs
999/// visible from the given DeclContext.
1000///
1001/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1002/// bistream, or 0 if no block was written.
1003uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1004 DeclContext *DC) {
1005 if (DC->getPrimaryContext() != DC)
1006 return 0;
1007
1008 // Force the DeclContext to build a its name-lookup table.
1009 DC->lookup(Context, DeclarationName());
1010
1011 // Serialize the contents of the mapping used for lookup. Note that,
1012 // although we have two very different code paths, the serialized
1013 // representation is the same for both cases: a declaration name,
1014 // followed by a size, followed by references to the visible
1015 // declarations that have that name.
1016 uint64_t Offset = S.GetCurrentBitNo();
1017 RecordData Record;
1018 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001019 if (!Map)
1020 return 0;
1021
Douglas Gregorc34897d2009-04-09 22:27:44 +00001022 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1023 D != DEnd; ++D) {
1024 AddDeclarationName(D->first, Record);
1025 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1026 Record.push_back(Result.second - Result.first);
1027 for(; Result.first != Result.second; ++Result.first)
1028 AddDeclRef(*Result.first, Record);
1029 }
1030
1031 if (Record.size() == 0)
1032 return 0;
1033
1034 S.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
1035 return Offset;
1036}
1037
1038/// \brief Write a block containing all of the declarations.
1039void PCHWriter::WriteDeclsBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001040 // Enter the declarations block.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001041 S.EnterSubblock(pch::DECLS_BLOCK_ID, 2);
1042
1043 // Emit all of the declarations.
1044 RecordData Record;
1045 PCHDeclWriter W(*this, Record);
1046 while (!DeclsToEmit.empty()) {
1047 // Pull the next declaration off the queue
1048 Decl *D = DeclsToEmit.front();
1049 DeclsToEmit.pop();
1050
1051 // If this declaration is also a DeclContext, write blocks for the
1052 // declarations that lexically stored inside its context and those
1053 // declarations that are visible from its context. These blocks
1054 // are written before the declaration itself so that we can put
1055 // their offsets into the record for the declaration.
1056 uint64_t LexicalOffset = 0;
1057 uint64_t VisibleOffset = 0;
1058 DeclContext *DC = dyn_cast<DeclContext>(D);
1059 if (DC) {
1060 LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
1061 VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
1062 }
1063
1064 // Determine the ID for this declaration
Douglas Gregorac8f2802009-04-10 17:25:41 +00001065 pch::DeclID ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001066 if (ID == 0)
1067 ID = DeclIDs.size();
1068
1069 unsigned Index = ID - 1;
1070
1071 // Record the offset for this declaration
1072 if (DeclOffsets.size() == Index)
1073 DeclOffsets.push_back(S.GetCurrentBitNo());
1074 else if (DeclOffsets.size() < Index) {
1075 DeclOffsets.resize(Index+1);
1076 DeclOffsets[Index] = S.GetCurrentBitNo();
1077 }
1078
1079 // Build and emit a record for this declaration
1080 Record.clear();
1081 W.Code = (pch::DeclCode)0;
1082 W.Visit(D);
1083 if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001084 assert(W.Code && "Unhandled declaration kind while generating PCH");
Douglas Gregorc34897d2009-04-09 22:27:44 +00001085 S.EmitRecord(W.Code, Record);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001086
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001087 // Flush any expressions that were written as part of this declaration.
1088 FlushExprs();
1089
Douglas Gregor631f6c62009-04-14 00:24:19 +00001090 // Note external declarations so that we can add them to a record
1091 // in the PCH file later.
1092 if (isa<FileScopeAsmDecl>(D))
1093 ExternalDefinitions.push_back(ID);
1094 else if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
1095 if (// Non-static file-scope variables with initializers or that
1096 // are tentative definitions.
1097 (Var->isFileVarDecl() &&
1098 (Var->getInit() || Var->getStorageClass() == VarDecl::None)) ||
1099 // Out-of-line definitions of static data members (C++).
1100 (Var->getDeclContext()->isRecord() &&
1101 !Var->getLexicalDeclContext()->isRecord() &&
1102 Var->getStorageClass() == VarDecl::Static))
1103 ExternalDefinitions.push_back(ID);
1104 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1105 if (Func->isThisDeclarationADefinition() &&
1106 Func->getStorageClass() != FunctionDecl::Static &&
1107 !Func->isInline())
1108 ExternalDefinitions.push_back(ID);
1109 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001110 }
1111
1112 // Exit the declarations block
1113 S.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001114}
1115
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001116/// \brief Write the identifier table into the PCH file.
1117///
1118/// The identifier table consists of a blob containing string data
1119/// (the actual identifiers themselves) and a separate "offsets" index
1120/// that maps identifier IDs to locations within the blob.
1121void PCHWriter::WriteIdentifierTable() {
1122 using namespace llvm;
1123
1124 // Create and write out the blob that contains the identifier
1125 // strings.
1126 RecordData IdentOffsets;
1127 IdentOffsets.resize(IdentifierIDs.size());
1128 {
1129 // Create the identifier string data.
1130 std::vector<char> Data;
1131 Data.push_back(0); // Data must not be empty.
1132 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1133 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1134 ID != IDEnd; ++ID) {
1135 assert(ID->first && "NULL identifier in identifier table");
1136
1137 // Make sure we're starting on an odd byte. The PCH reader
1138 // expects the low bit to be set on all of the offsets.
1139 if ((Data.size() & 0x01) == 0)
1140 Data.push_back((char)0);
1141
1142 IdentOffsets[ID->second - 1] = Data.size();
1143 Data.insert(Data.end(),
1144 ID->first->getName(),
1145 ID->first->getName() + ID->first->getLength());
1146 Data.push_back((char)0);
1147 }
1148
1149 // Create a blob abbreviation
1150 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1151 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
1152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
1153 unsigned IDTableAbbrev = S.EmitAbbrev(Abbrev);
1154
1155 // Write the identifier table
1156 RecordData Record;
1157 Record.push_back(pch::IDENTIFIER_TABLE);
1158 S.EmitRecordWithBlob(IDTableAbbrev, Record, &Data.front(), Data.size());
1159 }
1160
1161 // Write the offsets table for identifier IDs.
1162 S.EmitRecord(pch::IDENTIFIER_OFFSET, IdentOffsets);
1163}
1164
Douglas Gregorc34897d2009-04-09 22:27:44 +00001165PCHWriter::PCHWriter(llvm::BitstreamWriter &S)
1166 : S(S), NextTypeID(pch::NUM_PREDEF_TYPE_IDS) { }
1167
Chris Lattner850eabd2009-04-10 18:08:30 +00001168void PCHWriter::WritePCH(ASTContext &Context, const Preprocessor &PP) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001169 // Emit the file header.
1170 S.Emit((unsigned)'C', 8);
1171 S.Emit((unsigned)'P', 8);
1172 S.Emit((unsigned)'C', 8);
1173 S.Emit((unsigned)'H', 8);
1174
1175 // The translation unit is the first declaration we'll emit.
1176 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1177 DeclsToEmit.push(Context.getTranslationUnitDecl());
1178
1179 // Write the remaining PCH contents.
Douglas Gregorb5887f32009-04-10 21:16:55 +00001180 S.EnterSubblock(pch::PCH_BLOCK_ID, 3);
1181 WriteTargetTriple(Context.Target);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001182 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregorab1cef72009-04-10 03:52:48 +00001183 WriteSourceManagerBlock(Context.getSourceManager());
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001184 WritePreprocessor(PP);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001185 WriteTypesBlock(Context);
1186 WriteDeclsBlock(Context);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001187 WriteIdentifierTable();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001188 S.EmitRecord(pch::TYPE_OFFSET, TypeOffsets);
1189 S.EmitRecord(pch::DECL_OFFSET, DeclOffsets);
Douglas Gregor631f6c62009-04-14 00:24:19 +00001190 if (!ExternalDefinitions.empty())
1191 S.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001192 S.ExitBlock();
1193}
1194
1195void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1196 Record.push_back(Loc.getRawEncoding());
1197}
1198
1199void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1200 Record.push_back(Value.getBitWidth());
1201 unsigned N = Value.getNumWords();
1202 const uint64_t* Words = Value.getRawData();
1203 for (unsigned I = 0; I != N; ++I)
1204 Record.push_back(Words[I]);
1205}
1206
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001207void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1208 Record.push_back(Value.isUnsigned());
1209 AddAPInt(Value, Record);
1210}
1211
Douglas Gregore2f37202009-04-14 21:55:33 +00001212void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1213 AddAPInt(Value.bitcastToAPInt(), Record);
1214}
1215
Douglas Gregorc34897d2009-04-09 22:27:44 +00001216void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001217 if (II == 0) {
1218 Record.push_back(0);
1219 return;
1220 }
1221
1222 pch::IdentID &ID = IdentifierIDs[II];
1223 if (ID == 0)
1224 ID = IdentifierIDs.size();
1225
1226 Record.push_back(ID);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001227}
1228
1229void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1230 if (T.isNull()) {
1231 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1232 return;
1233 }
1234
1235 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001236 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001237 switch (BT->getKind()) {
1238 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1239 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1240 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1241 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1242 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1243 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1244 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1245 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1246 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1247 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1248 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1249 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1250 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1251 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1252 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1253 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1254 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1255 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1256 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1257 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1258 }
1259
1260 Record.push_back((ID << 3) | T.getCVRQualifiers());
1261 return;
1262 }
1263
Douglas Gregorac8f2802009-04-10 17:25:41 +00001264 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001265 if (ID == 0) // we haven't seen this type before
1266 ID = NextTypeID++;
1267
1268 // Encode the type qualifiers in the type reference.
1269 Record.push_back((ID << 3) | T.getCVRQualifiers());
1270}
1271
1272void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1273 if (D == 0) {
1274 Record.push_back(0);
1275 return;
1276 }
1277
Douglas Gregorac8f2802009-04-10 17:25:41 +00001278 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001279 if (ID == 0) {
1280 // We haven't seen this declaration before. Give it a new ID and
1281 // enqueue it in the list of declarations to emit.
1282 ID = DeclIDs.size();
1283 DeclsToEmit.push(const_cast<Decl *>(D));
1284 }
1285
1286 Record.push_back(ID);
1287}
1288
1289void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
1290 Record.push_back(Name.getNameKind());
1291 switch (Name.getNameKind()) {
1292 case DeclarationName::Identifier:
1293 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1294 break;
1295
1296 case DeclarationName::ObjCZeroArgSelector:
1297 case DeclarationName::ObjCOneArgSelector:
1298 case DeclarationName::ObjCMultiArgSelector:
1299 assert(false && "Serialization of Objective-C selectors unavailable");
1300 break;
1301
1302 case DeclarationName::CXXConstructorName:
1303 case DeclarationName::CXXDestructorName:
1304 case DeclarationName::CXXConversionFunctionName:
1305 AddTypeRef(Name.getCXXNameType(), Record);
1306 break;
1307
1308 case DeclarationName::CXXOperatorName:
1309 Record.push_back(Name.getCXXOverloadedOperator());
1310 break;
1311
1312 case DeclarationName::CXXUsingDirective:
1313 // No extra data to emit
1314 break;
1315 }
1316}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001317
Douglas Gregora151ba42009-04-14 23:32:43 +00001318/// \brief Write the given subexpression to the bitstream.
1319void PCHWriter::WriteSubExpr(Expr *E) {
1320 RecordData Record;
1321 PCHStmtWriter Writer(*this, Record);
1322
1323 if (!E) {
1324 S.EmitRecord(pch::EXPR_NULL, Record);
1325 return;
1326 }
1327
1328 Writer.Code = pch::EXPR_NULL;
1329 Writer.Visit(E);
1330 assert(Writer.Code != pch::EXPR_NULL &&
1331 "Unhandled expression writing PCH file");
1332 S.EmitRecord(Writer.Code, Record);
1333}
1334
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001335/// \brief Flush all of the expressions that have been added to the
1336/// queue via AddExpr().
1337void PCHWriter::FlushExprs() {
1338 RecordData Record;
1339 PCHStmtWriter Writer(*this, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001340
Douglas Gregora151ba42009-04-14 23:32:43 +00001341 for (unsigned I = 0, N = ExprsToEmit.size(); I != N; ++I) {
1342 Expr *E = ExprsToEmit[I];
1343
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001344 if (!E) {
1345 S.EmitRecord(pch::EXPR_NULL, Record);
1346 continue;
1347 }
1348
1349 Writer.Code = pch::EXPR_NULL;
1350 Writer.Visit(E);
1351 assert(Writer.Code != pch::EXPR_NULL &&
1352 "Unhandled expression writing PCH file");
1353 S.EmitRecord(Writer.Code, Record);
Douglas Gregora151ba42009-04-14 23:32:43 +00001354
1355 assert(N == ExprsToEmit.size() &&
1356 "Subexpression writen via AddExpr rather than WriteSubExpr!");
1357
1358 // Note that we are at the end of a full expression. Any
1359 // expression records that follow this one are part of a different
1360 // expression.
1361 Record.clear();
1362 S.EmitRecord(pch::EXPR_STOP, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001363 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001364
1365 ExprsToEmit.clear();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001366}