blob: 817893448a70b19b2030e6000c5819b1e1567224 [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 Gregor17fc2232009-04-14 21:55:33 +000030#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamWriter.h"
33#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000034#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000035#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
39// Type serialization
40//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000041
Douglas Gregor2cf26342009-04-09 22:27:44 +000042namespace {
43 class VISIBILITY_HIDDEN PCHTypeWriter {
44 PCHWriter &Writer;
45 PCHWriter::RecordData &Record;
46
47 public:
48 /// \brief Type code that corresponds to the record generated.
49 pch::TypeCode Code;
50
51 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor4fed3f42009-04-27 18:38:38 +000052 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000053
54 void VisitArrayType(const ArrayType *T);
55 void VisitFunctionType(const FunctionType *T);
56 void VisitTagType(const TagType *T);
57
58#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
59#define ABSTRACT_TYPE(Class, Base)
60#define DEPENDENT_TYPE(Class, Base)
61#include "clang/AST/TypeNodes.def"
62 };
63}
64
65void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
66 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
67 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
68 Record.push_back(T->getAddressSpace());
69 Code = pch::TYPE_EXT_QUAL;
70}
71
72void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
73 assert(false && "Built-in types are never serialized");
74}
75
76void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
77 Record.push_back(T->getWidth());
78 Record.push_back(T->isSigned());
79 Code = pch::TYPE_FIXED_WIDTH_INT;
80}
81
82void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
83 Writer.AddTypeRef(T->getElementType(), Record);
84 Code = pch::TYPE_COMPLEX;
85}
86
87void PCHTypeWriter::VisitPointerType(const PointerType *T) {
88 Writer.AddTypeRef(T->getPointeeType(), Record);
89 Code = pch::TYPE_POINTER;
90}
91
92void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_BLOCK_POINTER;
95}
96
97void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Code = pch::TYPE_LVALUE_REFERENCE;
100}
101
102void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Code = pch::TYPE_RVALUE_REFERENCE;
105}
106
107void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
108 Writer.AddTypeRef(T->getPointeeType(), Record);
109 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
110 Code = pch::TYPE_MEMBER_POINTER;
111}
112
113void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
114 Writer.AddTypeRef(T->getElementType(), Record);
115 Record.push_back(T->getSizeModifier()); // FIXME: stable values
116 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
117}
118
119void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
120 VisitArrayType(T);
121 Writer.AddAPInt(T->getSize(), Record);
122 Code = pch::TYPE_CONSTANT_ARRAY;
123}
124
125void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
126 VisitArrayType(T);
127 Code = pch::TYPE_INCOMPLETE_ARRAY;
128}
129
130void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
131 VisitArrayType(T);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000132 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133 Code = pch::TYPE_VARIABLE_ARRAY;
134}
135
136void PCHTypeWriter::VisitVectorType(const VectorType *T) {
137 Writer.AddTypeRef(T->getElementType(), Record);
138 Record.push_back(T->getNumElements());
139 Code = pch::TYPE_VECTOR;
140}
141
142void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
143 VisitVectorType(T);
144 Code = pch::TYPE_EXT_VECTOR;
145}
146
147void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
148 Writer.AddTypeRef(T->getResultType(), Record);
149}
150
151void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
152 VisitFunctionType(T);
153 Code = pch::TYPE_FUNCTION_NO_PROTO;
154}
155
156void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
157 VisitFunctionType(T);
158 Record.push_back(T->getNumArgs());
159 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
160 Writer.AddTypeRef(T->getArgType(I), Record);
161 Record.push_back(T->isVariadic());
162 Record.push_back(T->getTypeQuals());
163 Code = pch::TYPE_FUNCTION_PROTO;
164}
165
166void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
167 Writer.AddDeclRef(T->getDecl(), Record);
168 Code = pch::TYPE_TYPEDEF;
169}
170
171void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000172 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000173 Code = pch::TYPE_TYPEOF_EXPR;
174}
175
176void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
177 Writer.AddTypeRef(T->getUnderlyingType(), Record);
178 Code = pch::TYPE_TYPEOF;
179}
180
181void PCHTypeWriter::VisitTagType(const TagType *T) {
182 Writer.AddDeclRef(T->getDecl(), Record);
183 assert(!T->isBeingDefined() &&
184 "Cannot serialize in the middle of a type definition");
185}
186
187void PCHTypeWriter::VisitRecordType(const RecordType *T) {
188 VisitTagType(T);
189 Code = pch::TYPE_RECORD;
190}
191
192void PCHTypeWriter::VisitEnumType(const EnumType *T) {
193 VisitTagType(T);
194 Code = pch::TYPE_ENUM;
195}
196
197void
198PCHTypeWriter::VisitTemplateSpecializationType(
199 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000200 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000201 assert(false && "Cannot serialize template specialization types");
202}
203
204void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000205 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000206 assert(false && "Cannot serialize qualified name types");
207}
208
209void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
210 Writer.AddDeclRef(T->getDecl(), Record);
211 Code = pch::TYPE_OBJC_INTERFACE;
212}
213
214void
215PCHTypeWriter::VisitObjCQualifiedInterfaceType(
216 const ObjCQualifiedInterfaceType *T) {
217 VisitObjCInterfaceType(T);
218 Record.push_back(T->getNumProtocols());
219 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
220 Writer.AddDeclRef(T->getProtocol(I), Record);
221 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
222}
223
224void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
225 Record.push_back(T->getNumProtocols());
226 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
227 Writer.AddDeclRef(T->getProtocols(I), Record);
228 Code = pch::TYPE_OBJC_QUALIFIED_ID;
229}
230
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000231//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000232// PCHWriter Implementation
233//===----------------------------------------------------------------------===//
234
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000235static void EmitBlockID(unsigned ID, const char *Name,
236 llvm::BitstreamWriter &Stream,
237 PCHWriter::RecordData &Record) {
238 Record.clear();
239 Record.push_back(ID);
240 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
241
242 // Emit the block name if present.
243 if (Name == 0 || Name[0] == 0) return;
244 Record.clear();
245 while (*Name)
246 Record.push_back(*Name++);
247 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
248}
249
250static void EmitRecordID(unsigned ID, const char *Name,
251 llvm::BitstreamWriter &Stream,
252 PCHWriter::RecordData &Record) {
253 Record.clear();
254 Record.push_back(ID);
255 while (*Name)
256 Record.push_back(*Name++);
257 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000258}
259
260static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
261 PCHWriter::RecordData &Record) {
262#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
263 RECORD(STMT_STOP);
264 RECORD(STMT_NULL_PTR);
265 RECORD(STMT_NULL);
266 RECORD(STMT_COMPOUND);
267 RECORD(STMT_CASE);
268 RECORD(STMT_DEFAULT);
269 RECORD(STMT_LABEL);
270 RECORD(STMT_IF);
271 RECORD(STMT_SWITCH);
272 RECORD(STMT_WHILE);
273 RECORD(STMT_DO);
274 RECORD(STMT_FOR);
275 RECORD(STMT_GOTO);
276 RECORD(STMT_INDIRECT_GOTO);
277 RECORD(STMT_CONTINUE);
278 RECORD(STMT_BREAK);
279 RECORD(STMT_RETURN);
280 RECORD(STMT_DECL);
281 RECORD(STMT_ASM);
282 RECORD(EXPR_PREDEFINED);
283 RECORD(EXPR_DECL_REF);
284 RECORD(EXPR_INTEGER_LITERAL);
285 RECORD(EXPR_FLOATING_LITERAL);
286 RECORD(EXPR_IMAGINARY_LITERAL);
287 RECORD(EXPR_STRING_LITERAL);
288 RECORD(EXPR_CHARACTER_LITERAL);
289 RECORD(EXPR_PAREN);
290 RECORD(EXPR_UNARY_OPERATOR);
291 RECORD(EXPR_SIZEOF_ALIGN_OF);
292 RECORD(EXPR_ARRAY_SUBSCRIPT);
293 RECORD(EXPR_CALL);
294 RECORD(EXPR_MEMBER);
295 RECORD(EXPR_BINARY_OPERATOR);
296 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
297 RECORD(EXPR_CONDITIONAL_OPERATOR);
298 RECORD(EXPR_IMPLICIT_CAST);
299 RECORD(EXPR_CSTYLE_CAST);
300 RECORD(EXPR_COMPOUND_LITERAL);
301 RECORD(EXPR_EXT_VECTOR_ELEMENT);
302 RECORD(EXPR_INIT_LIST);
303 RECORD(EXPR_DESIGNATED_INIT);
304 RECORD(EXPR_IMPLICIT_VALUE_INIT);
305 RECORD(EXPR_VA_ARG);
306 RECORD(EXPR_ADDR_LABEL);
307 RECORD(EXPR_STMT);
308 RECORD(EXPR_TYPES_COMPATIBLE);
309 RECORD(EXPR_CHOOSE);
310 RECORD(EXPR_GNU_NULL);
311 RECORD(EXPR_SHUFFLE_VECTOR);
312 RECORD(EXPR_BLOCK);
313 RECORD(EXPR_BLOCK_DECL_REF);
314 RECORD(EXPR_OBJC_STRING_LITERAL);
315 RECORD(EXPR_OBJC_ENCODE);
316 RECORD(EXPR_OBJC_SELECTOR_EXPR);
317 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
318 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
319 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
320 RECORD(EXPR_OBJC_KVC_REF_EXPR);
321 RECORD(EXPR_OBJC_MESSAGE_EXPR);
322 RECORD(EXPR_OBJC_SUPER_EXPR);
323 RECORD(STMT_OBJC_FOR_COLLECTION);
324 RECORD(STMT_OBJC_CATCH);
325 RECORD(STMT_OBJC_FINALLY);
326 RECORD(STMT_OBJC_AT_TRY);
327 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
328 RECORD(STMT_OBJC_AT_THROW);
329#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000330}
331
332void PCHWriter::WriteBlockInfoBlock() {
333 RecordData Record;
334 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
335
Chris Lattner2f4efd12009-04-27 00:40:25 +0000336#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000337#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
338
339 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000340 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000341 RECORD(TYPE_OFFSET);
342 RECORD(DECL_OFFSET);
343 RECORD(LANGUAGE_OPTIONS);
344 RECORD(TARGET_TRIPLE);
345 RECORD(IDENTIFIER_OFFSET);
346 RECORD(IDENTIFIER_TABLE);
347 RECORD(EXTERNAL_DEFINITIONS);
348 RECORD(SPECIAL_TYPES);
349 RECORD(STATISTICS);
350 RECORD(TENTATIVE_DEFINITIONS);
351 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
352 RECORD(SELECTOR_OFFSETS);
353 RECORD(METHOD_POOL);
354 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000355 RECORD(SOURCE_LOCATION_OFFSETS);
356 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000357 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000358 RECORD(EXT_VECTOR_DECLS);
359 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000360
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000361 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000362 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000363 RECORD(SM_SLOC_FILE_ENTRY);
364 RECORD(SM_SLOC_BUFFER_ENTRY);
365 RECORD(SM_SLOC_BUFFER_BLOB);
366 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
367 RECORD(SM_LINE_TABLE);
368 RECORD(SM_HEADER_FILE_INFO);
369
370 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000371 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000372 RECORD(PP_MACRO_OBJECT_LIKE);
373 RECORD(PP_MACRO_FUNCTION_LIKE);
374 RECORD(PP_TOKEN);
375
376 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000377 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000378 RECORD(TYPE_EXT_QUAL);
379 RECORD(TYPE_FIXED_WIDTH_INT);
380 RECORD(TYPE_COMPLEX);
381 RECORD(TYPE_POINTER);
382 RECORD(TYPE_BLOCK_POINTER);
383 RECORD(TYPE_LVALUE_REFERENCE);
384 RECORD(TYPE_RVALUE_REFERENCE);
385 RECORD(TYPE_MEMBER_POINTER);
386 RECORD(TYPE_CONSTANT_ARRAY);
387 RECORD(TYPE_INCOMPLETE_ARRAY);
388 RECORD(TYPE_VARIABLE_ARRAY);
389 RECORD(TYPE_VECTOR);
390 RECORD(TYPE_EXT_VECTOR);
391 RECORD(TYPE_FUNCTION_PROTO);
392 RECORD(TYPE_FUNCTION_NO_PROTO);
393 RECORD(TYPE_TYPEDEF);
394 RECORD(TYPE_TYPEOF_EXPR);
395 RECORD(TYPE_TYPEOF);
396 RECORD(TYPE_RECORD);
397 RECORD(TYPE_ENUM);
398 RECORD(TYPE_OBJC_INTERFACE);
399 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
400 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000401 // Statements and Exprs can occur in the Types block.
402 AddStmtsExprs(Stream, Record);
403
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000404 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000405 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000406 RECORD(DECL_ATTR);
407 RECORD(DECL_TRANSLATION_UNIT);
408 RECORD(DECL_TYPEDEF);
409 RECORD(DECL_ENUM);
410 RECORD(DECL_RECORD);
411 RECORD(DECL_ENUM_CONSTANT);
412 RECORD(DECL_FUNCTION);
413 RECORD(DECL_OBJC_METHOD);
414 RECORD(DECL_OBJC_INTERFACE);
415 RECORD(DECL_OBJC_PROTOCOL);
416 RECORD(DECL_OBJC_IVAR);
417 RECORD(DECL_OBJC_AT_DEFS_FIELD);
418 RECORD(DECL_OBJC_CLASS);
419 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
420 RECORD(DECL_OBJC_CATEGORY);
421 RECORD(DECL_OBJC_CATEGORY_IMPL);
422 RECORD(DECL_OBJC_IMPLEMENTATION);
423 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
424 RECORD(DECL_OBJC_PROPERTY);
425 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000426 RECORD(DECL_FIELD);
427 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000428 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000429 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000430 RECORD(DECL_ORIGINAL_PARM_VAR);
431 RECORD(DECL_FILE_SCOPE_ASM);
432 RECORD(DECL_BLOCK);
433 RECORD(DECL_CONTEXT_LEXICAL);
434 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000435 // Statements and Exprs can occur in the Decls block.
436 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000437#undef RECORD
438#undef BLOCK
439 Stream.ExitBlock();
440}
441
442
Douglas Gregor2bec0412009-04-10 21:16:55 +0000443/// \brief Write the target triple (e.g., i686-apple-darwin9).
444void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
445 using namespace llvm;
446 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
447 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000449 unsigned TripleAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000450
451 RecordData Record;
452 Record.push_back(pch::TARGET_TRIPLE);
453 const char *Triple = Target.getTargetTriple();
Douglas Gregorc9490c02009-04-16 22:23:12 +0000454 Stream.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000455}
456
457/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000458void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
459 RecordData Record;
460 Record.push_back(LangOpts.Trigraphs);
461 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
462 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
463 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
464 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
465 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
466 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
467 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
468 Record.push_back(LangOpts.C99); // C99 Support
469 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
470 Record.push_back(LangOpts.CPlusPlus); // C++ Support
471 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
472 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
473 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
474
475 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
476 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
477 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
478
479 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
480 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
481 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
482 Record.push_back(LangOpts.LaxVectorConversions);
483 Record.push_back(LangOpts.Exceptions); // Support exception handling.
484
485 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
486 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
487 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
488
Chris Lattnerea5ce472009-04-27 07:35:58 +0000489 // Whether static initializers are protected by locks.
490 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000491 Record.push_back(LangOpts.Blocks); // block extension to C
492 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
493 // they are unused.
494 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
495 // (modulo the platform support).
496
497 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
498 // signed integer arithmetic overflows.
499
500 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
501 // may be ripped out at any time.
502
503 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
504 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
505 // defined.
506 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
507 // opposed to __DYNAMIC__).
508 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
509
510 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
511 // used (instead of C99 semantics).
512 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
513 Record.push_back(LangOpts.getGCMode());
514 Record.push_back(LangOpts.getVisibilityMode());
515 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000516 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000517}
518
Douglas Gregor14f79002009-04-10 03:52:48 +0000519//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000520// stat cache Serialization
521//===----------------------------------------------------------------------===//
522
523namespace {
524// Trait used for the on-disk hash table of stat cache results.
525class VISIBILITY_HIDDEN PCHStatCacheTrait {
526public:
527 typedef const char * key_type;
528 typedef key_type key_type_ref;
529
530 typedef std::pair<int, struct stat> data_type;
531 typedef const data_type& data_type_ref;
532
533 static unsigned ComputeHash(const char *path) {
534 return BernsteinHash(path);
535 }
536
537 std::pair<unsigned,unsigned>
538 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
539 data_type_ref Data) {
540 unsigned StrLen = strlen(path);
541 clang::io::Emit16(Out, StrLen);
542 unsigned DataLen = 1; // result value
543 if (Data.first == 0)
544 DataLen += 4 + 4 + 2 + 8 + 8;
545 clang::io::Emit8(Out, DataLen);
546 return std::make_pair(StrLen + 1, DataLen);
547 }
548
549 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
550 Out.write(path, KeyLen);
551 }
552
553 void EmitData(llvm::raw_ostream& Out, key_type_ref,
554 data_type_ref Data, unsigned DataLen) {
555 using namespace clang::io;
556 uint64_t Start = Out.tell(); (void)Start;
557
558 // Result of stat()
559 Emit8(Out, Data.first? 1 : 0);
560
561 if (Data.first == 0) {
562 Emit32(Out, (uint32_t) Data.second.st_ino);
563 Emit32(Out, (uint32_t) Data.second.st_dev);
564 Emit16(Out, (uint16_t) Data.second.st_mode);
565 Emit64(Out, (uint64_t) Data.second.st_mtime);
566 Emit64(Out, (uint64_t) Data.second.st_size);
567 }
568
569 assert(Out.tell() - Start == DataLen && "Wrong data length");
570 }
571};
572} // end anonymous namespace
573
574/// \brief Write the stat() system call cache to the PCH file.
575void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
576 // Build the on-disk hash table containing information about every
577 // stat() call.
578 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
579 unsigned NumStatEntries = 0;
580 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
581 StatEnd = StatCalls.end();
582 Stat != StatEnd; ++Stat, ++NumStatEntries)
583 Generator.insert(Stat->first(), Stat->second);
584
585 // Create the on-disk hash table in a buffer.
586 llvm::SmallVector<char, 4096> StatCacheData;
587 uint32_t BucketOffset;
588 {
589 llvm::raw_svector_ostream Out(StatCacheData);
590 // Make sure that no bucket is at offset 0
591 clang::io::Emit32(Out, 0);
592 BucketOffset = Generator.Emit(Out);
593 }
594
595 // Create a blob abbreviation
596 using namespace llvm;
597 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
598 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
602 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
603
604 // Write the stat cache
605 RecordData Record;
606 Record.push_back(pch::STAT_CACHE);
607 Record.push_back(BucketOffset);
608 Record.push_back(NumStatEntries);
609 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
610 &StatCacheData.front(),
611 StatCacheData.size());
612}
613
614//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000615// Source Manager Serialization
616//===----------------------------------------------------------------------===//
617
618/// \brief Create an abbreviation for the SLocEntry that refers to a
619/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000620static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000621 using namespace llvm;
622 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
623 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
624 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
625 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000628 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000629 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000630}
631
632/// \brief Create an abbreviation for the SLocEntry that refers to a
633/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000634static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000635 using namespace llvm;
636 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
637 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
638 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
641 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
642 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000643 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000644}
645
646/// \brief Create an abbreviation for the SLocEntry that refers to a
647/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000648static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000649 using namespace llvm;
650 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
651 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000653 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000654}
655
656/// \brief Create an abbreviation for the SLocEntry that refers to an
657/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000658static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000659 using namespace llvm;
660 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
661 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000667 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000668}
669
670/// \brief Writes the block containing the serialized form of the
671/// source manager.
672///
673/// TODO: We should probably use an on-disk hash table (stored in a
674/// blob), indexed based on the file name, so that we only create
675/// entries for files that we actually need. In the common case (no
676/// errors), we probably won't have to create file entries for any of
677/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000678void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
679 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000680 RecordData Record;
681
Chris Lattnerf04ad692009-04-10 17:16:57 +0000682 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000683 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000684
685 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000686 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
687 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
688 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
689 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000690
Douglas Gregorbd945002009-04-13 16:31:14 +0000691 // Write the line table.
692 if (SourceMgr.hasLineTable()) {
693 LineTableInfo &LineTable = SourceMgr.getLineTable();
694
695 // Emit the file names
696 Record.push_back(LineTable.getNumFilenames());
697 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
698 // Emit the file name
699 const char *Filename = LineTable.getFilename(I);
700 unsigned FilenameLen = Filename? strlen(Filename) : 0;
701 Record.push_back(FilenameLen);
702 if (FilenameLen)
703 Record.insert(Record.end(), Filename, Filename + FilenameLen);
704 }
705
706 // Emit the line entries
707 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
708 L != LEnd; ++L) {
709 // Emit the file ID
710 Record.push_back(L->first);
711
712 // Emit the line entries
713 Record.push_back(L->second.size());
714 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
715 LEEnd = L->second.end();
716 LE != LEEnd; ++LE) {
717 Record.push_back(LE->FileOffset);
718 Record.push_back(LE->LineNo);
719 Record.push_back(LE->FilenameID);
720 Record.push_back((unsigned)LE->FileKind);
721 Record.push_back(LE->IncludeOffset);
722 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000723 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000724 }
725 }
726
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000727 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000728 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000729 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000730 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
731 E = HS.header_file_end();
732 I != E; ++I) {
733 Record.push_back(I->isImport);
734 Record.push_back(I->DirInfo);
735 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000736 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000737 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
738 Record.clear();
739 }
740
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000741 // Write out the source location entry table. We skip the first
742 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000743 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000744 RecordData PreloadSLocs;
745 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
746 for (SourceManager::sloc_entry_iterator
747 SLoc = SourceMgr.sloc_entry_begin() + 1,
748 SLocEnd = SourceMgr.sloc_entry_end();
749 SLoc != SLocEnd; ++SLoc) {
750 // Record the offset of this source-location entry.
751 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
752
753 // Figure out which record code to use.
754 unsigned Code;
755 if (SLoc->isFile()) {
756 if (SLoc->getFile().getContentCache()->Entry)
757 Code = pch::SM_SLOC_FILE_ENTRY;
758 else
759 Code = pch::SM_SLOC_BUFFER_ENTRY;
760 } else
761 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
762 Record.clear();
763 Record.push_back(Code);
764
765 Record.push_back(SLoc->getOffset());
766 if (SLoc->isFile()) {
767 const SrcMgr::FileInfo &File = SLoc->getFile();
768 Record.push_back(File.getIncludeLoc().getRawEncoding());
769 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
770 Record.push_back(File.hasLineDirectives());
771
772 const SrcMgr::ContentCache *Content = File.getContentCache();
773 if (Content->Entry) {
774 // The source location entry is a file. The blob associated
775 // with this entry is the file name.
776 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
777 Content->Entry->getName(),
778 strlen(Content->Entry->getName()));
779
780 // FIXME: For now, preload all file source locations, so that
781 // we get the appropriate File entries in the reader. This is
782 // a temporary measure.
783 PreloadSLocs.push_back(SLocEntryOffsets.size());
784 } else {
785 // The source location entry is a buffer. The blob associated
786 // with this entry contains the contents of the buffer.
787
788 // We add one to the size so that we capture the trailing NULL
789 // that is required by llvm::MemoryBuffer::getMemBuffer (on
790 // the reader side).
791 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
792 const char *Name = Buffer->getBufferIdentifier();
793 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
794 Record.clear();
795 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
796 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
797 Buffer->getBufferStart(),
798 Buffer->getBufferSize() + 1);
799
800 if (strcmp(Name, "<built-in>") == 0)
801 PreloadSLocs.push_back(SLocEntryOffsets.size());
802 }
803 } else {
804 // The source location entry is an instantiation.
805 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
806 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
807 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
808 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
809
810 // Compute the token length for this macro expansion.
811 unsigned NextOffset = SourceMgr.getNextOffset();
812 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
813 if (++NextSLoc != SLocEnd)
814 NextOffset = NextSLoc->getOffset();
815 Record.push_back(NextOffset - SLoc->getOffset() - 1);
816 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
817 }
818 }
819
Douglas Gregorc9490c02009-04-16 22:23:12 +0000820 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000821
822 if (SLocEntryOffsets.empty())
823 return;
824
825 // Write the source-location offsets table into the PCH block. This
826 // table is used for lazily loading source-location information.
827 using namespace llvm;
828 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
829 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
831 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
832 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
833 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
834
835 Record.clear();
836 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
837 Record.push_back(SLocEntryOffsets.size());
838 Record.push_back(SourceMgr.getNextOffset());
839 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
840 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000841 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000842
843 // Write the source location entry preloads array, telling the PCH
844 // reader which source locations entries it should load eagerly.
845 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000846}
847
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000848//===----------------------------------------------------------------------===//
849// Preprocessor Serialization
850//===----------------------------------------------------------------------===//
851
Chris Lattner0b1fb982009-04-10 17:15:23 +0000852/// \brief Writes the block containing the serialized form of the
853/// preprocessor.
854///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000855void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000856 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000857
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000858 // If the preprocessor __COUNTER__ value has been bumped, remember it.
859 if (PP.getCounterValue() != 0) {
860 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000861 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000862 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000863 }
864
865 // Enter the preprocessor block.
866 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000867
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000868 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
869 // FIXME: use diagnostics subsystem for localization etc.
870 if (PP.SawDateOrTime())
871 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
872
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000873 // Loop over all the macro definitions that are live at the end of the file,
874 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000875 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
876 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000877 // FIXME: This emits macros in hash table order, we should do it in a stable
878 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000879 MacroInfo *MI = I->second;
880
881 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
882 // been redefined by the header (in which case they are not isBuiltinMacro).
883 if (MI->isBuiltinMacro())
884 continue;
885
Douglas Gregor37e26842009-04-21 23:56:24 +0000886 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000887 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000888 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000889 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
890 Record.push_back(MI->isUsed());
891
892 unsigned Code;
893 if (MI->isObjectLike()) {
894 Code = pch::PP_MACRO_OBJECT_LIKE;
895 } else {
896 Code = pch::PP_MACRO_FUNCTION_LIKE;
897
898 Record.push_back(MI->isC99Varargs());
899 Record.push_back(MI->isGNUVarargs());
900 Record.push_back(MI->getNumArgs());
901 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
902 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000903 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000904 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000905 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000906 Record.clear();
907
Chris Lattnerdf961c22009-04-10 18:08:30 +0000908 // Emit the tokens array.
909 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
910 // Note that we know that the preprocessor does not have any annotation
911 // tokens in it because they are created by the parser, and thus can't be
912 // in a macro definition.
913 const Token &Tok = MI->getReplacementToken(TokNo);
914
915 Record.push_back(Tok.getLocation().getRawEncoding());
916 Record.push_back(Tok.getLength());
917
Chris Lattnerdf961c22009-04-10 18:08:30 +0000918 // FIXME: When reading literal tokens, reconstruct the literal pointer if
919 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000920 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000921
922 // FIXME: Should translate token kind to a stable encoding.
923 Record.push_back(Tok.getKind());
924 // FIXME: Should translate token flags to a stable encoding.
925 Record.push_back(Tok.getFlags());
926
Douglas Gregorc9490c02009-04-16 22:23:12 +0000927 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000928 Record.clear();
929 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000930 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000931 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000932 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000933}
934
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000935//===----------------------------------------------------------------------===//
936// Type Serialization
937//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000938
Douglas Gregor2cf26342009-04-09 22:27:44 +0000939/// \brief Write the representation of a type to the PCH stream.
940void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000941 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000942 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000943 ID = NextTypeID++;
944
945 // Record the offset for this type.
946 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000947 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000948 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
949 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000950 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000951 }
952
953 RecordData Record;
954
955 // Emit the type's representation.
956 PCHTypeWriter W(*this, Record);
957 switch (T->getTypeClass()) {
958 // For all of the concrete, non-dependent types, call the
959 // appropriate visitor function.
960#define TYPE(Class, Base) \
961 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
962#define ABSTRACT_TYPE(Class, Base)
963#define DEPENDENT_TYPE(Class, Base)
964#include "clang/AST/TypeNodes.def"
965
966 // For all of the dependent type nodes (which only occur in C++
967 // templates), produce an error.
968#define TYPE(Class, Base)
969#define DEPENDENT_TYPE(Class, Base) case Type::Class:
970#include "clang/AST/TypeNodes.def"
971 assert(false && "Cannot serialize dependent type nodes");
972 break;
973 }
974
975 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000976 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +0000977
978 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000979 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000980}
981
982/// \brief Write a block containing all of the types.
983void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000984 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000985 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000986
Douglas Gregor366809a2009-04-26 03:49:13 +0000987 // Emit all of the types that need to be emitted (so far).
988 while (!TypesToEmit.empty()) {
989 const Type *T = TypesToEmit.front();
990 TypesToEmit.pop();
991 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
992 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000993 }
994
995 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +0000996 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000997}
998
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000999//===----------------------------------------------------------------------===//
1000// Declaration Serialization
1001//===----------------------------------------------------------------------===//
1002
Douglas Gregor2cf26342009-04-09 22:27:44 +00001003/// \brief Write the block containing all of the declaration IDs
1004/// lexically declared within the given DeclContext.
1005///
1006/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1007/// bistream, or 0 if no block was written.
1008uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1009 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001010 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001011 return 0;
1012
Douglas Gregorc9490c02009-04-16 22:23:12 +00001013 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001014 RecordData Record;
1015 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1016 DEnd = DC->decls_end(Context);
1017 D != DEnd; ++D)
1018 AddDeclRef(*D, Record);
1019
Douglas Gregor25123082009-04-22 22:34:57 +00001020 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001021 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001022 return Offset;
1023}
1024
1025/// \brief Write the block containing all of the declaration IDs
1026/// visible from the given DeclContext.
1027///
1028/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1029/// bistream, or 0 if no block was written.
1030uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1031 DeclContext *DC) {
1032 if (DC->getPrimaryContext() != DC)
1033 return 0;
1034
Douglas Gregoraff22df2009-04-21 22:32:33 +00001035 // Since there is no name lookup into functions or methods, and we
1036 // perform name lookup for the translation unit via the
1037 // IdentifierInfo chains, don't bother to build a
1038 // visible-declarations table for these entities.
1039 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001040 return 0;
1041
Douglas Gregor2cf26342009-04-09 22:27:44 +00001042 // Force the DeclContext to build a its name-lookup table.
1043 DC->lookup(Context, DeclarationName());
1044
1045 // Serialize the contents of the mapping used for lookup. Note that,
1046 // although we have two very different code paths, the serialized
1047 // representation is the same for both cases: a declaration name,
1048 // followed by a size, followed by references to the visible
1049 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001050 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001051 RecordData Record;
1052 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001053 if (!Map)
1054 return 0;
1055
Douglas Gregor2cf26342009-04-09 22:27:44 +00001056 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1057 D != DEnd; ++D) {
1058 AddDeclarationName(D->first, Record);
1059 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1060 Record.push_back(Result.second - Result.first);
1061 for(; Result.first != Result.second; ++Result.first)
1062 AddDeclRef(*Result.first, Record);
1063 }
1064
1065 if (Record.size() == 0)
1066 return 0;
1067
Douglas Gregorc9490c02009-04-16 22:23:12 +00001068 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001069 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001070 return Offset;
1071}
1072
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001073//===----------------------------------------------------------------------===//
1074// Global Method Pool and Selector Serialization
1075//===----------------------------------------------------------------------===//
1076
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001077namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001078// Trait used for the on-disk hash table used in the method pool.
1079class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1080 PCHWriter &Writer;
1081
1082public:
1083 typedef Selector key_type;
1084 typedef key_type key_type_ref;
1085
1086 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1087 typedef const data_type& data_type_ref;
1088
1089 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1090
1091 static unsigned ComputeHash(Selector Sel) {
1092 unsigned N = Sel.getNumArgs();
1093 if (N == 0)
1094 ++N;
1095 unsigned R = 5381;
1096 for (unsigned I = 0; I != N; ++I)
1097 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1098 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1099 return R;
1100 }
1101
1102 std::pair<unsigned,unsigned>
1103 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1104 data_type_ref Methods) {
1105 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1106 clang::io::Emit16(Out, KeyLen);
1107 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1108 for (const ObjCMethodList *Method = &Methods.first; Method;
1109 Method = Method->Next)
1110 if (Method->Method)
1111 DataLen += 4;
1112 for (const ObjCMethodList *Method = &Methods.second; Method;
1113 Method = Method->Next)
1114 if (Method->Method)
1115 DataLen += 4;
1116 clang::io::Emit16(Out, DataLen);
1117 return std::make_pair(KeyLen, DataLen);
1118 }
1119
Douglas Gregor83941df2009-04-25 17:48:32 +00001120 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1121 uint64_t Start = Out.tell();
1122 assert((Start >> 32) == 0 && "Selector key offset too large");
1123 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001124 unsigned N = Sel.getNumArgs();
1125 clang::io::Emit16(Out, N);
1126 if (N == 0)
1127 N = 1;
1128 for (unsigned I = 0; I != N; ++I)
1129 clang::io::Emit32(Out,
1130 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1131 }
1132
1133 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001134 data_type_ref Methods, unsigned DataLen) {
1135 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001136 unsigned NumInstanceMethods = 0;
1137 for (const ObjCMethodList *Method = &Methods.first; Method;
1138 Method = Method->Next)
1139 if (Method->Method)
1140 ++NumInstanceMethods;
1141
1142 unsigned NumFactoryMethods = 0;
1143 for (const ObjCMethodList *Method = &Methods.second; Method;
1144 Method = Method->Next)
1145 if (Method->Method)
1146 ++NumFactoryMethods;
1147
1148 clang::io::Emit16(Out, NumInstanceMethods);
1149 clang::io::Emit16(Out, NumFactoryMethods);
1150 for (const ObjCMethodList *Method = &Methods.first; Method;
1151 Method = Method->Next)
1152 if (Method->Method)
1153 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001154 for (const ObjCMethodList *Method = &Methods.second; Method;
1155 Method = Method->Next)
1156 if (Method->Method)
1157 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001158
1159 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001160 }
1161};
1162} // end anonymous namespace
1163
1164/// \brief Write the method pool into the PCH file.
1165///
1166/// The method pool contains both instance and factory methods, stored
1167/// in an on-disk hash table indexed by the selector.
1168void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1169 using namespace llvm;
1170
1171 // Create and write out the blob that contains the instance and
1172 // factor method pools.
1173 bool Empty = true;
1174 {
1175 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1176
1177 // Create the on-disk hash table representation. Start by
1178 // iterating through the instance method pool.
1179 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001180 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001181 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1182 Instance = SemaRef.InstanceMethodPool.begin(),
1183 InstanceEnd = SemaRef.InstanceMethodPool.end();
1184 Instance != InstanceEnd; ++Instance) {
1185 // Check whether there is a factory method with the same
1186 // selector.
1187 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1188 = SemaRef.FactoryMethodPool.find(Instance->first);
1189
1190 if (Factory == SemaRef.FactoryMethodPool.end())
1191 Generator.insert(Instance->first,
1192 std::make_pair(Instance->second,
1193 ObjCMethodList()));
1194 else
1195 Generator.insert(Instance->first,
1196 std::make_pair(Instance->second, Factory->second));
1197
Douglas Gregor83941df2009-04-25 17:48:32 +00001198 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001199 Empty = false;
1200 }
1201
1202 // Now iterate through the factory method pool, to pick up any
1203 // selectors that weren't already in the instance method pool.
1204 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1205 Factory = SemaRef.FactoryMethodPool.begin(),
1206 FactoryEnd = SemaRef.FactoryMethodPool.end();
1207 Factory != FactoryEnd; ++Factory) {
1208 // Check whether there is an instance method with the same
1209 // selector. If so, there is no work to do here.
1210 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1211 = SemaRef.InstanceMethodPool.find(Factory->first);
1212
Douglas Gregor83941df2009-04-25 17:48:32 +00001213 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001214 Generator.insert(Factory->first,
1215 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001216 ++NumSelectorsInMethodPool;
1217 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001218
1219 Empty = false;
1220 }
1221
Douglas Gregor83941df2009-04-25 17:48:32 +00001222 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001223 return;
1224
1225 // Create the on-disk hash table in a buffer.
1226 llvm::SmallVector<char, 4096> MethodPool;
1227 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001228 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001229 {
1230 PCHMethodPoolTrait Trait(*this);
1231 llvm::raw_svector_ostream Out(MethodPool);
1232 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001233 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001234 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001235
1236 // For every selector that we have seen but which was not
1237 // written into the hash table, write the selector itself and
1238 // record it's offset.
1239 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1240 if (SelectorOffsets[I] == 0)
1241 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001242 }
1243
1244 // Create a blob abbreviation
1245 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1246 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1247 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001248 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001249 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1250 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1251
Douglas Gregor83941df2009-04-25 17:48:32 +00001252 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001253 RecordData Record;
1254 Record.push_back(pch::METHOD_POOL);
1255 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001256 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001257 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1258 &MethodPool.front(),
1259 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001260
1261 // Create a blob abbreviation for the selector table offsets.
1262 Abbrev = new BitCodeAbbrev();
1263 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1264 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1265 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1266 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1267
1268 // Write the selector offsets table.
1269 Record.clear();
1270 Record.push_back(pch::SELECTOR_OFFSETS);
1271 Record.push_back(SelectorOffsets.size());
1272 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1273 (const char *)&SelectorOffsets.front(),
1274 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001275 }
1276}
1277
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001278//===----------------------------------------------------------------------===//
1279// Identifier Table Serialization
1280//===----------------------------------------------------------------------===//
1281
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001282namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001283class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1284 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001285 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001286
1287public:
1288 typedef const IdentifierInfo* key_type;
1289 typedef key_type key_type_ref;
1290
1291 typedef pch::IdentID data_type;
1292 typedef data_type data_type_ref;
1293
Douglas Gregor37e26842009-04-21 23:56:24 +00001294 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1295 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001296
1297 static unsigned ComputeHash(const IdentifierInfo* II) {
1298 return clang::BernsteinHash(II->getName());
1299 }
1300
Douglas Gregor37e26842009-04-21 23:56:24 +00001301 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001302 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1303 pch::IdentID ID) {
1304 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001305 unsigned DataLen = 4 + 4; // 4 bytes for token ID, builtin, flags
1306 // 4 bytes for the persistent ID
Douglas Gregor37e26842009-04-21 23:56:24 +00001307 if (II->hasMacroDefinition() &&
1308 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1309 DataLen += 8;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001310 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1311 DEnd = IdentifierResolver::end();
1312 D != DEnd; ++D)
1313 DataLen += sizeof(pch::DeclID);
Douglas Gregord6595a42009-04-25 21:04:17 +00001314 // We emit the key length after the data length so that the
1315 // "uninteresting" identifiers following the identifier hash table
1316 // structure will have the same (key length, key characters)
1317 // layout as the keys in the hash table. This also matches the
1318 // format for identifiers in pretokenized headers.
Douglas Gregor668c1a42009-04-21 22:25:48 +00001319 clang::io::Emit16(Out, DataLen);
Douglas Gregord6595a42009-04-25 21:04:17 +00001320 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001321 return std::make_pair(KeyLen, DataLen);
1322 }
1323
1324 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1325 unsigned KeyLen) {
1326 // Record the location of the key data. This is used when generating
1327 // the mapping from persistent IDs to strings.
1328 Writer.SetIdentifierOffset(II, Out.tell());
1329 Out.write(II->getName(), KeyLen);
1330 }
1331
1332 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1333 pch::IdentID ID, unsigned) {
1334 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001335 bool hasMacroDefinition =
1336 II->hasMacroDefinition() &&
1337 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001338 Bits = Bits | (uint32_t)II->getTokenID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001339 Bits = (Bits << 10) | (uint32_t)II->getObjCOrBuiltinID();
1340 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001341 Bits = (Bits << 1) | II->isExtensionToken();
1342 Bits = (Bits << 1) | II->isPoisoned();
1343 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
1344 clang::io::Emit32(Out, Bits);
1345 clang::io::Emit32(Out, ID);
1346
Douglas Gregor37e26842009-04-21 23:56:24 +00001347 if (hasMacroDefinition)
1348 clang::io::Emit64(Out, Writer.getMacroOffset(II));
1349
Douglas Gregor668c1a42009-04-21 22:25:48 +00001350 // Emit the declaration IDs in reverse order, because the
1351 // IdentifierResolver provides the declarations as they would be
1352 // visible (e.g., the function "stat" would come before the struct
1353 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1354 // adds declarations to the end of the list (so we need to see the
1355 // struct "status" before the function "status").
1356 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1357 IdentifierResolver::end());
1358 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1359 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001360 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001361 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001362 }
1363};
1364} // end anonymous namespace
1365
Douglas Gregorafaf3082009-04-11 00:14:32 +00001366/// \brief Write the identifier table into the PCH file.
1367///
1368/// The identifier table consists of a blob containing string data
1369/// (the actual identifiers themselves) and a separate "offsets" index
1370/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001371void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001372 using namespace llvm;
1373
1374 // Create and write out the blob that contains the identifier
1375 // strings.
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001376 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001377 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001378 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1379
Douglas Gregord6595a42009-04-25 21:04:17 +00001380 llvm::SmallVector<const IdentifierInfo *, 32> UninterestingIdentifiers;
1381
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001382 // Create the on-disk hash table representation.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001383 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1384 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1385 ID != IDEnd; ++ID) {
1386 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregord6595a42009-04-25 21:04:17 +00001387
1388 // Classify each identifier as either "interesting" or "not
1389 // interesting". Interesting identifiers are those that have
1390 // additional information that needs to be read from the PCH
1391 // file, e.g., a built-in ID, declaration chain, or macro
1392 // definition. These identifiers are placed into the hash table
1393 // so that they can be found when looked up in the user program.
1394 // All other identifiers are "uninteresting", which means that
1395 // the IdentifierInfo built by default has all of the
1396 // information we care about. Such identifiers are placed after
1397 // the hash table.
1398 const IdentifierInfo *II = ID->first;
1399 if (II->isPoisoned() ||
1400 II->isExtensionToken() ||
1401 II->hasMacroDefinition() ||
1402 II->getObjCOrBuiltinID() ||
1403 II->getFETokenInfo<void>())
1404 Generator.insert(ID->first, ID->second);
1405 else
1406 UninterestingIdentifiers.push_back(II);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001407 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001408
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001409 // Create the on-disk hash table in a buffer.
1410 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001411 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001412 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001413 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001414 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001415 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001416 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001417 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregord6595a42009-04-25 21:04:17 +00001418
1419 for (unsigned I = 0, N = UninterestingIdentifiers.size(); I != N; ++I) {
1420 const IdentifierInfo *II = UninterestingIdentifiers[I];
1421 unsigned N = II->getLength() + 1;
1422 clang::io::Emit16(Out, N);
1423 SetIdentifierOffset(II, Out.tell());
1424 Out.write(II->getName(), N);
1425 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001426 }
1427
1428 // Create a blob abbreviation
1429 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1430 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001432 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001433 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001434
1435 // Write the identifier table
1436 RecordData Record;
1437 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001438 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001439 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1440 &IdentifierTable.front(),
1441 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001442 }
1443
1444 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001445 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1446 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1447 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1449 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1450
1451 RecordData Record;
1452 Record.push_back(pch::IDENTIFIER_OFFSET);
1453 Record.push_back(IdentifierOffsets.size());
1454 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1455 (const char *)&IdentifierOffsets.front(),
1456 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001457}
1458
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001459//===----------------------------------------------------------------------===//
1460// General Serialization Routines
1461//===----------------------------------------------------------------------===//
1462
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001463/// \brief Write a record containing the given attributes.
1464void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1465 RecordData Record;
1466 for (; Attr; Attr = Attr->getNext()) {
1467 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1468 Record.push_back(Attr->isInherited());
1469 switch (Attr->getKind()) {
1470 case Attr::Alias:
1471 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1472 break;
1473
1474 case Attr::Aligned:
1475 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1476 break;
1477
1478 case Attr::AlwaysInline:
1479 break;
1480
1481 case Attr::AnalyzerNoReturn:
1482 break;
1483
1484 case Attr::Annotate:
1485 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1486 break;
1487
1488 case Attr::AsmLabel:
1489 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1490 break;
1491
1492 case Attr::Blocks:
1493 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1494 break;
1495
1496 case Attr::Cleanup:
1497 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1498 break;
1499
1500 case Attr::Const:
1501 break;
1502
1503 case Attr::Constructor:
1504 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1505 break;
1506
1507 case Attr::DLLExport:
1508 case Attr::DLLImport:
1509 case Attr::Deprecated:
1510 break;
1511
1512 case Attr::Destructor:
1513 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1514 break;
1515
1516 case Attr::FastCall:
1517 break;
1518
1519 case Attr::Format: {
1520 const FormatAttr *Format = cast<FormatAttr>(Attr);
1521 AddString(Format->getType(), Record);
1522 Record.push_back(Format->getFormatIdx());
1523 Record.push_back(Format->getFirstArg());
1524 break;
1525 }
1526
Chris Lattnercf2a7212009-04-20 19:12:28 +00001527 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001528 case Attr::IBOutletKind:
1529 case Attr::NoReturn:
1530 case Attr::NoThrow:
1531 case Attr::Nodebug:
1532 case Attr::Noinline:
1533 break;
1534
1535 case Attr::NonNull: {
1536 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1537 Record.push_back(NonNull->size());
1538 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1539 break;
1540 }
1541
1542 case Attr::ObjCException:
1543 case Attr::ObjCNSObject:
Ted Kremenekc6a59e42009-04-27 19:36:56 +00001544 case Attr::ObjCOwnershipCFRelease:
1545 case Attr::ObjCOwnershipRelease:
Ted Kremenek4064de92009-04-27 18:27:22 +00001546 case Attr::ObjCOwnershipCFRetain:
Ted Kremenekde9a81b2009-04-25 00:17:17 +00001547 case Attr::ObjCOwnershipRetain:
Ted Kremenek0fc169e2009-04-24 23:09:54 +00001548 case Attr::ObjCOwnershipReturns:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001549 case Attr::Overloadable:
1550 break;
1551
1552 case Attr::Packed:
1553 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1554 break;
1555
1556 case Attr::Pure:
1557 break;
1558
1559 case Attr::Regparm:
1560 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1561 break;
1562
1563 case Attr::Section:
1564 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1565 break;
1566
1567 case Attr::StdCall:
1568 case Attr::TransparentUnion:
1569 case Attr::Unavailable:
1570 case Attr::Unused:
1571 case Attr::Used:
1572 break;
1573
1574 case Attr::Visibility:
1575 // FIXME: stable encoding
1576 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1577 break;
1578
1579 case Attr::WarnUnusedResult:
1580 case Attr::Weak:
1581 case Attr::WeakImport:
1582 break;
1583 }
1584 }
1585
Douglas Gregorc9490c02009-04-16 22:23:12 +00001586 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001587}
1588
1589void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1590 Record.push_back(Str.size());
1591 Record.insert(Record.end(), Str.begin(), Str.end());
1592}
1593
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001594/// \brief Note that the identifier II occurs at the given offset
1595/// within the identifier table.
1596void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001597 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001598}
1599
Douglas Gregor83941df2009-04-25 17:48:32 +00001600/// \brief Note that the selector Sel occurs at the given offset
1601/// within the method pool/selector table.
1602void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1603 unsigned ID = SelectorIDs[Sel];
1604 assert(ID && "Unknown selector");
1605 SelectorOffsets[ID - 1] = Offset;
1606}
1607
Douglas Gregorc9490c02009-04-16 22:23:12 +00001608PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001609 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001610 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1611 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001612
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001613void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001614 using namespace llvm;
1615
Douglas Gregore7785042009-04-20 15:53:59 +00001616 ASTContext &Context = SemaRef.Context;
1617 Preprocessor &PP = SemaRef.PP;
1618
Douglas Gregor2cf26342009-04-09 22:27:44 +00001619 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001620 Stream.Emit((unsigned)'C', 8);
1621 Stream.Emit((unsigned)'P', 8);
1622 Stream.Emit((unsigned)'C', 8);
1623 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001624
1625 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001626
1627 // The translation unit is the first declaration we'll emit.
1628 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1629 DeclsToEmit.push(Context.getTranslationUnitDecl());
1630
Douglas Gregor2deaea32009-04-22 18:49:13 +00001631 // Make sure that we emit IdentifierInfos (and any attached
1632 // declarations) for builtins.
1633 {
1634 IdentifierTable &Table = PP.getIdentifierTable();
1635 llvm::SmallVector<const char *, 32> BuiltinNames;
1636 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1637 Context.getLangOptions().NoBuiltin);
1638 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1639 getIdentifierRef(&Table.get(BuiltinNames[I]));
1640 }
1641
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001642 // Build a record containing all of the tentative definitions in
1643 // this header file. Generally, this record will be empty.
1644 RecordData TentativeDefinitions;
1645 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1646 TD = SemaRef.TentativeDefinitions.begin(),
1647 TDEnd = SemaRef.TentativeDefinitions.end();
1648 TD != TDEnd; ++TD)
1649 AddDeclRef(TD->second, TentativeDefinitions);
1650
Douglas Gregor14c22f22009-04-22 22:18:58 +00001651 // Build a record containing all of the locally-scoped external
1652 // declarations in this header file. Generally, this record will be
1653 // empty.
1654 RecordData LocallyScopedExternalDecls;
1655 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1656 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1657 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1658 TD != TDEnd; ++TD)
1659 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1660
Douglas Gregorb81c1702009-04-27 20:06:05 +00001661 // Build a record containing all of the ext_vector declarations.
1662 RecordData ExtVectorDecls;
1663 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1664 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1665
1666 // Build a record containing all of the Objective-C category
1667 // implementations.
1668 RecordData ObjCCategoryImpls;
1669 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1670 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1671
Douglas Gregor2cf26342009-04-09 22:27:44 +00001672 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001673 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001674 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregor2bec0412009-04-10 21:16:55 +00001675 WriteTargetTriple(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001676 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001677 if (StatCalls)
1678 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001679 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001680 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001681
1682 // Keep writing types and declarations until all types and
1683 // declarations have been written.
1684 do {
1685 if (!DeclsToEmit.empty())
1686 WriteDeclsBlock(Context);
1687 if (!TypesToEmit.empty())
1688 WriteTypesBlock(Context);
1689 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1690
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001691 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001692 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001693
1694 // Write the type offsets array
1695 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1696 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1699 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1700 Record.clear();
1701 Record.push_back(pch::TYPE_OFFSET);
1702 Record.push_back(TypeOffsets.size());
1703 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1704 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001705 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001706
1707 // Write the declaration offsets array
1708 Abbrev = new BitCodeAbbrev();
1709 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1712 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1713 Record.clear();
1714 Record.push_back(pch::DECL_OFFSET);
1715 Record.push_back(DeclOffsets.size());
1716 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1717 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001718 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001719
1720 // Write the record of special types.
1721 Record.clear();
1722 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001723 AddTypeRef(Context.getObjCIdType(), Record);
1724 AddTypeRef(Context.getObjCSelType(), Record);
1725 AddTypeRef(Context.getObjCProtoType(), Record);
1726 AddTypeRef(Context.getObjCClassType(), Record);
1727 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1728 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001729 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1730
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001731 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001732 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001733 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001734
1735 // Write the record containing tentative definitions.
1736 if (!TentativeDefinitions.empty())
1737 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001738
1739 // Write the record containing locally-scoped external definitions.
1740 if (!LocallyScopedExternalDecls.empty())
1741 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1742 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001743
1744 // Write the record containing ext_vector type names.
1745 if (!ExtVectorDecls.empty())
1746 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1747
1748 // Write the record containing Objective-C category implementations.
1749 if (!ObjCCategoryImpls.empty())
1750 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001751
1752 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001753 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001754 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001755 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001756 Record.push_back(NumLexicalDeclContexts);
1757 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001758 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001759 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001760}
1761
1762void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1763 Record.push_back(Loc.getRawEncoding());
1764}
1765
1766void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1767 Record.push_back(Value.getBitWidth());
1768 unsigned N = Value.getNumWords();
1769 const uint64_t* Words = Value.getRawData();
1770 for (unsigned I = 0; I != N; ++I)
1771 Record.push_back(Words[I]);
1772}
1773
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001774void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1775 Record.push_back(Value.isUnsigned());
1776 AddAPInt(Value, Record);
1777}
1778
Douglas Gregor17fc2232009-04-14 21:55:33 +00001779void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1780 AddAPInt(Value.bitcastToAPInt(), Record);
1781}
1782
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001784 Record.push_back(getIdentifierRef(II));
1785}
1786
1787pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1788 if (II == 0)
1789 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001790
1791 pch::IdentID &ID = IdentifierIDs[II];
1792 if (ID == 0)
1793 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001794 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001795}
1796
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001797void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1798 if (SelRef.getAsOpaquePtr() == 0) {
1799 Record.push_back(0);
1800 return;
1801 }
1802
1803 pch::SelectorID &SID = SelectorIDs[SelRef];
1804 if (SID == 0) {
1805 SID = SelectorIDs.size();
1806 SelVector.push_back(SelRef);
1807 }
1808 Record.push_back(SID);
1809}
1810
Douglas Gregor2cf26342009-04-09 22:27:44 +00001811void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1812 if (T.isNull()) {
1813 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1814 return;
1815 }
1816
1817 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001818 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001819 switch (BT->getKind()) {
1820 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1821 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1822 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1823 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1824 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1825 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1826 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1827 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1828 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1829 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1830 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1831 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1832 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1833 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1834 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1835 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1836 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1837 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1838 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1839 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1840 }
1841
1842 Record.push_back((ID << 3) | T.getCVRQualifiers());
1843 return;
1844 }
1845
Douglas Gregor8038d512009-04-10 17:25:41 +00001846 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001847 if (ID == 0) {
1848 // We haven't seen this type before. Assign it a new ID and put it
1849 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001850 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001851 TypesToEmit.push(T.getTypePtr());
1852 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001853
1854 // Encode the type qualifiers in the type reference.
1855 Record.push_back((ID << 3) | T.getCVRQualifiers());
1856}
1857
1858void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1859 if (D == 0) {
1860 Record.push_back(0);
1861 return;
1862 }
1863
Douglas Gregor8038d512009-04-10 17:25:41 +00001864 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001865 if (ID == 0) {
1866 // We haven't seen this declaration before. Give it a new ID and
1867 // enqueue it in the list of declarations to emit.
1868 ID = DeclIDs.size();
1869 DeclsToEmit.push(const_cast<Decl *>(D));
1870 }
1871
1872 Record.push_back(ID);
1873}
1874
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001875pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1876 if (D == 0)
1877 return 0;
1878
1879 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1880 return DeclIDs[D];
1881}
1882
Douglas Gregor2cf26342009-04-09 22:27:44 +00001883void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001884 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001885 Record.push_back(Name.getNameKind());
1886 switch (Name.getNameKind()) {
1887 case DeclarationName::Identifier:
1888 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1889 break;
1890
1891 case DeclarationName::ObjCZeroArgSelector:
1892 case DeclarationName::ObjCOneArgSelector:
1893 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001894 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001895 break;
1896
1897 case DeclarationName::CXXConstructorName:
1898 case DeclarationName::CXXDestructorName:
1899 case DeclarationName::CXXConversionFunctionName:
1900 AddTypeRef(Name.getCXXNameType(), Record);
1901 break;
1902
1903 case DeclarationName::CXXOperatorName:
1904 Record.push_back(Name.getCXXOverloadedOperator());
1905 break;
1906
1907 case DeclarationName::CXXUsingDirective:
1908 // No extra data to emit
1909 break;
1910 }
1911}
Douglas Gregor0b748912009-04-14 21:18:50 +00001912