blob: 80e863bd711076731cd527229941f4b45d2b4d62 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
Sebastian Redl2767d882009-05-27 22:11:52 +0000165 Record.push_back(T->hasExceptionSpec());
166 Record.push_back(T->hasAnyExceptionSpec());
167 Record.push_back(T->getNumExceptions());
168 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
169 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_FUNCTION_PROTO;
171}
172
173void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
174 Writer.AddDeclRef(T->getDecl(), Record);
175 Code = pch::TYPE_TYPEDEF;
176}
177
178void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000180 Code = pch::TYPE_TYPEOF_EXPR;
181}
182
183void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
184 Writer.AddTypeRef(T->getUnderlyingType(), Record);
185 Code = pch::TYPE_TYPEOF;
186}
187
188void PCHTypeWriter::VisitTagType(const TagType *T) {
189 Writer.AddDeclRef(T->getDecl(), Record);
190 assert(!T->isBeingDefined() &&
191 "Cannot serialize in the middle of a type definition");
192}
193
194void PCHTypeWriter::VisitRecordType(const RecordType *T) {
195 VisitTagType(T);
196 Code = pch::TYPE_RECORD;
197}
198
199void PCHTypeWriter::VisitEnumType(const EnumType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_ENUM;
202}
203
204void
205PCHTypeWriter::VisitTemplateSpecializationType(
206 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000207 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 assert(false && "Cannot serialize template specialization types");
209}
210
211void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize qualified name types");
214}
215
216void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
217 Writer.AddDeclRef(T->getDecl(), Record);
218 Code = pch::TYPE_OBJC_INTERFACE;
219}
220
221void
222PCHTypeWriter::VisitObjCQualifiedInterfaceType(
223 const ObjCQualifiedInterfaceType *T) {
224 VisitObjCInterfaceType(T);
225 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000226 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
227 E = T->qual_end(); I != E; ++I)
228 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000229 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
230}
231
232void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
233 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000234 for (ObjCQualifiedIdType::qual_iterator I = T->qual_begin(),
235 E = T->qual_end(); I != E; ++I)
236 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000237 Code = pch::TYPE_OBJC_QUALIFIED_ID;
238}
239
Chris Lattner80f83c62009-04-22 05:57:30 +0000240//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000241// PCHWriter Implementation
242//===----------------------------------------------------------------------===//
243
Chris Lattner920673a2009-04-26 22:26:21 +0000244static void EmitBlockID(unsigned ID, const char *Name,
245 llvm::BitstreamWriter &Stream,
246 PCHWriter::RecordData &Record) {
247 Record.clear();
248 Record.push_back(ID);
249 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
250
251 // Emit the block name if present.
252 if (Name == 0 || Name[0] == 0) return;
253 Record.clear();
254 while (*Name)
255 Record.push_back(*Name++);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
257}
258
259static void EmitRecordID(unsigned ID, const char *Name,
260 llvm::BitstreamWriter &Stream,
261 PCHWriter::RecordData &Record) {
262 Record.clear();
263 Record.push_back(ID);
264 while (*Name)
265 Record.push_back(*Name++);
266 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000267}
268
269static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
270 PCHWriter::RecordData &Record) {
271#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
272 RECORD(STMT_STOP);
273 RECORD(STMT_NULL_PTR);
274 RECORD(STMT_NULL);
275 RECORD(STMT_COMPOUND);
276 RECORD(STMT_CASE);
277 RECORD(STMT_DEFAULT);
278 RECORD(STMT_LABEL);
279 RECORD(STMT_IF);
280 RECORD(STMT_SWITCH);
281 RECORD(STMT_WHILE);
282 RECORD(STMT_DO);
283 RECORD(STMT_FOR);
284 RECORD(STMT_GOTO);
285 RECORD(STMT_INDIRECT_GOTO);
286 RECORD(STMT_CONTINUE);
287 RECORD(STMT_BREAK);
288 RECORD(STMT_RETURN);
289 RECORD(STMT_DECL);
290 RECORD(STMT_ASM);
291 RECORD(EXPR_PREDEFINED);
292 RECORD(EXPR_DECL_REF);
293 RECORD(EXPR_INTEGER_LITERAL);
294 RECORD(EXPR_FLOATING_LITERAL);
295 RECORD(EXPR_IMAGINARY_LITERAL);
296 RECORD(EXPR_STRING_LITERAL);
297 RECORD(EXPR_CHARACTER_LITERAL);
298 RECORD(EXPR_PAREN);
299 RECORD(EXPR_UNARY_OPERATOR);
300 RECORD(EXPR_SIZEOF_ALIGN_OF);
301 RECORD(EXPR_ARRAY_SUBSCRIPT);
302 RECORD(EXPR_CALL);
303 RECORD(EXPR_MEMBER);
304 RECORD(EXPR_BINARY_OPERATOR);
305 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
306 RECORD(EXPR_CONDITIONAL_OPERATOR);
307 RECORD(EXPR_IMPLICIT_CAST);
308 RECORD(EXPR_CSTYLE_CAST);
309 RECORD(EXPR_COMPOUND_LITERAL);
310 RECORD(EXPR_EXT_VECTOR_ELEMENT);
311 RECORD(EXPR_INIT_LIST);
312 RECORD(EXPR_DESIGNATED_INIT);
313 RECORD(EXPR_IMPLICIT_VALUE_INIT);
314 RECORD(EXPR_VA_ARG);
315 RECORD(EXPR_ADDR_LABEL);
316 RECORD(EXPR_STMT);
317 RECORD(EXPR_TYPES_COMPATIBLE);
318 RECORD(EXPR_CHOOSE);
319 RECORD(EXPR_GNU_NULL);
320 RECORD(EXPR_SHUFFLE_VECTOR);
321 RECORD(EXPR_BLOCK);
322 RECORD(EXPR_BLOCK_DECL_REF);
323 RECORD(EXPR_OBJC_STRING_LITERAL);
324 RECORD(EXPR_OBJC_ENCODE);
325 RECORD(EXPR_OBJC_SELECTOR_EXPR);
326 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
327 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
328 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
329 RECORD(EXPR_OBJC_KVC_REF_EXPR);
330 RECORD(EXPR_OBJC_MESSAGE_EXPR);
331 RECORD(EXPR_OBJC_SUPER_EXPR);
332 RECORD(STMT_OBJC_FOR_COLLECTION);
333 RECORD(STMT_OBJC_CATCH);
334 RECORD(STMT_OBJC_FINALLY);
335 RECORD(STMT_OBJC_AT_TRY);
336 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
337 RECORD(STMT_OBJC_AT_THROW);
338#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000339}
340
341void PCHWriter::WriteBlockInfoBlock() {
342 RecordData Record;
343 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
344
Chris Lattner880f3f72009-04-27 00:40:25 +0000345#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000346#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
347
348 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000349 BLOCK(PCH_BLOCK);
Zhongxing Xu29b61a52009-06-03 09:23:28 +0000350 RECORD(ORIGINAL_FILE_NAME);
Chris Lattner920673a2009-04-26 22:26:21 +0000351 RECORD(TYPE_OFFSET);
352 RECORD(DECL_OFFSET);
353 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000354 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000355 RECORD(IDENTIFIER_OFFSET);
356 RECORD(IDENTIFIER_TABLE);
357 RECORD(EXTERNAL_DEFINITIONS);
358 RECORD(SPECIAL_TYPES);
359 RECORD(STATISTICS);
360 RECORD(TENTATIVE_DEFINITIONS);
361 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
362 RECORD(SELECTOR_OFFSETS);
363 RECORD(METHOD_POOL);
364 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000365 RECORD(SOURCE_LOCATION_OFFSETS);
366 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000367 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000368 RECORD(EXT_VECTOR_DECLS);
369 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000370
Chris Lattner920673a2009-04-26 22:26:21 +0000371 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000372 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000373 RECORD(SM_SLOC_FILE_ENTRY);
374 RECORD(SM_SLOC_BUFFER_ENTRY);
375 RECORD(SM_SLOC_BUFFER_BLOB);
376 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
377 RECORD(SM_LINE_TABLE);
378 RECORD(SM_HEADER_FILE_INFO);
379
380 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000381 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000382 RECORD(PP_MACRO_OBJECT_LIKE);
383 RECORD(PP_MACRO_FUNCTION_LIKE);
384 RECORD(PP_TOKEN);
385
386 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000387 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000388 RECORD(TYPE_EXT_QUAL);
389 RECORD(TYPE_FIXED_WIDTH_INT);
390 RECORD(TYPE_COMPLEX);
391 RECORD(TYPE_POINTER);
392 RECORD(TYPE_BLOCK_POINTER);
393 RECORD(TYPE_LVALUE_REFERENCE);
394 RECORD(TYPE_RVALUE_REFERENCE);
395 RECORD(TYPE_MEMBER_POINTER);
396 RECORD(TYPE_CONSTANT_ARRAY);
397 RECORD(TYPE_INCOMPLETE_ARRAY);
398 RECORD(TYPE_VARIABLE_ARRAY);
399 RECORD(TYPE_VECTOR);
400 RECORD(TYPE_EXT_VECTOR);
401 RECORD(TYPE_FUNCTION_PROTO);
402 RECORD(TYPE_FUNCTION_NO_PROTO);
403 RECORD(TYPE_TYPEDEF);
404 RECORD(TYPE_TYPEOF_EXPR);
405 RECORD(TYPE_TYPEOF);
406 RECORD(TYPE_RECORD);
407 RECORD(TYPE_ENUM);
408 RECORD(TYPE_OBJC_INTERFACE);
409 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
410 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000411 // Statements and Exprs can occur in the Types block.
412 AddStmtsExprs(Stream, Record);
413
Chris Lattner920673a2009-04-26 22:26:21 +0000414 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000415 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000416 RECORD(DECL_ATTR);
417 RECORD(DECL_TRANSLATION_UNIT);
418 RECORD(DECL_TYPEDEF);
419 RECORD(DECL_ENUM);
420 RECORD(DECL_RECORD);
421 RECORD(DECL_ENUM_CONSTANT);
422 RECORD(DECL_FUNCTION);
423 RECORD(DECL_OBJC_METHOD);
424 RECORD(DECL_OBJC_INTERFACE);
425 RECORD(DECL_OBJC_PROTOCOL);
426 RECORD(DECL_OBJC_IVAR);
427 RECORD(DECL_OBJC_AT_DEFS_FIELD);
428 RECORD(DECL_OBJC_CLASS);
429 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
430 RECORD(DECL_OBJC_CATEGORY);
431 RECORD(DECL_OBJC_CATEGORY_IMPL);
432 RECORD(DECL_OBJC_IMPLEMENTATION);
433 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
434 RECORD(DECL_OBJC_PROPERTY);
435 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000436 RECORD(DECL_FIELD);
437 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000438 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000439 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000440 RECORD(DECL_ORIGINAL_PARM_VAR);
441 RECORD(DECL_FILE_SCOPE_ASM);
442 RECORD(DECL_BLOCK);
443 RECORD(DECL_CONTEXT_LEXICAL);
444 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000445 // Statements and Exprs can occur in the Decls block.
446 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000447#undef RECORD
448#undef BLOCK
449 Stream.ExitBlock();
450}
451
452
Douglas Gregorb7064742009-04-27 22:23:34 +0000453/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000454void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000455 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000456
457 // Original file name
458 SourceManager &SM = Context.getSourceManager();
459 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
460 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
461 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
462 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
463 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
464
465 llvm::sys::Path MainFilePath(MainFile->getName());
466 std::string MainFileName;
467
468 if (!MainFilePath.isAbsolute()) {
469 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
470 P.appendComponent(MainFilePath.toString());
471 MainFileName = P.toString();
472 } else {
473 MainFileName = MainFilePath.toString();
474 }
475
476 RecordData Record;
477 Record.push_back(pch::ORIGINAL_FILE_NAME);
478 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
479 MainFileName.size());
480 }
481
482 // Metadata
483 const TargetInfo &Target = Context.Target;
484 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
485 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
486 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
487 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
488 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
489 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
490 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
491 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000492
493 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000494 Record.push_back(pch::METADATA);
495 Record.push_back(pch::VERSION_MAJOR);
496 Record.push_back(pch::VERSION_MINOR);
497 Record.push_back(CLANG_VERSION_MAJOR);
498 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000499 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000500 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000501}
502
503/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000504void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
505 RecordData Record;
506 Record.push_back(LangOpts.Trigraphs);
507 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
508 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
509 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
510 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
511 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
512 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
513 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
514 Record.push_back(LangOpts.C99); // C99 Support
515 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
516 Record.push_back(LangOpts.CPlusPlus); // C++ Support
517 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000518 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
519
520 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
521 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
522 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
523
524 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000525 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
526 Record.push_back(LangOpts.LaxVectorConversions);
527 Record.push_back(LangOpts.Exceptions); // Support exception handling.
528
529 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
530 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
531 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
532
Chris Lattnercd4da472009-04-27 07:35:58 +0000533 // Whether static initializers are protected by locks.
534 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000535 Record.push_back(LangOpts.Blocks); // block extension to C
536 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
537 // they are unused.
538 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
539 // (modulo the platform support).
540
541 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
542 // signed integer arithmetic overflows.
543
544 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
545 // may be ripped out at any time.
546
547 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
548 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
549 // defined.
550 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
551 // opposed to __DYNAMIC__).
552 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
553
554 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
555 // used (instead of C99 semantics).
556 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000557 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
558 // be enabled.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000559 Record.push_back(LangOpts.getGCMode());
560 Record.push_back(LangOpts.getVisibilityMode());
561 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000562 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000563}
564
Douglas Gregorab1cef72009-04-10 03:52:48 +0000565//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000566// stat cache Serialization
567//===----------------------------------------------------------------------===//
568
569namespace {
570// Trait used for the on-disk hash table of stat cache results.
571class VISIBILITY_HIDDEN PCHStatCacheTrait {
572public:
573 typedef const char * key_type;
574 typedef key_type key_type_ref;
575
576 typedef std::pair<int, struct stat> data_type;
577 typedef const data_type& data_type_ref;
578
579 static unsigned ComputeHash(const char *path) {
580 return BernsteinHash(path);
581 }
582
583 std::pair<unsigned,unsigned>
584 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
585 data_type_ref Data) {
586 unsigned StrLen = strlen(path);
587 clang::io::Emit16(Out, StrLen);
588 unsigned DataLen = 1; // result value
589 if (Data.first == 0)
590 DataLen += 4 + 4 + 2 + 8 + 8;
591 clang::io::Emit8(Out, DataLen);
592 return std::make_pair(StrLen + 1, DataLen);
593 }
594
595 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
596 Out.write(path, KeyLen);
597 }
598
599 void EmitData(llvm::raw_ostream& Out, key_type_ref,
600 data_type_ref Data, unsigned DataLen) {
601 using namespace clang::io;
602 uint64_t Start = Out.tell(); (void)Start;
603
604 // Result of stat()
605 Emit8(Out, Data.first? 1 : 0);
606
607 if (Data.first == 0) {
608 Emit32(Out, (uint32_t) Data.second.st_ino);
609 Emit32(Out, (uint32_t) Data.second.st_dev);
610 Emit16(Out, (uint16_t) Data.second.st_mode);
611 Emit64(Out, (uint64_t) Data.second.st_mtime);
612 Emit64(Out, (uint64_t) Data.second.st_size);
613 }
614
615 assert(Out.tell() - Start == DataLen && "Wrong data length");
616 }
617};
618} // end anonymous namespace
619
620/// \brief Write the stat() system call cache to the PCH file.
621void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
622 // Build the on-disk hash table containing information about every
623 // stat() call.
624 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
625 unsigned NumStatEntries = 0;
626 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
627 StatEnd = StatCalls.end();
628 Stat != StatEnd; ++Stat, ++NumStatEntries)
629 Generator.insert(Stat->first(), Stat->second);
630
631 // Create the on-disk hash table in a buffer.
632 llvm::SmallVector<char, 4096> StatCacheData;
633 uint32_t BucketOffset;
634 {
635 llvm::raw_svector_ostream Out(StatCacheData);
636 // Make sure that no bucket is at offset 0
637 clang::io::Emit32(Out, 0);
638 BucketOffset = Generator.Emit(Out);
639 }
640
641 // Create a blob abbreviation
642 using namespace llvm;
643 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
644 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
648 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
649
650 // Write the stat cache
651 RecordData Record;
652 Record.push_back(pch::STAT_CACHE);
653 Record.push_back(BucketOffset);
654 Record.push_back(NumStatEntries);
655 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
656 &StatCacheData.front(),
657 StatCacheData.size());
658}
659
660//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000661// Source Manager Serialization
662//===----------------------------------------------------------------------===//
663
664/// \brief Create an abbreviation for the SLocEntry that refers to a
665/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000666static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000667 using namespace llvm;
668 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
669 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
671 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000675 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000676}
677
678/// \brief Create an abbreviation for the SLocEntry that refers to a
679/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000680static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000681 using namespace llvm;
682 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
683 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000689 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000690}
691
692/// \brief Create an abbreviation for the SLocEntry that refers to a
693/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000694static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000695 using namespace llvm;
696 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
697 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000699 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000700}
701
702/// \brief Create an abbreviation for the SLocEntry that refers to an
703/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000704static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000705 using namespace llvm;
706 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
707 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000713 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000714}
715
716/// \brief Writes the block containing the serialized form of the
717/// source manager.
718///
719/// TODO: We should probably use an on-disk hash table (stored in a
720/// blob), indexed based on the file name, so that we only create
721/// entries for files that we actually need. In the common case (no
722/// errors), we probably won't have to create file entries for any of
723/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000724void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
725 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000726 RecordData Record;
727
Chris Lattner84b04f12009-04-10 17:16:57 +0000728 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000729 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000730
731 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000732 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
733 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
734 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
735 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000736
Douglas Gregor635f97f2009-04-13 16:31:14 +0000737 // Write the line table.
738 if (SourceMgr.hasLineTable()) {
739 LineTableInfo &LineTable = SourceMgr.getLineTable();
740
741 // Emit the file names
742 Record.push_back(LineTable.getNumFilenames());
743 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
744 // Emit the file name
745 const char *Filename = LineTable.getFilename(I);
746 unsigned FilenameLen = Filename? strlen(Filename) : 0;
747 Record.push_back(FilenameLen);
748 if (FilenameLen)
749 Record.insert(Record.end(), Filename, Filename + FilenameLen);
750 }
751
752 // Emit the line entries
753 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
754 L != LEnd; ++L) {
755 // Emit the file ID
756 Record.push_back(L->first);
757
758 // Emit the line entries
759 Record.push_back(L->second.size());
760 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
761 LEEnd = L->second.end();
762 LE != LEEnd; ++LE) {
763 Record.push_back(LE->FileOffset);
764 Record.push_back(LE->LineNo);
765 Record.push_back(LE->FilenameID);
766 Record.push_back((unsigned)LE->FileKind);
767 Record.push_back(LE->IncludeOffset);
768 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000769 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000770 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000771 }
772
Douglas Gregor32e231c2009-04-27 06:38:32 +0000773 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000774 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000775 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000776 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
777 E = HS.header_file_end();
778 I != E; ++I) {
779 Record.push_back(I->isImport);
780 Record.push_back(I->DirInfo);
781 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000782 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000783 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
784 Record.clear();
785 }
786
Douglas Gregor32e231c2009-04-27 06:38:32 +0000787 // Write out the source location entry table. We skip the first
788 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000789 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000790 RecordData PreloadSLocs;
791 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
792 for (SourceManager::sloc_entry_iterator
793 SLoc = SourceMgr.sloc_entry_begin() + 1,
794 SLocEnd = SourceMgr.sloc_entry_end();
795 SLoc != SLocEnd; ++SLoc) {
796 // Record the offset of this source-location entry.
797 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
798
799 // Figure out which record code to use.
800 unsigned Code;
801 if (SLoc->isFile()) {
802 if (SLoc->getFile().getContentCache()->Entry)
803 Code = pch::SM_SLOC_FILE_ENTRY;
804 else
805 Code = pch::SM_SLOC_BUFFER_ENTRY;
806 } else
807 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
808 Record.clear();
809 Record.push_back(Code);
810
811 Record.push_back(SLoc->getOffset());
812 if (SLoc->isFile()) {
813 const SrcMgr::FileInfo &File = SLoc->getFile();
814 Record.push_back(File.getIncludeLoc().getRawEncoding());
815 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
816 Record.push_back(File.hasLineDirectives());
817
818 const SrcMgr::ContentCache *Content = File.getContentCache();
819 if (Content->Entry) {
820 // The source location entry is a file. The blob associated
821 // with this entry is the file name.
822 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
823 Content->Entry->getName(),
824 strlen(Content->Entry->getName()));
825
826 // FIXME: For now, preload all file source locations, so that
827 // we get the appropriate File entries in the reader. This is
828 // a temporary measure.
829 PreloadSLocs.push_back(SLocEntryOffsets.size());
830 } else {
831 // The source location entry is a buffer. The blob associated
832 // with this entry contains the contents of the buffer.
833
834 // We add one to the size so that we capture the trailing NULL
835 // that is required by llvm::MemoryBuffer::getMemBuffer (on
836 // the reader side).
837 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
838 const char *Name = Buffer->getBufferIdentifier();
839 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
840 Record.clear();
841 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
842 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
843 Buffer->getBufferStart(),
844 Buffer->getBufferSize() + 1);
845
846 if (strcmp(Name, "<built-in>") == 0)
847 PreloadSLocs.push_back(SLocEntryOffsets.size());
848 }
849 } else {
850 // The source location entry is an instantiation.
851 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
852 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
853 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
854 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
855
856 // Compute the token length for this macro expansion.
857 unsigned NextOffset = SourceMgr.getNextOffset();
858 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
859 if (++NextSLoc != SLocEnd)
860 NextOffset = NextSLoc->getOffset();
861 Record.push_back(NextOffset - SLoc->getOffset() - 1);
862 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
863 }
864 }
865
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000866 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000867
868 if (SLocEntryOffsets.empty())
869 return;
870
871 // Write the source-location offsets table into the PCH block. This
872 // table is used for lazily loading source-location information.
873 using namespace llvm;
874 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
875 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
879 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
880
881 Record.clear();
882 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
883 Record.push_back(SLocEntryOffsets.size());
884 Record.push_back(SourceMgr.getNextOffset());
885 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
886 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000887 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000888
889 // Write the source location entry preloads array, telling the PCH
890 // reader which source locations entries it should load eagerly.
891 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000892}
893
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000894//===----------------------------------------------------------------------===//
895// Preprocessor Serialization
896//===----------------------------------------------------------------------===//
897
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000898/// \brief Writes the block containing the serialized form of the
899/// preprocessor.
900///
Chris Lattner850eabd2009-04-10 18:08:30 +0000901void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000902 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000903
Chris Lattner4b21c202009-04-13 01:29:17 +0000904 // If the preprocessor __COUNTER__ value has been bumped, remember it.
905 if (PP.getCounterValue() != 0) {
906 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000907 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000908 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000909 }
910
911 // Enter the preprocessor block.
912 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000913
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000914 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
915 // FIXME: use diagnostics subsystem for localization etc.
916 if (PP.SawDateOrTime())
917 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
918
Chris Lattner1b094952009-04-10 18:00:12 +0000919 // Loop over all the macro definitions that are live at the end of the file,
920 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000921 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
922 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000923 // FIXME: This emits macros in hash table order, we should do it in a stable
924 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000925 MacroInfo *MI = I->second;
926
927 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
928 // been redefined by the header (in which case they are not isBuiltinMacro).
929 if (MI->isBuiltinMacro())
930 continue;
931
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000932 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000933 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000934 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000935 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
936 Record.push_back(MI->isUsed());
937
938 unsigned Code;
939 if (MI->isObjectLike()) {
940 Code = pch::PP_MACRO_OBJECT_LIKE;
941 } else {
942 Code = pch::PP_MACRO_FUNCTION_LIKE;
943
944 Record.push_back(MI->isC99Varargs());
945 Record.push_back(MI->isGNUVarargs());
946 Record.push_back(MI->getNumArgs());
947 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
948 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000949 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000950 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000951 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000952 Record.clear();
953
Chris Lattner850eabd2009-04-10 18:08:30 +0000954 // Emit the tokens array.
955 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
956 // Note that we know that the preprocessor does not have any annotation
957 // tokens in it because they are created by the parser, and thus can't be
958 // in a macro definition.
959 const Token &Tok = MI->getReplacementToken(TokNo);
960
961 Record.push_back(Tok.getLocation().getRawEncoding());
962 Record.push_back(Tok.getLength());
963
Chris Lattner850eabd2009-04-10 18:08:30 +0000964 // FIXME: When reading literal tokens, reconstruct the literal pointer if
965 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000966 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000967
968 // FIXME: Should translate token kind to a stable encoding.
969 Record.push_back(Tok.getKind());
970 // FIXME: Should translate token flags to a stable encoding.
971 Record.push_back(Tok.getFlags());
972
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000973 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000974 Record.clear();
975 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000976 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000977 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000978 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000979}
980
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000981//===----------------------------------------------------------------------===//
982// Type Serialization
983//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000984
Douglas Gregorc34897d2009-04-09 22:27:44 +0000985/// \brief Write the representation of a type to the PCH stream.
986void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000987 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000988 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000989 ID = NextTypeID++;
990
991 // Record the offset for this type.
992 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000993 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000994 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
995 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000996 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000997 }
998
999 RecordData Record;
1000
1001 // Emit the type's representation.
1002 PCHTypeWriter W(*this, Record);
1003 switch (T->getTypeClass()) {
1004 // For all of the concrete, non-dependent types, call the
1005 // appropriate visitor function.
1006#define TYPE(Class, Base) \
1007 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1008#define ABSTRACT_TYPE(Class, Base)
1009#define DEPENDENT_TYPE(Class, Base)
1010#include "clang/AST/TypeNodes.def"
1011
1012 // For all of the dependent type nodes (which only occur in C++
1013 // templates), produce an error.
1014#define TYPE(Class, Base)
1015#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1016#include "clang/AST/TypeNodes.def"
1017 assert(false && "Cannot serialize dependent type nodes");
1018 break;
1019 }
1020
1021 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001022 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001023
1024 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001025 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001026}
1027
1028/// \brief Write a block containing all of the types.
1029void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001030 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001031 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001032
Douglas Gregore43f0972009-04-26 03:49:13 +00001033 // Emit all of the types that need to be emitted (so far).
1034 while (!TypesToEmit.empty()) {
1035 const Type *T = TypesToEmit.front();
1036 TypesToEmit.pop();
1037 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1038 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001039 }
1040
1041 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001042 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001043}
1044
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001045//===----------------------------------------------------------------------===//
1046// Declaration Serialization
1047//===----------------------------------------------------------------------===//
1048
Douglas Gregorc34897d2009-04-09 22:27:44 +00001049/// \brief Write the block containing all of the declaration IDs
1050/// lexically declared within the given DeclContext.
1051///
1052/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1053/// bistream, or 0 if no block was written.
1054uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1055 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001056 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001057 return 0;
1058
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001059 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001060 RecordData Record;
1061 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1062 DEnd = DC->decls_end(Context);
1063 D != DEnd; ++D)
1064 AddDeclRef(*D, Record);
1065
Douglas Gregoraf136d92009-04-22 22:34:57 +00001066 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001067 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001068 return Offset;
1069}
1070
1071/// \brief Write the block containing all of the declaration IDs
1072/// visible from the given DeclContext.
1073///
1074/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1075/// bistream, or 0 if no block was written.
1076uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1077 DeclContext *DC) {
1078 if (DC->getPrimaryContext() != DC)
1079 return 0;
1080
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001081 // Since there is no name lookup into functions or methods, and we
1082 // perform name lookup for the translation unit via the
1083 // IdentifierInfo chains, don't bother to build a
1084 // visible-declarations table for these entities.
1085 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001086 return 0;
1087
Douglas Gregorc34897d2009-04-09 22:27:44 +00001088 // Force the DeclContext to build a its name-lookup table.
1089 DC->lookup(Context, DeclarationName());
1090
1091 // Serialize the contents of the mapping used for lookup. Note that,
1092 // although we have two very different code paths, the serialized
1093 // representation is the same for both cases: a declaration name,
1094 // followed by a size, followed by references to the visible
1095 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001096 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001097 RecordData Record;
1098 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001099 if (!Map)
1100 return 0;
1101
Douglas Gregorc34897d2009-04-09 22:27:44 +00001102 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1103 D != DEnd; ++D) {
1104 AddDeclarationName(D->first, Record);
1105 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1106 Record.push_back(Result.second - Result.first);
1107 for(; Result.first != Result.second; ++Result.first)
1108 AddDeclRef(*Result.first, Record);
1109 }
1110
1111 if (Record.size() == 0)
1112 return 0;
1113
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001114 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001115 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001116 return Offset;
1117}
1118
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001119//===----------------------------------------------------------------------===//
1120// Global Method Pool and Selector Serialization
1121//===----------------------------------------------------------------------===//
1122
Douglas Gregorff9a6092009-04-20 20:36:09 +00001123namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001124// Trait used for the on-disk hash table used in the method pool.
1125class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1126 PCHWriter &Writer;
1127
1128public:
1129 typedef Selector key_type;
1130 typedef key_type key_type_ref;
1131
1132 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1133 typedef const data_type& data_type_ref;
1134
1135 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1136
1137 static unsigned ComputeHash(Selector Sel) {
1138 unsigned N = Sel.getNumArgs();
1139 if (N == 0)
1140 ++N;
1141 unsigned R = 5381;
1142 for (unsigned I = 0; I != N; ++I)
1143 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1144 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1145 return R;
1146 }
1147
1148 std::pair<unsigned,unsigned>
1149 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1150 data_type_ref Methods) {
1151 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1152 clang::io::Emit16(Out, KeyLen);
1153 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1154 for (const ObjCMethodList *Method = &Methods.first; Method;
1155 Method = Method->Next)
1156 if (Method->Method)
1157 DataLen += 4;
1158 for (const ObjCMethodList *Method = &Methods.second; Method;
1159 Method = Method->Next)
1160 if (Method->Method)
1161 DataLen += 4;
1162 clang::io::Emit16(Out, DataLen);
1163 return std::make_pair(KeyLen, DataLen);
1164 }
1165
Douglas Gregor2d711832009-04-25 17:48:32 +00001166 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1167 uint64_t Start = Out.tell();
1168 assert((Start >> 32) == 0 && "Selector key offset too large");
1169 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001170 unsigned N = Sel.getNumArgs();
1171 clang::io::Emit16(Out, N);
1172 if (N == 0)
1173 N = 1;
1174 for (unsigned I = 0; I != N; ++I)
1175 clang::io::Emit32(Out,
1176 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1177 }
1178
1179 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001180 data_type_ref Methods, unsigned DataLen) {
1181 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001182 unsigned NumInstanceMethods = 0;
1183 for (const ObjCMethodList *Method = &Methods.first; Method;
1184 Method = Method->Next)
1185 if (Method->Method)
1186 ++NumInstanceMethods;
1187
1188 unsigned NumFactoryMethods = 0;
1189 for (const ObjCMethodList *Method = &Methods.second; Method;
1190 Method = Method->Next)
1191 if (Method->Method)
1192 ++NumFactoryMethods;
1193
1194 clang::io::Emit16(Out, NumInstanceMethods);
1195 clang::io::Emit16(Out, NumFactoryMethods);
1196 for (const ObjCMethodList *Method = &Methods.first; Method;
1197 Method = Method->Next)
1198 if (Method->Method)
1199 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001200 for (const ObjCMethodList *Method = &Methods.second; Method;
1201 Method = Method->Next)
1202 if (Method->Method)
1203 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001204
1205 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001206 }
1207};
1208} // end anonymous namespace
1209
1210/// \brief Write the method pool into the PCH file.
1211///
1212/// The method pool contains both instance and factory methods, stored
1213/// in an on-disk hash table indexed by the selector.
1214void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1215 using namespace llvm;
1216
1217 // Create and write out the blob that contains the instance and
1218 // factor method pools.
1219 bool Empty = true;
1220 {
1221 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1222
1223 // Create the on-disk hash table representation. Start by
1224 // iterating through the instance method pool.
1225 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001226 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001227 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1228 Instance = SemaRef.InstanceMethodPool.begin(),
1229 InstanceEnd = SemaRef.InstanceMethodPool.end();
1230 Instance != InstanceEnd; ++Instance) {
1231 // Check whether there is a factory method with the same
1232 // selector.
1233 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1234 = SemaRef.FactoryMethodPool.find(Instance->first);
1235
1236 if (Factory == SemaRef.FactoryMethodPool.end())
1237 Generator.insert(Instance->first,
1238 std::make_pair(Instance->second,
1239 ObjCMethodList()));
1240 else
1241 Generator.insert(Instance->first,
1242 std::make_pair(Instance->second, Factory->second));
1243
Douglas Gregor2d711832009-04-25 17:48:32 +00001244 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001245 Empty = false;
1246 }
1247
1248 // Now iterate through the factory method pool, to pick up any
1249 // selectors that weren't already in the instance method pool.
1250 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1251 Factory = SemaRef.FactoryMethodPool.begin(),
1252 FactoryEnd = SemaRef.FactoryMethodPool.end();
1253 Factory != FactoryEnd; ++Factory) {
1254 // Check whether there is an instance method with the same
1255 // selector. If so, there is no work to do here.
1256 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1257 = SemaRef.InstanceMethodPool.find(Factory->first);
1258
Douglas Gregor2d711832009-04-25 17:48:32 +00001259 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001260 Generator.insert(Factory->first,
1261 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001262 ++NumSelectorsInMethodPool;
1263 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001264
1265 Empty = false;
1266 }
1267
Douglas Gregor2d711832009-04-25 17:48:32 +00001268 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001269 return;
1270
1271 // Create the on-disk hash table in a buffer.
1272 llvm::SmallVector<char, 4096> MethodPool;
1273 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001274 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001275 {
1276 PCHMethodPoolTrait Trait(*this);
1277 llvm::raw_svector_ostream Out(MethodPool);
1278 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001279 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001280 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001281
1282 // For every selector that we have seen but which was not
1283 // written into the hash table, write the selector itself and
1284 // record it's offset.
1285 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1286 if (SelectorOffsets[I] == 0)
1287 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001288 }
1289
1290 // Create a blob abbreviation
1291 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1292 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1293 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001294 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001295 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1296 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1297
Douglas Gregor2d711832009-04-25 17:48:32 +00001298 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001299 RecordData Record;
1300 Record.push_back(pch::METHOD_POOL);
1301 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001302 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001303 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1304 &MethodPool.front(),
1305 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001306
1307 // Create a blob abbreviation for the selector table offsets.
1308 Abbrev = new BitCodeAbbrev();
1309 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1310 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1311 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1312 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1313
1314 // Write the selector offsets table.
1315 Record.clear();
1316 Record.push_back(pch::SELECTOR_OFFSETS);
1317 Record.push_back(SelectorOffsets.size());
1318 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1319 (const char *)&SelectorOffsets.front(),
1320 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001321 }
1322}
1323
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001324//===----------------------------------------------------------------------===//
1325// Identifier Table Serialization
1326//===----------------------------------------------------------------------===//
1327
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001328namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001329class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1330 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001331 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001332
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001333 /// \brief Determines whether this is an "interesting" identifier
1334 /// that needs a full IdentifierInfo structure written into the hash
1335 /// table.
1336 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1337 return II->isPoisoned() ||
1338 II->isExtensionToken() ||
1339 II->hasMacroDefinition() ||
1340 II->getObjCOrBuiltinID() ||
1341 II->getFETokenInfo<void>();
1342 }
1343
Douglas Gregorff9a6092009-04-20 20:36:09 +00001344public:
1345 typedef const IdentifierInfo* key_type;
1346 typedef key_type key_type_ref;
1347
1348 typedef pch::IdentID data_type;
1349 typedef data_type data_type_ref;
1350
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001351 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1352 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001353
1354 static unsigned ComputeHash(const IdentifierInfo* II) {
1355 return clang::BernsteinHash(II->getName());
1356 }
1357
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001358 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001359 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1360 pch::IdentID ID) {
1361 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001362 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1363 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001364 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001365 if (II->hasMacroDefinition() &&
1366 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001367 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001368 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1369 DEnd = IdentifierResolver::end();
1370 D != DEnd; ++D)
1371 DataLen += sizeof(pch::DeclID);
1372 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001373 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001374 // We emit the key length after the data length so that every
1375 // string is preceded by a 16-bit length. This matches the PTH
1376 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001377 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001378 return std::make_pair(KeyLen, DataLen);
1379 }
1380
1381 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1382 unsigned KeyLen) {
1383 // Record the location of the key data. This is used when generating
1384 // the mapping from persistent IDs to strings.
1385 Writer.SetIdentifierOffset(II, Out.tell());
1386 Out.write(II->getName(), KeyLen);
1387 }
1388
1389 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1390 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001391 if (!isInterestingIdentifier(II)) {
1392 clang::io::Emit32(Out, ID << 1);
1393 return;
1394 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001395
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001396 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001397 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001398 bool hasMacroDefinition =
1399 II->hasMacroDefinition() &&
1400 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001401 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001402 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001403 Bits = (Bits << 1) | II->isExtensionToken();
1404 Bits = (Bits << 1) | II->isPoisoned();
1405 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001406 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001407
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001408 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001409 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001410
Douglas Gregorc713da92009-04-21 22:25:48 +00001411 // Emit the declaration IDs in reverse order, because the
1412 // IdentifierResolver provides the declarations as they would be
1413 // visible (e.g., the function "stat" would come before the struct
1414 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1415 // adds declarations to the end of the list (so we need to see the
1416 // struct "status" before the function "status").
1417 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1418 IdentifierResolver::end());
1419 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1420 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001421 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001422 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001423 }
1424};
1425} // end anonymous namespace
1426
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001427/// \brief Write the identifier table into the PCH file.
1428///
1429/// The identifier table consists of a blob containing string data
1430/// (the actual identifiers themselves) and a separate "offsets" index
1431/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001432void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001433 using namespace llvm;
1434
1435 // Create and write out the blob that contains the identifier
1436 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001437 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001438 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1439
Douglas Gregor91137812009-04-28 20:33:11 +00001440 // Look for any identifiers that were named while processing the
1441 // headers, but are otherwise not needed. We add these to the hash
1442 // table to enable checking of the predefines buffer in the case
1443 // where the user adds new macro definitions when building the PCH
1444 // file.
1445 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1446 IDEnd = PP.getIdentifierTable().end();
1447 ID != IDEnd; ++ID)
1448 getIdentifierRef(ID->second);
1449
Douglas Gregorff9a6092009-04-20 20:36:09 +00001450 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001451 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001452 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1453 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1454 ID != IDEnd; ++ID) {
1455 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001456 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001457 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001458
Douglas Gregorff9a6092009-04-20 20:36:09 +00001459 // Create the on-disk hash table in a buffer.
1460 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001461 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001462 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001463 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001464 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001465 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001466 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001467 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001468 }
1469
1470 // Create a blob abbreviation
1471 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1472 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001473 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001474 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001475 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001476
1477 // Write the identifier table
1478 RecordData Record;
1479 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001480 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001481 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1482 &IdentifierTable.front(),
1483 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001484 }
1485
1486 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001487 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1488 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1490 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1491 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1492
1493 RecordData Record;
1494 Record.push_back(pch::IDENTIFIER_OFFSET);
1495 Record.push_back(IdentifierOffsets.size());
1496 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1497 (const char *)&IdentifierOffsets.front(),
1498 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001499}
1500
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001501//===----------------------------------------------------------------------===//
1502// General Serialization Routines
1503//===----------------------------------------------------------------------===//
1504
Douglas Gregor1c507882009-04-15 21:30:51 +00001505/// \brief Write a record containing the given attributes.
1506void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1507 RecordData Record;
1508 for (; Attr; Attr = Attr->getNext()) {
1509 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1510 Record.push_back(Attr->isInherited());
1511 switch (Attr->getKind()) {
1512 case Attr::Alias:
1513 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1514 break;
1515
1516 case Attr::Aligned:
1517 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1518 break;
1519
1520 case Attr::AlwaysInline:
1521 break;
1522
1523 case Attr::AnalyzerNoReturn:
1524 break;
1525
1526 case Attr::Annotate:
1527 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1528 break;
1529
1530 case Attr::AsmLabel:
1531 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1532 break;
1533
1534 case Attr::Blocks:
1535 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1536 break;
1537
1538 case Attr::Cleanup:
1539 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1540 break;
1541
1542 case Attr::Const:
1543 break;
1544
1545 case Attr::Constructor:
1546 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1547 break;
1548
1549 case Attr::DLLExport:
1550 case Attr::DLLImport:
1551 case Attr::Deprecated:
1552 break;
1553
1554 case Attr::Destructor:
1555 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1556 break;
1557
1558 case Attr::FastCall:
1559 break;
1560
1561 case Attr::Format: {
1562 const FormatAttr *Format = cast<FormatAttr>(Attr);
1563 AddString(Format->getType(), Record);
1564 Record.push_back(Format->getFormatIdx());
1565 Record.push_back(Format->getFirstArg());
1566 break;
1567 }
1568
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001569 case Attr::FormatArg: {
1570 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1571 Record.push_back(Format->getFormatIdx());
1572 break;
1573 }
1574
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001575 case Attr::Sentinel : {
1576 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1577 Record.push_back(Sentinel->getSentinel());
1578 Record.push_back(Sentinel->getNullPos());
1579 break;
1580 }
1581
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001582 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001583 case Attr::IBOutletKind:
1584 case Attr::NoReturn:
1585 case Attr::NoThrow:
1586 case Attr::Nodebug:
1587 case Attr::Noinline:
1588 break;
1589
1590 case Attr::NonNull: {
1591 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1592 Record.push_back(NonNull->size());
1593 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1594 break;
1595 }
1596
1597 case Attr::ObjCException:
1598 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001599 case Attr::CFReturnsRetained:
1600 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001601 case Attr::Overloadable:
1602 break;
1603
1604 case Attr::Packed:
1605 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1606 break;
1607
1608 case Attr::Pure:
1609 break;
1610
1611 case Attr::Regparm:
1612 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1613 break;
1614
1615 case Attr::Section:
1616 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1617 break;
1618
1619 case Attr::StdCall:
1620 case Attr::TransparentUnion:
1621 case Attr::Unavailable:
1622 case Attr::Unused:
1623 case Attr::Used:
1624 break;
1625
1626 case Attr::Visibility:
1627 // FIXME: stable encoding
1628 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1629 break;
1630
1631 case Attr::WarnUnusedResult:
1632 case Attr::Weak:
1633 case Attr::WeakImport:
1634 break;
1635 }
1636 }
1637
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001638 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001639}
1640
1641void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1642 Record.push_back(Str.size());
1643 Record.insert(Record.end(), Str.begin(), Str.end());
1644}
1645
Douglas Gregorff9a6092009-04-20 20:36:09 +00001646/// \brief Note that the identifier II occurs at the given offset
1647/// within the identifier table.
1648void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001649 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001650}
1651
Douglas Gregor2d711832009-04-25 17:48:32 +00001652/// \brief Note that the selector Sel occurs at the given offset
1653/// within the method pool/selector table.
1654void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1655 unsigned ID = SelectorIDs[Sel];
1656 assert(ID && "Unknown selector");
1657 SelectorOffsets[ID - 1] = Offset;
1658}
1659
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001660PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001661 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001662 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1663 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001664
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001665void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001666 using namespace llvm;
1667
Douglas Gregor87887da2009-04-20 15:53:59 +00001668 ASTContext &Context = SemaRef.Context;
1669 Preprocessor &PP = SemaRef.PP;
1670
Douglas Gregorc34897d2009-04-09 22:27:44 +00001671 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001672 Stream.Emit((unsigned)'C', 8);
1673 Stream.Emit((unsigned)'P', 8);
1674 Stream.Emit((unsigned)'C', 8);
1675 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001676
1677 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001678
1679 // The translation unit is the first declaration we'll emit.
1680 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1681 DeclsToEmit.push(Context.getTranslationUnitDecl());
1682
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001683 // Make sure that we emit IdentifierInfos (and any attached
1684 // declarations) for builtins.
1685 {
1686 IdentifierTable &Table = PP.getIdentifierTable();
1687 llvm::SmallVector<const char *, 32> BuiltinNames;
1688 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1689 Context.getLangOptions().NoBuiltin);
1690 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1691 getIdentifierRef(&Table.get(BuiltinNames[I]));
1692 }
1693
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001694 // Build a record containing all of the tentative definitions in
1695 // this header file. Generally, this record will be empty.
1696 RecordData TentativeDefinitions;
1697 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1698 TD = SemaRef.TentativeDefinitions.begin(),
1699 TDEnd = SemaRef.TentativeDefinitions.end();
1700 TD != TDEnd; ++TD)
1701 AddDeclRef(TD->second, TentativeDefinitions);
1702
Douglas Gregor062d9482009-04-22 22:18:58 +00001703 // Build a record containing all of the locally-scoped external
1704 // declarations in this header file. Generally, this record will be
1705 // empty.
1706 RecordData LocallyScopedExternalDecls;
1707 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1708 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1709 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1710 TD != TDEnd; ++TD)
1711 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1712
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001713 // Build a record containing all of the ext_vector declarations.
1714 RecordData ExtVectorDecls;
1715 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1716 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1717
1718 // Build a record containing all of the Objective-C category
1719 // implementations.
1720 RecordData ObjCCategoryImpls;
1721 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1722 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1723
Douglas Gregorc34897d2009-04-09 22:27:44 +00001724 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001725 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001726 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001727 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001728 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001729 if (StatCalls)
1730 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001731 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001732 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001733
1734 // Keep writing types and declarations until all types and
1735 // declarations have been written.
1736 do {
1737 if (!DeclsToEmit.empty())
1738 WriteDeclsBlock(Context);
1739 if (!TypesToEmit.empty())
1740 WriteTypesBlock(Context);
1741 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1742
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001743 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001744 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001745
1746 // Write the type offsets array
1747 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1748 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1751 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1752 Record.clear();
1753 Record.push_back(pch::TYPE_OFFSET);
1754 Record.push_back(TypeOffsets.size());
1755 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1756 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001757 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001758
1759 // Write the declaration offsets array
1760 Abbrev = new BitCodeAbbrev();
1761 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1764 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1765 Record.clear();
1766 Record.push_back(pch::DECL_OFFSET);
1767 Record.push_back(DeclOffsets.size());
1768 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1769 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001770 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001771
1772 // Write the record of special types.
1773 Record.clear();
1774 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001775 AddTypeRef(Context.getObjCIdType(), Record);
1776 AddTypeRef(Context.getObjCSelType(), Record);
1777 AddTypeRef(Context.getObjCProtoType(), Record);
1778 AddTypeRef(Context.getObjCClassType(), Record);
1779 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1780 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001781 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1782
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001783 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001784 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001785 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001786
1787 // Write the record containing tentative definitions.
1788 if (!TentativeDefinitions.empty())
1789 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001790
1791 // Write the record containing locally-scoped external definitions.
1792 if (!LocallyScopedExternalDecls.empty())
1793 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1794 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001795
1796 // Write the record containing ext_vector type names.
1797 if (!ExtVectorDecls.empty())
1798 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1799
1800 // Write the record containing Objective-C category implementations.
1801 if (!ObjCCategoryImpls.empty())
1802 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001803
1804 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001805 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001806 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001807 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001808 Record.push_back(NumLexicalDeclContexts);
1809 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001810 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001811 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001812}
1813
1814void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1815 Record.push_back(Loc.getRawEncoding());
1816}
1817
1818void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1819 Record.push_back(Value.getBitWidth());
1820 unsigned N = Value.getNumWords();
1821 const uint64_t* Words = Value.getRawData();
1822 for (unsigned I = 0; I != N; ++I)
1823 Record.push_back(Words[I]);
1824}
1825
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001826void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1827 Record.push_back(Value.isUnsigned());
1828 AddAPInt(Value, Record);
1829}
1830
Douglas Gregore2f37202009-04-14 21:55:33 +00001831void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1832 AddAPInt(Value.bitcastToAPInt(), Record);
1833}
1834
Douglas Gregorc34897d2009-04-09 22:27:44 +00001835void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001836 Record.push_back(getIdentifierRef(II));
1837}
1838
1839pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1840 if (II == 0)
1841 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001842
1843 pch::IdentID &ID = IdentifierIDs[II];
1844 if (ID == 0)
1845 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001846 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001847}
1848
Steve Naroff9e84d782009-04-23 10:39:46 +00001849void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1850 if (SelRef.getAsOpaquePtr() == 0) {
1851 Record.push_back(0);
1852 return;
1853 }
1854
1855 pch::SelectorID &SID = SelectorIDs[SelRef];
1856 if (SID == 0) {
1857 SID = SelectorIDs.size();
1858 SelVector.push_back(SelRef);
1859 }
1860 Record.push_back(SID);
1861}
1862
Douglas Gregorc34897d2009-04-09 22:27:44 +00001863void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1864 if (T.isNull()) {
1865 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1866 return;
1867 }
1868
1869 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001870 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001871 switch (BT->getKind()) {
1872 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1873 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1874 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1875 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1876 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1877 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1878 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1879 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001880 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001881 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1882 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1883 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1884 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1885 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1886 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1887 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001888 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001889 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1890 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1891 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001892 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001893 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1894 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1895 }
1896
1897 Record.push_back((ID << 3) | T.getCVRQualifiers());
1898 return;
1899 }
1900
Douglas Gregorac8f2802009-04-10 17:25:41 +00001901 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001902 if (ID == 0) {
1903 // We haven't seen this type before. Assign it a new ID and put it
1904 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001905 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001906 TypesToEmit.push(T.getTypePtr());
1907 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001908
1909 // Encode the type qualifiers in the type reference.
1910 Record.push_back((ID << 3) | T.getCVRQualifiers());
1911}
1912
1913void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1914 if (D == 0) {
1915 Record.push_back(0);
1916 return;
1917 }
1918
Douglas Gregorac8f2802009-04-10 17:25:41 +00001919 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001920 if (ID == 0) {
1921 // We haven't seen this declaration before. Give it a new ID and
1922 // enqueue it in the list of declarations to emit.
1923 ID = DeclIDs.size();
1924 DeclsToEmit.push(const_cast<Decl *>(D));
1925 }
1926
1927 Record.push_back(ID);
1928}
1929
Douglas Gregorff9a6092009-04-20 20:36:09 +00001930pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1931 if (D == 0)
1932 return 0;
1933
1934 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1935 return DeclIDs[D];
1936}
1937
Douglas Gregorc34897d2009-04-09 22:27:44 +00001938void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001939 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001940 Record.push_back(Name.getNameKind());
1941 switch (Name.getNameKind()) {
1942 case DeclarationName::Identifier:
1943 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1944 break;
1945
1946 case DeclarationName::ObjCZeroArgSelector:
1947 case DeclarationName::ObjCOneArgSelector:
1948 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001949 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001950 break;
1951
1952 case DeclarationName::CXXConstructorName:
1953 case DeclarationName::CXXDestructorName:
1954 case DeclarationName::CXXConversionFunctionName:
1955 AddTypeRef(Name.getCXXNameType(), Record);
1956 break;
1957
1958 case DeclarationName::CXXOperatorName:
1959 Record.push_back(Name.getCXXOverloadedOperator());
1960 break;
1961
1962 case DeclarationName::CXXUsingDirective:
1963 // No extra data to emit
1964 break;
1965 }
1966}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001967