blob: dacb2cdfd3a160e757e73896b3e12585f03e03a4 [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"
Douglas Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregor3251ceb2009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000036#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000037using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// Type serialization
41//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000042
Douglas Gregor2cf26342009-04-09 22:27:44 +000043namespace {
44 class VISIBILITY_HIDDEN PCHTypeWriter {
45 PCHWriter &Writer;
46 PCHWriter::RecordData &Record;
47
48 public:
49 /// \brief Type code that corresponds to the record generated.
50 pch::TypeCode Code;
51
52 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor4fed3f42009-04-27 18:38:38 +000053 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000054
55 void VisitArrayType(const ArrayType *T);
56 void VisitFunctionType(const FunctionType *T);
57 void VisitTagType(const TagType *T);
58
59#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
60#define ABSTRACT_TYPE(Class, Base)
61#define DEPENDENT_TYPE(Class, Base)
62#include "clang/AST/TypeNodes.def"
63 };
64}
65
66void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
67 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
68 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
69 Record.push_back(T->getAddressSpace());
70 Code = pch::TYPE_EXT_QUAL;
71}
72
73void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
74 assert(false && "Built-in types are never serialized");
75}
76
77void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
78 Record.push_back(T->getWidth());
79 Record.push_back(T->isSigned());
80 Code = pch::TYPE_FIXED_WIDTH_INT;
81}
82
83void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
84 Writer.AddTypeRef(T->getElementType(), Record);
85 Code = pch::TYPE_COMPLEX;
86}
87
88void PCHTypeWriter::VisitPointerType(const PointerType *T) {
89 Writer.AddTypeRef(T->getPointeeType(), Record);
90 Code = pch::TYPE_POINTER;
91}
92
93void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
94 Writer.AddTypeRef(T->getPointeeType(), Record);
95 Code = pch::TYPE_BLOCK_POINTER;
96}
97
98void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
99 Writer.AddTypeRef(T->getPointeeType(), Record);
100 Code = pch::TYPE_LVALUE_REFERENCE;
101}
102
103void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
104 Writer.AddTypeRef(T->getPointeeType(), Record);
105 Code = pch::TYPE_RVALUE_REFERENCE;
106}
107
108void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
109 Writer.AddTypeRef(T->getPointeeType(), Record);
110 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
111 Code = pch::TYPE_MEMBER_POINTER;
112}
113
114void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
115 Writer.AddTypeRef(T->getElementType(), Record);
116 Record.push_back(T->getSizeModifier()); // FIXME: stable values
117 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
118}
119
120void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
121 VisitArrayType(T);
122 Writer.AddAPInt(T->getSize(), Record);
123 Code = pch::TYPE_CONSTANT_ARRAY;
124}
125
126void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
127 VisitArrayType(T);
128 Code = pch::TYPE_INCOMPLETE_ARRAY;
129}
130
131void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
132 VisitArrayType(T);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000133 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000134 Code = pch::TYPE_VARIABLE_ARRAY;
135}
136
137void PCHTypeWriter::VisitVectorType(const VectorType *T) {
138 Writer.AddTypeRef(T->getElementType(), Record);
139 Record.push_back(T->getNumElements());
140 Code = pch::TYPE_VECTOR;
141}
142
143void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
144 VisitVectorType(T);
145 Code = pch::TYPE_EXT_VECTOR;
146}
147
148void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
149 Writer.AddTypeRef(T->getResultType(), Record);
150}
151
152void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
153 VisitFunctionType(T);
154 Code = pch::TYPE_FUNCTION_NO_PROTO;
155}
156
157void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
158 VisitFunctionType(T);
159 Record.push_back(T->getNumArgs());
160 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
161 Writer.AddTypeRef(T->getArgType(I), Record);
162 Record.push_back(T->isVariadic());
163 Record.push_back(T->getTypeQuals());
164 Code = pch::TYPE_FUNCTION_PROTO;
165}
166
167void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
168 Writer.AddDeclRef(T->getDecl(), Record);
169 Code = pch::TYPE_TYPEDEF;
170}
171
172void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000173 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000174 Code = pch::TYPE_TYPEOF_EXPR;
175}
176
177void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
178 Writer.AddTypeRef(T->getUnderlyingType(), Record);
179 Code = pch::TYPE_TYPEOF;
180}
181
182void PCHTypeWriter::VisitTagType(const TagType *T) {
183 Writer.AddDeclRef(T->getDecl(), Record);
184 assert(!T->isBeingDefined() &&
185 "Cannot serialize in the middle of a type definition");
186}
187
188void PCHTypeWriter::VisitRecordType(const RecordType *T) {
189 VisitTagType(T);
190 Code = pch::TYPE_RECORD;
191}
192
193void PCHTypeWriter::VisitEnumType(const EnumType *T) {
194 VisitTagType(T);
195 Code = pch::TYPE_ENUM;
196}
197
198void
199PCHTypeWriter::VisitTemplateSpecializationType(
200 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000201 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000202 assert(false && "Cannot serialize template specialization types");
203}
204
205void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000206 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000207 assert(false && "Cannot serialize qualified name types");
208}
209
210void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
211 Writer.AddDeclRef(T->getDecl(), Record);
212 Code = pch::TYPE_OBJC_INTERFACE;
213}
214
215void
216PCHTypeWriter::VisitObjCQualifiedInterfaceType(
217 const ObjCQualifiedInterfaceType *T) {
218 VisitObjCInterfaceType(T);
219 Record.push_back(T->getNumProtocols());
220 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
221 Writer.AddDeclRef(T->getProtocol(I), Record);
222 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
223}
224
225void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
226 Record.push_back(T->getNumProtocols());
227 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
228 Writer.AddDeclRef(T->getProtocols(I), Record);
229 Code = pch::TYPE_OBJC_QUALIFIED_ID;
230}
231
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000232//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000233// PCHWriter Implementation
234//===----------------------------------------------------------------------===//
235
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000236static void EmitBlockID(unsigned ID, const char *Name,
237 llvm::BitstreamWriter &Stream,
238 PCHWriter::RecordData &Record) {
239 Record.clear();
240 Record.push_back(ID);
241 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
242
243 // Emit the block name if present.
244 if (Name == 0 || Name[0] == 0) return;
245 Record.clear();
246 while (*Name)
247 Record.push_back(*Name++);
248 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
249}
250
251static void EmitRecordID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 while (*Name)
257 Record.push_back(*Name++);
258 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000259}
260
261static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
262 PCHWriter::RecordData &Record) {
263#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
264 RECORD(STMT_STOP);
265 RECORD(STMT_NULL_PTR);
266 RECORD(STMT_NULL);
267 RECORD(STMT_COMPOUND);
268 RECORD(STMT_CASE);
269 RECORD(STMT_DEFAULT);
270 RECORD(STMT_LABEL);
271 RECORD(STMT_IF);
272 RECORD(STMT_SWITCH);
273 RECORD(STMT_WHILE);
274 RECORD(STMT_DO);
275 RECORD(STMT_FOR);
276 RECORD(STMT_GOTO);
277 RECORD(STMT_INDIRECT_GOTO);
278 RECORD(STMT_CONTINUE);
279 RECORD(STMT_BREAK);
280 RECORD(STMT_RETURN);
281 RECORD(STMT_DECL);
282 RECORD(STMT_ASM);
283 RECORD(EXPR_PREDEFINED);
284 RECORD(EXPR_DECL_REF);
285 RECORD(EXPR_INTEGER_LITERAL);
286 RECORD(EXPR_FLOATING_LITERAL);
287 RECORD(EXPR_IMAGINARY_LITERAL);
288 RECORD(EXPR_STRING_LITERAL);
289 RECORD(EXPR_CHARACTER_LITERAL);
290 RECORD(EXPR_PAREN);
291 RECORD(EXPR_UNARY_OPERATOR);
292 RECORD(EXPR_SIZEOF_ALIGN_OF);
293 RECORD(EXPR_ARRAY_SUBSCRIPT);
294 RECORD(EXPR_CALL);
295 RECORD(EXPR_MEMBER);
296 RECORD(EXPR_BINARY_OPERATOR);
297 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
298 RECORD(EXPR_CONDITIONAL_OPERATOR);
299 RECORD(EXPR_IMPLICIT_CAST);
300 RECORD(EXPR_CSTYLE_CAST);
301 RECORD(EXPR_COMPOUND_LITERAL);
302 RECORD(EXPR_EXT_VECTOR_ELEMENT);
303 RECORD(EXPR_INIT_LIST);
304 RECORD(EXPR_DESIGNATED_INIT);
305 RECORD(EXPR_IMPLICIT_VALUE_INIT);
306 RECORD(EXPR_VA_ARG);
307 RECORD(EXPR_ADDR_LABEL);
308 RECORD(EXPR_STMT);
309 RECORD(EXPR_TYPES_COMPATIBLE);
310 RECORD(EXPR_CHOOSE);
311 RECORD(EXPR_GNU_NULL);
312 RECORD(EXPR_SHUFFLE_VECTOR);
313 RECORD(EXPR_BLOCK);
314 RECORD(EXPR_BLOCK_DECL_REF);
315 RECORD(EXPR_OBJC_STRING_LITERAL);
316 RECORD(EXPR_OBJC_ENCODE);
317 RECORD(EXPR_OBJC_SELECTOR_EXPR);
318 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
319 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
320 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
321 RECORD(EXPR_OBJC_KVC_REF_EXPR);
322 RECORD(EXPR_OBJC_MESSAGE_EXPR);
323 RECORD(EXPR_OBJC_SUPER_EXPR);
324 RECORD(STMT_OBJC_FOR_COLLECTION);
325 RECORD(STMT_OBJC_CATCH);
326 RECORD(STMT_OBJC_FINALLY);
327 RECORD(STMT_OBJC_AT_TRY);
328 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
329 RECORD(STMT_OBJC_AT_THROW);
330#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000331}
332
333void PCHWriter::WriteBlockInfoBlock() {
334 RecordData Record;
335 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
336
Chris Lattner2f4efd12009-04-27 00:40:25 +0000337#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000338#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
339
340 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000341 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000342 RECORD(TYPE_OFFSET);
343 RECORD(DECL_OFFSET);
344 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000345 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000346 RECORD(IDENTIFIER_OFFSET);
347 RECORD(IDENTIFIER_TABLE);
348 RECORD(EXTERNAL_DEFINITIONS);
349 RECORD(SPECIAL_TYPES);
350 RECORD(STATISTICS);
351 RECORD(TENTATIVE_DEFINITIONS);
352 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
353 RECORD(SELECTOR_OFFSETS);
354 RECORD(METHOD_POOL);
355 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000356 RECORD(SOURCE_LOCATION_OFFSETS);
357 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000358 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000359 RECORD(EXT_VECTOR_DECLS);
360 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000361
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000362 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000363 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000364 RECORD(SM_SLOC_FILE_ENTRY);
365 RECORD(SM_SLOC_BUFFER_ENTRY);
366 RECORD(SM_SLOC_BUFFER_BLOB);
367 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
368 RECORD(SM_LINE_TABLE);
369 RECORD(SM_HEADER_FILE_INFO);
370
371 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000372 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000373 RECORD(PP_MACRO_OBJECT_LIKE);
374 RECORD(PP_MACRO_FUNCTION_LIKE);
375 RECORD(PP_TOKEN);
376
377 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000378 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000379 RECORD(TYPE_EXT_QUAL);
380 RECORD(TYPE_FIXED_WIDTH_INT);
381 RECORD(TYPE_COMPLEX);
382 RECORD(TYPE_POINTER);
383 RECORD(TYPE_BLOCK_POINTER);
384 RECORD(TYPE_LVALUE_REFERENCE);
385 RECORD(TYPE_RVALUE_REFERENCE);
386 RECORD(TYPE_MEMBER_POINTER);
387 RECORD(TYPE_CONSTANT_ARRAY);
388 RECORD(TYPE_INCOMPLETE_ARRAY);
389 RECORD(TYPE_VARIABLE_ARRAY);
390 RECORD(TYPE_VECTOR);
391 RECORD(TYPE_EXT_VECTOR);
392 RECORD(TYPE_FUNCTION_PROTO);
393 RECORD(TYPE_FUNCTION_NO_PROTO);
394 RECORD(TYPE_TYPEDEF);
395 RECORD(TYPE_TYPEOF_EXPR);
396 RECORD(TYPE_TYPEOF);
397 RECORD(TYPE_RECORD);
398 RECORD(TYPE_ENUM);
399 RECORD(TYPE_OBJC_INTERFACE);
400 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
401 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000402 // Statements and Exprs can occur in the Types block.
403 AddStmtsExprs(Stream, Record);
404
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000405 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000406 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000407 RECORD(DECL_ATTR);
408 RECORD(DECL_TRANSLATION_UNIT);
409 RECORD(DECL_TYPEDEF);
410 RECORD(DECL_ENUM);
411 RECORD(DECL_RECORD);
412 RECORD(DECL_ENUM_CONSTANT);
413 RECORD(DECL_FUNCTION);
414 RECORD(DECL_OBJC_METHOD);
415 RECORD(DECL_OBJC_INTERFACE);
416 RECORD(DECL_OBJC_PROTOCOL);
417 RECORD(DECL_OBJC_IVAR);
418 RECORD(DECL_OBJC_AT_DEFS_FIELD);
419 RECORD(DECL_OBJC_CLASS);
420 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
421 RECORD(DECL_OBJC_CATEGORY);
422 RECORD(DECL_OBJC_CATEGORY_IMPL);
423 RECORD(DECL_OBJC_IMPLEMENTATION);
424 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
425 RECORD(DECL_OBJC_PROPERTY);
426 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000427 RECORD(DECL_FIELD);
428 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000429 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000430 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000431 RECORD(DECL_ORIGINAL_PARM_VAR);
432 RECORD(DECL_FILE_SCOPE_ASM);
433 RECORD(DECL_BLOCK);
434 RECORD(DECL_CONTEXT_LEXICAL);
435 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000436 // Statements and Exprs can occur in the Decls block.
437 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000438#undef RECORD
439#undef BLOCK
440 Stream.ExitBlock();
441}
442
443
Douglas Gregorab41e632009-04-27 22:23:34 +0000444/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
445void PCHWriter::WriteMetadata(const TargetInfo &Target) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000446 using namespace llvm;
447 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
Douglas Gregorab41e632009-04-27 22:23:34 +0000448 Abbrev->Add(BitCodeAbbrevOp(pch::METADATA));
449 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
454 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000455
456 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000457 Record.push_back(pch::METADATA);
458 Record.push_back(pch::VERSION_MAJOR);
459 Record.push_back(pch::VERSION_MINOR);
460 Record.push_back(CLANG_VERSION_MAJOR);
461 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000462 const char *Triple = Target.getTargetTriple();
Douglas Gregorab41e632009-04-27 22:23:34 +0000463 Stream.EmitRecordWithBlob(AbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000464}
465
466/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000467void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
468 RecordData Record;
469 Record.push_back(LangOpts.Trigraphs);
470 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
471 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
472 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
473 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
474 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
475 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
476 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
477 Record.push_back(LangOpts.C99); // C99 Support
478 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
479 Record.push_back(LangOpts.CPlusPlus); // C++ Support
480 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000481 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
482
483 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
484 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
485 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
486
487 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000488 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
489 Record.push_back(LangOpts.LaxVectorConversions);
490 Record.push_back(LangOpts.Exceptions); // Support exception handling.
491
492 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
493 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
494 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
495
Chris Lattnerea5ce472009-04-27 07:35:58 +0000496 // Whether static initializers are protected by locks.
497 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000498 Record.push_back(LangOpts.Blocks); // block extension to C
499 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
500 // they are unused.
501 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
502 // (modulo the platform support).
503
504 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
505 // signed integer arithmetic overflows.
506
507 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
508 // may be ripped out at any time.
509
510 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
511 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
512 // defined.
513 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
514 // opposed to __DYNAMIC__).
515 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
516
517 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
518 // used (instead of C99 semantics).
519 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
520 Record.push_back(LangOpts.getGCMode());
521 Record.push_back(LangOpts.getVisibilityMode());
522 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000523 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000524}
525
Douglas Gregor14f79002009-04-10 03:52:48 +0000526//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000527// stat cache Serialization
528//===----------------------------------------------------------------------===//
529
530namespace {
531// Trait used for the on-disk hash table of stat cache results.
532class VISIBILITY_HIDDEN PCHStatCacheTrait {
533public:
534 typedef const char * key_type;
535 typedef key_type key_type_ref;
536
537 typedef std::pair<int, struct stat> data_type;
538 typedef const data_type& data_type_ref;
539
540 static unsigned ComputeHash(const char *path) {
541 return BernsteinHash(path);
542 }
543
544 std::pair<unsigned,unsigned>
545 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
546 data_type_ref Data) {
547 unsigned StrLen = strlen(path);
548 clang::io::Emit16(Out, StrLen);
549 unsigned DataLen = 1; // result value
550 if (Data.first == 0)
551 DataLen += 4 + 4 + 2 + 8 + 8;
552 clang::io::Emit8(Out, DataLen);
553 return std::make_pair(StrLen + 1, DataLen);
554 }
555
556 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
557 Out.write(path, KeyLen);
558 }
559
560 void EmitData(llvm::raw_ostream& Out, key_type_ref,
561 data_type_ref Data, unsigned DataLen) {
562 using namespace clang::io;
563 uint64_t Start = Out.tell(); (void)Start;
564
565 // Result of stat()
566 Emit8(Out, Data.first? 1 : 0);
567
568 if (Data.first == 0) {
569 Emit32(Out, (uint32_t) Data.second.st_ino);
570 Emit32(Out, (uint32_t) Data.second.st_dev);
571 Emit16(Out, (uint16_t) Data.second.st_mode);
572 Emit64(Out, (uint64_t) Data.second.st_mtime);
573 Emit64(Out, (uint64_t) Data.second.st_size);
574 }
575
576 assert(Out.tell() - Start == DataLen && "Wrong data length");
577 }
578};
579} // end anonymous namespace
580
581/// \brief Write the stat() system call cache to the PCH file.
582void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
583 // Build the on-disk hash table containing information about every
584 // stat() call.
585 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
586 unsigned NumStatEntries = 0;
587 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
588 StatEnd = StatCalls.end();
589 Stat != StatEnd; ++Stat, ++NumStatEntries)
590 Generator.insert(Stat->first(), Stat->second);
591
592 // Create the on-disk hash table in a buffer.
593 llvm::SmallVector<char, 4096> StatCacheData;
594 uint32_t BucketOffset;
595 {
596 llvm::raw_svector_ostream Out(StatCacheData);
597 // Make sure that no bucket is at offset 0
598 clang::io::Emit32(Out, 0);
599 BucketOffset = Generator.Emit(Out);
600 }
601
602 // Create a blob abbreviation
603 using namespace llvm;
604 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
605 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
606 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
607 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
608 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
609 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
610
611 // Write the stat cache
612 RecordData Record;
613 Record.push_back(pch::STAT_CACHE);
614 Record.push_back(BucketOffset);
615 Record.push_back(NumStatEntries);
616 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
617 &StatCacheData.front(),
618 StatCacheData.size());
619}
620
621//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000622// Source Manager Serialization
623//===----------------------------------------------------------------------===//
624
625/// \brief Create an abbreviation for the SLocEntry that refers to a
626/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000627static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000628 using namespace llvm;
629 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
630 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
631 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
632 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
634 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000636 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000637}
638
639/// \brief Create an abbreviation for the SLocEntry that refers to a
640/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000641static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000642 using namespace llvm;
643 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
644 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000650 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000651}
652
653/// \brief Create an abbreviation for the SLocEntry that refers to a
654/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000655static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000656 using namespace llvm;
657 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
658 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000660 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000661}
662
663/// \brief Create an abbreviation for the SLocEntry that refers to an
664/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000665static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000666 using namespace llvm;
667 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
668 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
671 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000674 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000675}
676
677/// \brief Writes the block containing the serialized form of the
678/// source manager.
679///
680/// TODO: We should probably use an on-disk hash table (stored in a
681/// blob), indexed based on the file name, so that we only create
682/// entries for files that we actually need. In the common case (no
683/// errors), we probably won't have to create file entries for any of
684/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000685void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
686 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000687 RecordData Record;
688
Chris Lattnerf04ad692009-04-10 17:16:57 +0000689 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000690 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000691
692 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000693 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
694 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
695 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
696 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000697
Douglas Gregorbd945002009-04-13 16:31:14 +0000698 // Write the line table.
699 if (SourceMgr.hasLineTable()) {
700 LineTableInfo &LineTable = SourceMgr.getLineTable();
701
702 // Emit the file names
703 Record.push_back(LineTable.getNumFilenames());
704 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
705 // Emit the file name
706 const char *Filename = LineTable.getFilename(I);
707 unsigned FilenameLen = Filename? strlen(Filename) : 0;
708 Record.push_back(FilenameLen);
709 if (FilenameLen)
710 Record.insert(Record.end(), Filename, Filename + FilenameLen);
711 }
712
713 // Emit the line entries
714 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
715 L != LEnd; ++L) {
716 // Emit the file ID
717 Record.push_back(L->first);
718
719 // Emit the line entries
720 Record.push_back(L->second.size());
721 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
722 LEEnd = L->second.end();
723 LE != LEEnd; ++LE) {
724 Record.push_back(LE->FileOffset);
725 Record.push_back(LE->LineNo);
726 Record.push_back(LE->FilenameID);
727 Record.push_back((unsigned)LE->FileKind);
728 Record.push_back(LE->IncludeOffset);
729 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000730 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000731 }
732 }
733
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000734 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000735 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000736 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000737 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
738 E = HS.header_file_end();
739 I != E; ++I) {
740 Record.push_back(I->isImport);
741 Record.push_back(I->DirInfo);
742 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000743 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000744 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
745 Record.clear();
746 }
747
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000748 // Write out the source location entry table. We skip the first
749 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000750 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000751 RecordData PreloadSLocs;
752 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
753 for (SourceManager::sloc_entry_iterator
754 SLoc = SourceMgr.sloc_entry_begin() + 1,
755 SLocEnd = SourceMgr.sloc_entry_end();
756 SLoc != SLocEnd; ++SLoc) {
757 // Record the offset of this source-location entry.
758 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
759
760 // Figure out which record code to use.
761 unsigned Code;
762 if (SLoc->isFile()) {
763 if (SLoc->getFile().getContentCache()->Entry)
764 Code = pch::SM_SLOC_FILE_ENTRY;
765 else
766 Code = pch::SM_SLOC_BUFFER_ENTRY;
767 } else
768 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
769 Record.clear();
770 Record.push_back(Code);
771
772 Record.push_back(SLoc->getOffset());
773 if (SLoc->isFile()) {
774 const SrcMgr::FileInfo &File = SLoc->getFile();
775 Record.push_back(File.getIncludeLoc().getRawEncoding());
776 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
777 Record.push_back(File.hasLineDirectives());
778
779 const SrcMgr::ContentCache *Content = File.getContentCache();
780 if (Content->Entry) {
781 // The source location entry is a file. The blob associated
782 // with this entry is the file name.
783 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
784 Content->Entry->getName(),
785 strlen(Content->Entry->getName()));
786
787 // FIXME: For now, preload all file source locations, so that
788 // we get the appropriate File entries in the reader. This is
789 // a temporary measure.
790 PreloadSLocs.push_back(SLocEntryOffsets.size());
791 } else {
792 // The source location entry is a buffer. The blob associated
793 // with this entry contains the contents of the buffer.
794
795 // We add one to the size so that we capture the trailing NULL
796 // that is required by llvm::MemoryBuffer::getMemBuffer (on
797 // the reader side).
798 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
799 const char *Name = Buffer->getBufferIdentifier();
800 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
801 Record.clear();
802 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
803 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
804 Buffer->getBufferStart(),
805 Buffer->getBufferSize() + 1);
806
807 if (strcmp(Name, "<built-in>") == 0)
808 PreloadSLocs.push_back(SLocEntryOffsets.size());
809 }
810 } else {
811 // The source location entry is an instantiation.
812 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
813 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
814 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
815 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
816
817 // Compute the token length for this macro expansion.
818 unsigned NextOffset = SourceMgr.getNextOffset();
819 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
820 if (++NextSLoc != SLocEnd)
821 NextOffset = NextSLoc->getOffset();
822 Record.push_back(NextOffset - SLoc->getOffset() - 1);
823 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
824 }
825 }
826
Douglas Gregorc9490c02009-04-16 22:23:12 +0000827 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000828
829 if (SLocEntryOffsets.empty())
830 return;
831
832 // Write the source-location offsets table into the PCH block. This
833 // table is used for lazily loading source-location information.
834 using namespace llvm;
835 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
836 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
837 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
840 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
841
842 Record.clear();
843 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
844 Record.push_back(SLocEntryOffsets.size());
845 Record.push_back(SourceMgr.getNextOffset());
846 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
847 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000848 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000849
850 // Write the source location entry preloads array, telling the PCH
851 // reader which source locations entries it should load eagerly.
852 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000853}
854
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000855//===----------------------------------------------------------------------===//
856// Preprocessor Serialization
857//===----------------------------------------------------------------------===//
858
Chris Lattner0b1fb982009-04-10 17:15:23 +0000859/// \brief Writes the block containing the serialized form of the
860/// preprocessor.
861///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000862void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000863 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000864
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000865 // If the preprocessor __COUNTER__ value has been bumped, remember it.
866 if (PP.getCounterValue() != 0) {
867 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000868 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000869 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000870 }
871
872 // Enter the preprocessor block.
873 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000874
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000875 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
876 // FIXME: use diagnostics subsystem for localization etc.
877 if (PP.SawDateOrTime())
878 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
879
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000880 // Loop over all the macro definitions that are live at the end of the file,
881 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000882 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
883 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000884 // FIXME: This emits macros in hash table order, we should do it in a stable
885 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000886 MacroInfo *MI = I->second;
887
888 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
889 // been redefined by the header (in which case they are not isBuiltinMacro).
890 if (MI->isBuiltinMacro())
891 continue;
892
Douglas Gregor37e26842009-04-21 23:56:24 +0000893 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000894 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000895 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000896 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
897 Record.push_back(MI->isUsed());
898
899 unsigned Code;
900 if (MI->isObjectLike()) {
901 Code = pch::PP_MACRO_OBJECT_LIKE;
902 } else {
903 Code = pch::PP_MACRO_FUNCTION_LIKE;
904
905 Record.push_back(MI->isC99Varargs());
906 Record.push_back(MI->isGNUVarargs());
907 Record.push_back(MI->getNumArgs());
908 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
909 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000910 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000911 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000912 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000913 Record.clear();
914
Chris Lattnerdf961c22009-04-10 18:08:30 +0000915 // Emit the tokens array.
916 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
917 // Note that we know that the preprocessor does not have any annotation
918 // tokens in it because they are created by the parser, and thus can't be
919 // in a macro definition.
920 const Token &Tok = MI->getReplacementToken(TokNo);
921
922 Record.push_back(Tok.getLocation().getRawEncoding());
923 Record.push_back(Tok.getLength());
924
Chris Lattnerdf961c22009-04-10 18:08:30 +0000925 // FIXME: When reading literal tokens, reconstruct the literal pointer if
926 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000927 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000928
929 // FIXME: Should translate token kind to a stable encoding.
930 Record.push_back(Tok.getKind());
931 // FIXME: Should translate token flags to a stable encoding.
932 Record.push_back(Tok.getFlags());
933
Douglas Gregorc9490c02009-04-16 22:23:12 +0000934 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000935 Record.clear();
936 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000937 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000938 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000939 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000940}
941
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000942//===----------------------------------------------------------------------===//
943// Type Serialization
944//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000945
Douglas Gregor2cf26342009-04-09 22:27:44 +0000946/// \brief Write the representation of a type to the PCH stream.
947void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000948 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000949 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000950 ID = NextTypeID++;
951
952 // Record the offset for this type.
953 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000954 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000955 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
956 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000957 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000958 }
959
960 RecordData Record;
961
962 // Emit the type's representation.
963 PCHTypeWriter W(*this, Record);
964 switch (T->getTypeClass()) {
965 // For all of the concrete, non-dependent types, call the
966 // appropriate visitor function.
967#define TYPE(Class, Base) \
968 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
969#define ABSTRACT_TYPE(Class, Base)
970#define DEPENDENT_TYPE(Class, Base)
971#include "clang/AST/TypeNodes.def"
972
973 // For all of the dependent type nodes (which only occur in C++
974 // templates), produce an error.
975#define TYPE(Class, Base)
976#define DEPENDENT_TYPE(Class, Base) case Type::Class:
977#include "clang/AST/TypeNodes.def"
978 assert(false && "Cannot serialize dependent type nodes");
979 break;
980 }
981
982 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000983 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +0000984
985 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000986 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000987}
988
989/// \brief Write a block containing all of the types.
990void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000991 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000992 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000993
Douglas Gregor366809a2009-04-26 03:49:13 +0000994 // Emit all of the types that need to be emitted (so far).
995 while (!TypesToEmit.empty()) {
996 const Type *T = TypesToEmit.front();
997 TypesToEmit.pop();
998 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
999 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001000 }
1001
1002 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001003 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001004}
1005
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001006//===----------------------------------------------------------------------===//
1007// Declaration Serialization
1008//===----------------------------------------------------------------------===//
1009
Douglas Gregor2cf26342009-04-09 22:27:44 +00001010/// \brief Write the block containing all of the declaration IDs
1011/// lexically declared within the given DeclContext.
1012///
1013/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1014/// bistream, or 0 if no block was written.
1015uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1016 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001017 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001018 return 0;
1019
Douglas Gregorc9490c02009-04-16 22:23:12 +00001020 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001021 RecordData Record;
1022 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1023 DEnd = DC->decls_end(Context);
1024 D != DEnd; ++D)
1025 AddDeclRef(*D, Record);
1026
Douglas Gregor25123082009-04-22 22:34:57 +00001027 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001028 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001029 return Offset;
1030}
1031
1032/// \brief Write the block containing all of the declaration IDs
1033/// visible from the given DeclContext.
1034///
1035/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1036/// bistream, or 0 if no block was written.
1037uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1038 DeclContext *DC) {
1039 if (DC->getPrimaryContext() != DC)
1040 return 0;
1041
Douglas Gregoraff22df2009-04-21 22:32:33 +00001042 // Since there is no name lookup into functions or methods, and we
1043 // perform name lookup for the translation unit via the
1044 // IdentifierInfo chains, don't bother to build a
1045 // visible-declarations table for these entities.
1046 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001047 return 0;
1048
Douglas Gregor2cf26342009-04-09 22:27:44 +00001049 // Force the DeclContext to build a its name-lookup table.
1050 DC->lookup(Context, DeclarationName());
1051
1052 // Serialize the contents of the mapping used for lookup. Note that,
1053 // although we have two very different code paths, the serialized
1054 // representation is the same for both cases: a declaration name,
1055 // followed by a size, followed by references to the visible
1056 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001057 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001058 RecordData Record;
1059 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001060 if (!Map)
1061 return 0;
1062
Douglas Gregor2cf26342009-04-09 22:27:44 +00001063 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1064 D != DEnd; ++D) {
1065 AddDeclarationName(D->first, Record);
1066 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1067 Record.push_back(Result.second - Result.first);
1068 for(; Result.first != Result.second; ++Result.first)
1069 AddDeclRef(*Result.first, Record);
1070 }
1071
1072 if (Record.size() == 0)
1073 return 0;
1074
Douglas Gregorc9490c02009-04-16 22:23:12 +00001075 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001076 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001077 return Offset;
1078}
1079
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001080//===----------------------------------------------------------------------===//
1081// Global Method Pool and Selector Serialization
1082//===----------------------------------------------------------------------===//
1083
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001084namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001085// Trait used for the on-disk hash table used in the method pool.
1086class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1087 PCHWriter &Writer;
1088
1089public:
1090 typedef Selector key_type;
1091 typedef key_type key_type_ref;
1092
1093 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1094 typedef const data_type& data_type_ref;
1095
1096 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1097
1098 static unsigned ComputeHash(Selector Sel) {
1099 unsigned N = Sel.getNumArgs();
1100 if (N == 0)
1101 ++N;
1102 unsigned R = 5381;
1103 for (unsigned I = 0; I != N; ++I)
1104 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1105 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1106 return R;
1107 }
1108
1109 std::pair<unsigned,unsigned>
1110 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1111 data_type_ref Methods) {
1112 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1113 clang::io::Emit16(Out, KeyLen);
1114 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1115 for (const ObjCMethodList *Method = &Methods.first; Method;
1116 Method = Method->Next)
1117 if (Method->Method)
1118 DataLen += 4;
1119 for (const ObjCMethodList *Method = &Methods.second; Method;
1120 Method = Method->Next)
1121 if (Method->Method)
1122 DataLen += 4;
1123 clang::io::Emit16(Out, DataLen);
1124 return std::make_pair(KeyLen, DataLen);
1125 }
1126
Douglas Gregor83941df2009-04-25 17:48:32 +00001127 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1128 uint64_t Start = Out.tell();
1129 assert((Start >> 32) == 0 && "Selector key offset too large");
1130 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001131 unsigned N = Sel.getNumArgs();
1132 clang::io::Emit16(Out, N);
1133 if (N == 0)
1134 N = 1;
1135 for (unsigned I = 0; I != N; ++I)
1136 clang::io::Emit32(Out,
1137 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1138 }
1139
1140 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001141 data_type_ref Methods, unsigned DataLen) {
1142 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001143 unsigned NumInstanceMethods = 0;
1144 for (const ObjCMethodList *Method = &Methods.first; Method;
1145 Method = Method->Next)
1146 if (Method->Method)
1147 ++NumInstanceMethods;
1148
1149 unsigned NumFactoryMethods = 0;
1150 for (const ObjCMethodList *Method = &Methods.second; Method;
1151 Method = Method->Next)
1152 if (Method->Method)
1153 ++NumFactoryMethods;
1154
1155 clang::io::Emit16(Out, NumInstanceMethods);
1156 clang::io::Emit16(Out, NumFactoryMethods);
1157 for (const ObjCMethodList *Method = &Methods.first; Method;
1158 Method = Method->Next)
1159 if (Method->Method)
1160 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001161 for (const ObjCMethodList *Method = &Methods.second; Method;
1162 Method = Method->Next)
1163 if (Method->Method)
1164 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001165
1166 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001167 }
1168};
1169} // end anonymous namespace
1170
1171/// \brief Write the method pool into the PCH file.
1172///
1173/// The method pool contains both instance and factory methods, stored
1174/// in an on-disk hash table indexed by the selector.
1175void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1176 using namespace llvm;
1177
1178 // Create and write out the blob that contains the instance and
1179 // factor method pools.
1180 bool Empty = true;
1181 {
1182 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1183
1184 // Create the on-disk hash table representation. Start by
1185 // iterating through the instance method pool.
1186 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001187 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001188 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1189 Instance = SemaRef.InstanceMethodPool.begin(),
1190 InstanceEnd = SemaRef.InstanceMethodPool.end();
1191 Instance != InstanceEnd; ++Instance) {
1192 // Check whether there is a factory method with the same
1193 // selector.
1194 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1195 = SemaRef.FactoryMethodPool.find(Instance->first);
1196
1197 if (Factory == SemaRef.FactoryMethodPool.end())
1198 Generator.insert(Instance->first,
1199 std::make_pair(Instance->second,
1200 ObjCMethodList()));
1201 else
1202 Generator.insert(Instance->first,
1203 std::make_pair(Instance->second, Factory->second));
1204
Douglas Gregor83941df2009-04-25 17:48:32 +00001205 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001206 Empty = false;
1207 }
1208
1209 // Now iterate through the factory method pool, to pick up any
1210 // selectors that weren't already in the instance method pool.
1211 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1212 Factory = SemaRef.FactoryMethodPool.begin(),
1213 FactoryEnd = SemaRef.FactoryMethodPool.end();
1214 Factory != FactoryEnd; ++Factory) {
1215 // Check whether there is an instance method with the same
1216 // selector. If so, there is no work to do here.
1217 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1218 = SemaRef.InstanceMethodPool.find(Factory->first);
1219
Douglas Gregor83941df2009-04-25 17:48:32 +00001220 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001221 Generator.insert(Factory->first,
1222 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001223 ++NumSelectorsInMethodPool;
1224 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001225
1226 Empty = false;
1227 }
1228
Douglas Gregor83941df2009-04-25 17:48:32 +00001229 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001230 return;
1231
1232 // Create the on-disk hash table in a buffer.
1233 llvm::SmallVector<char, 4096> MethodPool;
1234 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001235 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001236 {
1237 PCHMethodPoolTrait Trait(*this);
1238 llvm::raw_svector_ostream Out(MethodPool);
1239 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001240 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001241 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001242
1243 // For every selector that we have seen but which was not
1244 // written into the hash table, write the selector itself and
1245 // record it's offset.
1246 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1247 if (SelectorOffsets[I] == 0)
1248 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001249 }
1250
1251 // Create a blob abbreviation
1252 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1253 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1257 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1258
Douglas Gregor83941df2009-04-25 17:48:32 +00001259 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001260 RecordData Record;
1261 Record.push_back(pch::METHOD_POOL);
1262 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001263 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001264 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1265 &MethodPool.front(),
1266 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001267
1268 // Create a blob abbreviation for the selector table offsets.
1269 Abbrev = new BitCodeAbbrev();
1270 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1273 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1274
1275 // Write the selector offsets table.
1276 Record.clear();
1277 Record.push_back(pch::SELECTOR_OFFSETS);
1278 Record.push_back(SelectorOffsets.size());
1279 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1280 (const char *)&SelectorOffsets.front(),
1281 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001282 }
1283}
1284
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001285//===----------------------------------------------------------------------===//
1286// Identifier Table Serialization
1287//===----------------------------------------------------------------------===//
1288
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001289namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001290class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1291 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001292 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001293
Douglas Gregora92193e2009-04-28 21:18:29 +00001294 /// \brief Determines whether this is an "interesting" identifier
1295 /// that needs a full IdentifierInfo structure written into the hash
1296 /// table.
1297 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1298 return II->isPoisoned() ||
1299 II->isExtensionToken() ||
1300 II->hasMacroDefinition() ||
1301 II->getObjCOrBuiltinID() ||
1302 II->getFETokenInfo<void>();
1303 }
1304
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001305public:
1306 typedef const IdentifierInfo* key_type;
1307 typedef key_type key_type_ref;
1308
1309 typedef pch::IdentID data_type;
1310 typedef data_type data_type_ref;
1311
Douglas Gregor37e26842009-04-21 23:56:24 +00001312 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1313 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001314
1315 static unsigned ComputeHash(const IdentifierInfo* II) {
1316 return clang::BernsteinHash(II->getName());
1317 }
1318
Douglas Gregor37e26842009-04-21 23:56:24 +00001319 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001320 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1321 pch::IdentID ID) {
1322 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001323 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1324 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001325 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001326 if (II->hasMacroDefinition() &&
1327 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001328 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001329 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1330 DEnd = IdentifierResolver::end();
1331 D != DEnd; ++D)
1332 DataLen += sizeof(pch::DeclID);
1333 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001334 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001335 // We emit the key length after the data length so that every
1336 // string is preceded by a 16-bit length. This matches the PTH
1337 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001338 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001339 return std::make_pair(KeyLen, DataLen);
1340 }
1341
1342 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1343 unsigned KeyLen) {
1344 // Record the location of the key data. This is used when generating
1345 // the mapping from persistent IDs to strings.
1346 Writer.SetIdentifierOffset(II, Out.tell());
1347 Out.write(II->getName(), KeyLen);
1348 }
1349
1350 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1351 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001352 if (!isInterestingIdentifier(II)) {
1353 clang::io::Emit32(Out, ID << 1);
1354 return;
1355 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001356
Douglas Gregora92193e2009-04-28 21:18:29 +00001357 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001358 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001359 bool hasMacroDefinition =
1360 II->hasMacroDefinition() &&
1361 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001362 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001363 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001364 Bits = (Bits << 1) | II->isExtensionToken();
1365 Bits = (Bits << 1) | II->isPoisoned();
1366 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001367 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001368
Douglas Gregor37e26842009-04-21 23:56:24 +00001369 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001370 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001371
Douglas Gregor668c1a42009-04-21 22:25:48 +00001372 // Emit the declaration IDs in reverse order, because the
1373 // IdentifierResolver provides the declarations as they would be
1374 // visible (e.g., the function "stat" would come before the struct
1375 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1376 // adds declarations to the end of the list (so we need to see the
1377 // struct "status" before the function "status").
1378 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1379 IdentifierResolver::end());
1380 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1381 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001382 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001383 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001384 }
1385};
1386} // end anonymous namespace
1387
Douglas Gregorafaf3082009-04-11 00:14:32 +00001388/// \brief Write the identifier table into the PCH file.
1389///
1390/// The identifier table consists of a blob containing string data
1391/// (the actual identifiers themselves) and a separate "offsets" index
1392/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001393void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001394 using namespace llvm;
1395
1396 // Create and write out the blob that contains the identifier
1397 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001398 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001399 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1400
Douglas Gregor92b059e2009-04-28 20:33:11 +00001401 // Look for any identifiers that were named while processing the
1402 // headers, but are otherwise not needed. We add these to the hash
1403 // table to enable checking of the predefines buffer in the case
1404 // where the user adds new macro definitions when building the PCH
1405 // file.
1406 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1407 IDEnd = PP.getIdentifierTable().end();
1408 ID != IDEnd; ++ID)
1409 getIdentifierRef(ID->second);
1410
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001411 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001412 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001413 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1414 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1415 ID != IDEnd; ++ID) {
1416 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001417 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001418 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001419
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001420 // Create the on-disk hash table in a buffer.
1421 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001422 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001423 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001424 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001425 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001426 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001427 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001428 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001429 }
1430
1431 // Create a blob abbreviation
1432 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1433 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001436 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001437
1438 // Write the identifier table
1439 RecordData Record;
1440 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001441 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001442 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1443 &IdentifierTable.front(),
1444 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001445 }
1446
1447 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001448 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1449 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1452 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1453
1454 RecordData Record;
1455 Record.push_back(pch::IDENTIFIER_OFFSET);
1456 Record.push_back(IdentifierOffsets.size());
1457 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1458 (const char *)&IdentifierOffsets.front(),
1459 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001460}
1461
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001462//===----------------------------------------------------------------------===//
1463// General Serialization Routines
1464//===----------------------------------------------------------------------===//
1465
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001466/// \brief Write a record containing the given attributes.
1467void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1468 RecordData Record;
1469 for (; Attr; Attr = Attr->getNext()) {
1470 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1471 Record.push_back(Attr->isInherited());
1472 switch (Attr->getKind()) {
1473 case Attr::Alias:
1474 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1475 break;
1476
1477 case Attr::Aligned:
1478 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1479 break;
1480
1481 case Attr::AlwaysInline:
1482 break;
1483
1484 case Attr::AnalyzerNoReturn:
1485 break;
1486
1487 case Attr::Annotate:
1488 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1489 break;
1490
1491 case Attr::AsmLabel:
1492 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1493 break;
1494
1495 case Attr::Blocks:
1496 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1497 break;
1498
1499 case Attr::Cleanup:
1500 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1501 break;
1502
1503 case Attr::Const:
1504 break;
1505
1506 case Attr::Constructor:
1507 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1508 break;
1509
1510 case Attr::DLLExport:
1511 case Attr::DLLImport:
1512 case Attr::Deprecated:
1513 break;
1514
1515 case Attr::Destructor:
1516 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1517 break;
1518
1519 case Attr::FastCall:
1520 break;
1521
1522 case Attr::Format: {
1523 const FormatAttr *Format = cast<FormatAttr>(Attr);
1524 AddString(Format->getType(), Record);
1525 Record.push_back(Format->getFormatIdx());
1526 Record.push_back(Format->getFirstArg());
1527 break;
1528 }
1529
Chris Lattnercf2a7212009-04-20 19:12:28 +00001530 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001531 case Attr::IBOutletKind:
1532 case Attr::NoReturn:
1533 case Attr::NoThrow:
1534 case Attr::Nodebug:
1535 case Attr::Noinline:
1536 break;
1537
1538 case Attr::NonNull: {
1539 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1540 Record.push_back(NonNull->size());
1541 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1542 break;
1543 }
1544
1545 case Attr::ObjCException:
1546 case Attr::ObjCNSObject:
Ted Kremenek31c215e2009-05-04 17:29:57 +00001547 case Attr::CFOwnershipRelease:
1548 case Attr::CFOwnershipRetain:
Ted Kremeneke351aa12009-05-05 00:46:09 +00001549 case Attr::CFOwnershipReturns:
Ted Kremenek69aa0802009-05-05 18:44:20 +00001550 case Attr::NSOwnershipAutorelease:
Ted Kremenek75494ff2009-05-04 19:10:19 +00001551 case Attr::NSOwnershipRelease:
1552 case Attr::NSOwnershipRetain:
1553 case Attr::NSOwnershipReturns:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001554 case Attr::Overloadable:
1555 break;
1556
1557 case Attr::Packed:
1558 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1559 break;
1560
1561 case Attr::Pure:
1562 break;
1563
1564 case Attr::Regparm:
1565 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1566 break;
1567
1568 case Attr::Section:
1569 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1570 break;
1571
1572 case Attr::StdCall:
1573 case Attr::TransparentUnion:
1574 case Attr::Unavailable:
1575 case Attr::Unused:
1576 case Attr::Used:
1577 break;
1578
1579 case Attr::Visibility:
1580 // FIXME: stable encoding
1581 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1582 break;
1583
1584 case Attr::WarnUnusedResult:
1585 case Attr::Weak:
1586 case Attr::WeakImport:
1587 break;
1588 }
1589 }
1590
Douglas Gregorc9490c02009-04-16 22:23:12 +00001591 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001592}
1593
1594void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1595 Record.push_back(Str.size());
1596 Record.insert(Record.end(), Str.begin(), Str.end());
1597}
1598
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001599/// \brief Note that the identifier II occurs at the given offset
1600/// within the identifier table.
1601void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001602 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001603}
1604
Douglas Gregor83941df2009-04-25 17:48:32 +00001605/// \brief Note that the selector Sel occurs at the given offset
1606/// within the method pool/selector table.
1607void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1608 unsigned ID = SelectorIDs[Sel];
1609 assert(ID && "Unknown selector");
1610 SelectorOffsets[ID - 1] = Offset;
1611}
1612
Douglas Gregorc9490c02009-04-16 22:23:12 +00001613PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001614 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001615 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1616 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001617
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001618void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001619 using namespace llvm;
1620
Douglas Gregore7785042009-04-20 15:53:59 +00001621 ASTContext &Context = SemaRef.Context;
1622 Preprocessor &PP = SemaRef.PP;
1623
Douglas Gregor2cf26342009-04-09 22:27:44 +00001624 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001625 Stream.Emit((unsigned)'C', 8);
1626 Stream.Emit((unsigned)'P', 8);
1627 Stream.Emit((unsigned)'C', 8);
1628 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001629
1630 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001631
1632 // The translation unit is the first declaration we'll emit.
1633 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1634 DeclsToEmit.push(Context.getTranslationUnitDecl());
1635
Douglas Gregor2deaea32009-04-22 18:49:13 +00001636 // Make sure that we emit IdentifierInfos (and any attached
1637 // declarations) for builtins.
1638 {
1639 IdentifierTable &Table = PP.getIdentifierTable();
1640 llvm::SmallVector<const char *, 32> BuiltinNames;
1641 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1642 Context.getLangOptions().NoBuiltin);
1643 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1644 getIdentifierRef(&Table.get(BuiltinNames[I]));
1645 }
1646
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001647 // Build a record containing all of the tentative definitions in
1648 // this header file. Generally, this record will be empty.
1649 RecordData TentativeDefinitions;
1650 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1651 TD = SemaRef.TentativeDefinitions.begin(),
1652 TDEnd = SemaRef.TentativeDefinitions.end();
1653 TD != TDEnd; ++TD)
1654 AddDeclRef(TD->second, TentativeDefinitions);
1655
Douglas Gregor14c22f22009-04-22 22:18:58 +00001656 // Build a record containing all of the locally-scoped external
1657 // declarations in this header file. Generally, this record will be
1658 // empty.
1659 RecordData LocallyScopedExternalDecls;
1660 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1661 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1662 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1663 TD != TDEnd; ++TD)
1664 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1665
Douglas Gregorb81c1702009-04-27 20:06:05 +00001666 // Build a record containing all of the ext_vector declarations.
1667 RecordData ExtVectorDecls;
1668 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1669 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1670
1671 // Build a record containing all of the Objective-C category
1672 // implementations.
1673 RecordData ObjCCategoryImpls;
1674 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1675 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1676
Douglas Gregor2cf26342009-04-09 22:27:44 +00001677 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001678 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001679 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorab41e632009-04-27 22:23:34 +00001680 WriteMetadata(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001681 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001682 if (StatCalls)
1683 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001684 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001685 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001686
1687 // Keep writing types and declarations until all types and
1688 // declarations have been written.
1689 do {
1690 if (!DeclsToEmit.empty())
1691 WriteDeclsBlock(Context);
1692 if (!TypesToEmit.empty())
1693 WriteTypesBlock(Context);
1694 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1695
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001696 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001697 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001698
1699 // Write the type offsets array
1700 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1701 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1704 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1705 Record.clear();
1706 Record.push_back(pch::TYPE_OFFSET);
1707 Record.push_back(TypeOffsets.size());
1708 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1709 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001710 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001711
1712 // Write the declaration offsets array
1713 Abbrev = new BitCodeAbbrev();
1714 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1717 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1718 Record.clear();
1719 Record.push_back(pch::DECL_OFFSET);
1720 Record.push_back(DeclOffsets.size());
1721 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1722 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001723 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001724
1725 // Write the record of special types.
1726 Record.clear();
1727 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001728 AddTypeRef(Context.getObjCIdType(), Record);
1729 AddTypeRef(Context.getObjCSelType(), Record);
1730 AddTypeRef(Context.getObjCProtoType(), Record);
1731 AddTypeRef(Context.getObjCClassType(), Record);
1732 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1733 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001734 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1735
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001736 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001737 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001738 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001739
1740 // Write the record containing tentative definitions.
1741 if (!TentativeDefinitions.empty())
1742 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001743
1744 // Write the record containing locally-scoped external definitions.
1745 if (!LocallyScopedExternalDecls.empty())
1746 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1747 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001748
1749 // Write the record containing ext_vector type names.
1750 if (!ExtVectorDecls.empty())
1751 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1752
1753 // Write the record containing Objective-C category implementations.
1754 if (!ObjCCategoryImpls.empty())
1755 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001756
1757 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001758 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001759 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001760 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001761 Record.push_back(NumLexicalDeclContexts);
1762 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001763 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001764 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001765}
1766
1767void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1768 Record.push_back(Loc.getRawEncoding());
1769}
1770
1771void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1772 Record.push_back(Value.getBitWidth());
1773 unsigned N = Value.getNumWords();
1774 const uint64_t* Words = Value.getRawData();
1775 for (unsigned I = 0; I != N; ++I)
1776 Record.push_back(Words[I]);
1777}
1778
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001779void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1780 Record.push_back(Value.isUnsigned());
1781 AddAPInt(Value, Record);
1782}
1783
Douglas Gregor17fc2232009-04-14 21:55:33 +00001784void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1785 AddAPInt(Value.bitcastToAPInt(), Record);
1786}
1787
Douglas Gregor2cf26342009-04-09 22:27:44 +00001788void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001789 Record.push_back(getIdentifierRef(II));
1790}
1791
1792pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1793 if (II == 0)
1794 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001795
1796 pch::IdentID &ID = IdentifierIDs[II];
1797 if (ID == 0)
1798 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001799 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001800}
1801
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001802void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1803 if (SelRef.getAsOpaquePtr() == 0) {
1804 Record.push_back(0);
1805 return;
1806 }
1807
1808 pch::SelectorID &SID = SelectorIDs[SelRef];
1809 if (SID == 0) {
1810 SID = SelectorIDs.size();
1811 SelVector.push_back(SelRef);
1812 }
1813 Record.push_back(SID);
1814}
1815
Douglas Gregor2cf26342009-04-09 22:27:44 +00001816void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1817 if (T.isNull()) {
1818 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1819 return;
1820 }
1821
1822 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001823 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001824 switch (BT->getKind()) {
1825 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1826 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1827 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1828 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1829 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1830 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1831 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1832 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001833 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001834 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1835 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1836 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1837 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1838 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1839 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1840 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001841 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001842 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1843 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1844 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1845 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1846 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1847 }
1848
1849 Record.push_back((ID << 3) | T.getCVRQualifiers());
1850 return;
1851 }
1852
Douglas Gregor8038d512009-04-10 17:25:41 +00001853 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001854 if (ID == 0) {
1855 // We haven't seen this type before. Assign it a new ID and put it
1856 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001857 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001858 TypesToEmit.push(T.getTypePtr());
1859 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001860
1861 // Encode the type qualifiers in the type reference.
1862 Record.push_back((ID << 3) | T.getCVRQualifiers());
1863}
1864
1865void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1866 if (D == 0) {
1867 Record.push_back(0);
1868 return;
1869 }
1870
Douglas Gregor8038d512009-04-10 17:25:41 +00001871 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001872 if (ID == 0) {
1873 // We haven't seen this declaration before. Give it a new ID and
1874 // enqueue it in the list of declarations to emit.
1875 ID = DeclIDs.size();
1876 DeclsToEmit.push(const_cast<Decl *>(D));
1877 }
1878
1879 Record.push_back(ID);
1880}
1881
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001882pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1883 if (D == 0)
1884 return 0;
1885
1886 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1887 return DeclIDs[D];
1888}
1889
Douglas Gregor2cf26342009-04-09 22:27:44 +00001890void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001891 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001892 Record.push_back(Name.getNameKind());
1893 switch (Name.getNameKind()) {
1894 case DeclarationName::Identifier:
1895 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1896 break;
1897
1898 case DeclarationName::ObjCZeroArgSelector:
1899 case DeclarationName::ObjCOneArgSelector:
1900 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001901 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001902 break;
1903
1904 case DeclarationName::CXXConstructorName:
1905 case DeclarationName::CXXDestructorName:
1906 case DeclarationName::CXXConversionFunctionName:
1907 AddTypeRef(Name.getCXXNameType(), Record);
1908 break;
1909
1910 case DeclarationName::CXXOperatorName:
1911 Record.push_back(Name.getCXXOverloadedOperator());
1912 break;
1913
1914 case DeclarationName::CXXUsingDirective:
1915 // No extra data to emit
1916 break;
1917 }
1918}
Douglas Gregor0b748912009-04-14 21:18:50 +00001919