blob: 9f9b3b4e09c6be70459897f55b26d12157074476 [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);
Chris Lattner920673a2009-04-26 22:26:21 +0000350 RECORD(TYPE_OFFSET);
351 RECORD(DECL_OFFSET);
352 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000353 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000354 RECORD(IDENTIFIER_OFFSET);
355 RECORD(IDENTIFIER_TABLE);
356 RECORD(EXTERNAL_DEFINITIONS);
357 RECORD(SPECIAL_TYPES);
358 RECORD(STATISTICS);
359 RECORD(TENTATIVE_DEFINITIONS);
360 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
361 RECORD(SELECTOR_OFFSETS);
362 RECORD(METHOD_POOL);
363 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000364 RECORD(SOURCE_LOCATION_OFFSETS);
365 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000366 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000367 RECORD(EXT_VECTOR_DECLS);
368 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000369
Chris Lattner920673a2009-04-26 22:26:21 +0000370 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000371 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000372 RECORD(SM_SLOC_FILE_ENTRY);
373 RECORD(SM_SLOC_BUFFER_ENTRY);
374 RECORD(SM_SLOC_BUFFER_BLOB);
375 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
376 RECORD(SM_LINE_TABLE);
377 RECORD(SM_HEADER_FILE_INFO);
378
379 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000380 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000381 RECORD(PP_MACRO_OBJECT_LIKE);
382 RECORD(PP_MACRO_FUNCTION_LIKE);
383 RECORD(PP_TOKEN);
384
385 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000386 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000387 RECORD(TYPE_EXT_QUAL);
388 RECORD(TYPE_FIXED_WIDTH_INT);
389 RECORD(TYPE_COMPLEX);
390 RECORD(TYPE_POINTER);
391 RECORD(TYPE_BLOCK_POINTER);
392 RECORD(TYPE_LVALUE_REFERENCE);
393 RECORD(TYPE_RVALUE_REFERENCE);
394 RECORD(TYPE_MEMBER_POINTER);
395 RECORD(TYPE_CONSTANT_ARRAY);
396 RECORD(TYPE_INCOMPLETE_ARRAY);
397 RECORD(TYPE_VARIABLE_ARRAY);
398 RECORD(TYPE_VECTOR);
399 RECORD(TYPE_EXT_VECTOR);
400 RECORD(TYPE_FUNCTION_PROTO);
401 RECORD(TYPE_FUNCTION_NO_PROTO);
402 RECORD(TYPE_TYPEDEF);
403 RECORD(TYPE_TYPEOF_EXPR);
404 RECORD(TYPE_TYPEOF);
405 RECORD(TYPE_RECORD);
406 RECORD(TYPE_ENUM);
407 RECORD(TYPE_OBJC_INTERFACE);
408 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
409 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000410 // Statements and Exprs can occur in the Types block.
411 AddStmtsExprs(Stream, Record);
412
Chris Lattner920673a2009-04-26 22:26:21 +0000413 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000414 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000415 RECORD(DECL_ATTR);
416 RECORD(DECL_TRANSLATION_UNIT);
417 RECORD(DECL_TYPEDEF);
418 RECORD(DECL_ENUM);
419 RECORD(DECL_RECORD);
420 RECORD(DECL_ENUM_CONSTANT);
421 RECORD(DECL_FUNCTION);
422 RECORD(DECL_OBJC_METHOD);
423 RECORD(DECL_OBJC_INTERFACE);
424 RECORD(DECL_OBJC_PROTOCOL);
425 RECORD(DECL_OBJC_IVAR);
426 RECORD(DECL_OBJC_AT_DEFS_FIELD);
427 RECORD(DECL_OBJC_CLASS);
428 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
429 RECORD(DECL_OBJC_CATEGORY);
430 RECORD(DECL_OBJC_CATEGORY_IMPL);
431 RECORD(DECL_OBJC_IMPLEMENTATION);
432 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
433 RECORD(DECL_OBJC_PROPERTY);
434 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000435 RECORD(DECL_FIELD);
436 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000437 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000438 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000439 RECORD(DECL_ORIGINAL_PARM_VAR);
440 RECORD(DECL_FILE_SCOPE_ASM);
441 RECORD(DECL_BLOCK);
442 RECORD(DECL_CONTEXT_LEXICAL);
443 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000444 // Statements and Exprs can occur in the Decls block.
445 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000446#undef RECORD
447#undef BLOCK
448 Stream.ExitBlock();
449}
450
451
Douglas Gregorb7064742009-04-27 22:23:34 +0000452/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000453void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000454 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000455
456 // Original file name
457 SourceManager &SM = Context.getSourceManager();
458 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
459 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
460 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
461 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
462 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
463
464 llvm::sys::Path MainFilePath(MainFile->getName());
465 std::string MainFileName;
466
467 if (!MainFilePath.isAbsolute()) {
468 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
469 P.appendComponent(MainFilePath.toString());
470 MainFileName = P.toString();
471 } else {
472 MainFileName = MainFilePath.toString();
473 }
474
475 RecordData Record;
476 Record.push_back(pch::ORIGINAL_FILE_NAME);
477 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
478 MainFileName.size());
479 }
480
481 // Metadata
482 const TargetInfo &Target = Context.Target;
483 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
484 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
485 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
486 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
487 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
488 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
489 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
490 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000491
492 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000493 Record.push_back(pch::METADATA);
494 Record.push_back(pch::VERSION_MAJOR);
495 Record.push_back(pch::VERSION_MINOR);
496 Record.push_back(CLANG_VERSION_MAJOR);
497 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000498 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000499 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000500}
501
502/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000503void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
504 RecordData Record;
505 Record.push_back(LangOpts.Trigraphs);
506 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
507 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
508 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
509 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
510 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
511 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
512 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
513 Record.push_back(LangOpts.C99); // C99 Support
514 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
515 Record.push_back(LangOpts.CPlusPlus); // C++ Support
516 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000517 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
518
519 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
520 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
521 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
522
523 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000524 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
525 Record.push_back(LangOpts.LaxVectorConversions);
526 Record.push_back(LangOpts.Exceptions); // Support exception handling.
527
528 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
529 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
530 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
531
Chris Lattnercd4da472009-04-27 07:35:58 +0000532 // Whether static initializers are protected by locks.
533 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000534 Record.push_back(LangOpts.Blocks); // block extension to C
535 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
536 // they are unused.
537 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
538 // (modulo the platform support).
539
540 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
541 // signed integer arithmetic overflows.
542
543 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
544 // may be ripped out at any time.
545
546 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
547 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
548 // defined.
549 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
550 // opposed to __DYNAMIC__).
551 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
552
553 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
554 // used (instead of C99 semantics).
555 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000556 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
557 // be enabled.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000558 Record.push_back(LangOpts.getGCMode());
559 Record.push_back(LangOpts.getVisibilityMode());
560 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000561 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000562}
563
Douglas Gregorab1cef72009-04-10 03:52:48 +0000564//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000565// stat cache Serialization
566//===----------------------------------------------------------------------===//
567
568namespace {
569// Trait used for the on-disk hash table of stat cache results.
570class VISIBILITY_HIDDEN PCHStatCacheTrait {
571public:
572 typedef const char * key_type;
573 typedef key_type key_type_ref;
574
575 typedef std::pair<int, struct stat> data_type;
576 typedef const data_type& data_type_ref;
577
578 static unsigned ComputeHash(const char *path) {
579 return BernsteinHash(path);
580 }
581
582 std::pair<unsigned,unsigned>
583 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
584 data_type_ref Data) {
585 unsigned StrLen = strlen(path);
586 clang::io::Emit16(Out, StrLen);
587 unsigned DataLen = 1; // result value
588 if (Data.first == 0)
589 DataLen += 4 + 4 + 2 + 8 + 8;
590 clang::io::Emit8(Out, DataLen);
591 return std::make_pair(StrLen + 1, DataLen);
592 }
593
594 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
595 Out.write(path, KeyLen);
596 }
597
598 void EmitData(llvm::raw_ostream& Out, key_type_ref,
599 data_type_ref Data, unsigned DataLen) {
600 using namespace clang::io;
601 uint64_t Start = Out.tell(); (void)Start;
602
603 // Result of stat()
604 Emit8(Out, Data.first? 1 : 0);
605
606 if (Data.first == 0) {
607 Emit32(Out, (uint32_t) Data.second.st_ino);
608 Emit32(Out, (uint32_t) Data.second.st_dev);
609 Emit16(Out, (uint16_t) Data.second.st_mode);
610 Emit64(Out, (uint64_t) Data.second.st_mtime);
611 Emit64(Out, (uint64_t) Data.second.st_size);
612 }
613
614 assert(Out.tell() - Start == DataLen && "Wrong data length");
615 }
616};
617} // end anonymous namespace
618
619/// \brief Write the stat() system call cache to the PCH file.
620void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
621 // Build the on-disk hash table containing information about every
622 // stat() call.
623 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
624 unsigned NumStatEntries = 0;
625 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
626 StatEnd = StatCalls.end();
627 Stat != StatEnd; ++Stat, ++NumStatEntries)
628 Generator.insert(Stat->first(), Stat->second);
629
630 // Create the on-disk hash table in a buffer.
631 llvm::SmallVector<char, 4096> StatCacheData;
632 uint32_t BucketOffset;
633 {
634 llvm::raw_svector_ostream Out(StatCacheData);
635 // Make sure that no bucket is at offset 0
636 clang::io::Emit32(Out, 0);
637 BucketOffset = Generator.Emit(Out);
638 }
639
640 // Create a blob abbreviation
641 using namespace llvm;
642 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
643 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
644 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
645 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
647 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
648
649 // Write the stat cache
650 RecordData Record;
651 Record.push_back(pch::STAT_CACHE);
652 Record.push_back(BucketOffset);
653 Record.push_back(NumStatEntries);
654 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
655 &StatCacheData.front(),
656 StatCacheData.size());
657}
658
659//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000660// Source Manager Serialization
661//===----------------------------------------------------------------------===//
662
663/// \brief Create an abbreviation for the SLocEntry that refers to a
664/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000665static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000666 using namespace llvm;
667 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
668 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
671 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000674 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000675}
676
677/// \brief Create an abbreviation for the SLocEntry that refers to a
678/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000679static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000680 using namespace llvm;
681 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
682 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000688 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000689}
690
691/// \brief Create an abbreviation for the SLocEntry that refers to a
692/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000693static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000694 using namespace llvm;
695 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
696 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000698 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000699}
700
701/// \brief Create an abbreviation for the SLocEntry that refers to an
702/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000703static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000704 using namespace llvm;
705 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
706 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
707 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
708 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000712 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000713}
714
715/// \brief Writes the block containing the serialized form of the
716/// source manager.
717///
718/// TODO: We should probably use an on-disk hash table (stored in a
719/// blob), indexed based on the file name, so that we only create
720/// entries for files that we actually need. In the common case (no
721/// errors), we probably won't have to create file entries for any of
722/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000723void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
724 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000725 RecordData Record;
726
Chris Lattner84b04f12009-04-10 17:16:57 +0000727 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000728 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000729
730 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000731 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
732 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
733 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
734 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000735
Douglas Gregor635f97f2009-04-13 16:31:14 +0000736 // Write the line table.
737 if (SourceMgr.hasLineTable()) {
738 LineTableInfo &LineTable = SourceMgr.getLineTable();
739
740 // Emit the file names
741 Record.push_back(LineTable.getNumFilenames());
742 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
743 // Emit the file name
744 const char *Filename = LineTable.getFilename(I);
745 unsigned FilenameLen = Filename? strlen(Filename) : 0;
746 Record.push_back(FilenameLen);
747 if (FilenameLen)
748 Record.insert(Record.end(), Filename, Filename + FilenameLen);
749 }
750
751 // Emit the line entries
752 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
753 L != LEnd; ++L) {
754 // Emit the file ID
755 Record.push_back(L->first);
756
757 // Emit the line entries
758 Record.push_back(L->second.size());
759 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
760 LEEnd = L->second.end();
761 LE != LEEnd; ++LE) {
762 Record.push_back(LE->FileOffset);
763 Record.push_back(LE->LineNo);
764 Record.push_back(LE->FilenameID);
765 Record.push_back((unsigned)LE->FileKind);
766 Record.push_back(LE->IncludeOffset);
767 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000768 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000769 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000770 }
771
Douglas Gregor32e231c2009-04-27 06:38:32 +0000772 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000773 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000774 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000775 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
776 E = HS.header_file_end();
777 I != E; ++I) {
778 Record.push_back(I->isImport);
779 Record.push_back(I->DirInfo);
780 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000781 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000782 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
783 Record.clear();
784 }
785
Douglas Gregor32e231c2009-04-27 06:38:32 +0000786 // Write out the source location entry table. We skip the first
787 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000788 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000789 RecordData PreloadSLocs;
790 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
791 for (SourceManager::sloc_entry_iterator
792 SLoc = SourceMgr.sloc_entry_begin() + 1,
793 SLocEnd = SourceMgr.sloc_entry_end();
794 SLoc != SLocEnd; ++SLoc) {
795 // Record the offset of this source-location entry.
796 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
797
798 // Figure out which record code to use.
799 unsigned Code;
800 if (SLoc->isFile()) {
801 if (SLoc->getFile().getContentCache()->Entry)
802 Code = pch::SM_SLOC_FILE_ENTRY;
803 else
804 Code = pch::SM_SLOC_BUFFER_ENTRY;
805 } else
806 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
807 Record.clear();
808 Record.push_back(Code);
809
810 Record.push_back(SLoc->getOffset());
811 if (SLoc->isFile()) {
812 const SrcMgr::FileInfo &File = SLoc->getFile();
813 Record.push_back(File.getIncludeLoc().getRawEncoding());
814 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
815 Record.push_back(File.hasLineDirectives());
816
817 const SrcMgr::ContentCache *Content = File.getContentCache();
818 if (Content->Entry) {
819 // The source location entry is a file. The blob associated
820 // with this entry is the file name.
821 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
822 Content->Entry->getName(),
823 strlen(Content->Entry->getName()));
824
825 // FIXME: For now, preload all file source locations, so that
826 // we get the appropriate File entries in the reader. This is
827 // a temporary measure.
828 PreloadSLocs.push_back(SLocEntryOffsets.size());
829 } else {
830 // The source location entry is a buffer. The blob associated
831 // with this entry contains the contents of the buffer.
832
833 // We add one to the size so that we capture the trailing NULL
834 // that is required by llvm::MemoryBuffer::getMemBuffer (on
835 // the reader side).
836 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
837 const char *Name = Buffer->getBufferIdentifier();
838 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
839 Record.clear();
840 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
841 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
842 Buffer->getBufferStart(),
843 Buffer->getBufferSize() + 1);
844
845 if (strcmp(Name, "<built-in>") == 0)
846 PreloadSLocs.push_back(SLocEntryOffsets.size());
847 }
848 } else {
849 // The source location entry is an instantiation.
850 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
851 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
852 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
853 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
854
855 // Compute the token length for this macro expansion.
856 unsigned NextOffset = SourceMgr.getNextOffset();
857 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
858 if (++NextSLoc != SLocEnd)
859 NextOffset = NextSLoc->getOffset();
860 Record.push_back(NextOffset - SLoc->getOffset() - 1);
861 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
862 }
863 }
864
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000865 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000866
867 if (SLocEntryOffsets.empty())
868 return;
869
870 // Write the source-location offsets table into the PCH block. This
871 // table is used for lazily loading source-location information.
872 using namespace llvm;
873 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
874 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
878 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
879
880 Record.clear();
881 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
882 Record.push_back(SLocEntryOffsets.size());
883 Record.push_back(SourceMgr.getNextOffset());
884 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
885 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000886 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000887
888 // Write the source location entry preloads array, telling the PCH
889 // reader which source locations entries it should load eagerly.
890 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000891}
892
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000893//===----------------------------------------------------------------------===//
894// Preprocessor Serialization
895//===----------------------------------------------------------------------===//
896
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000897/// \brief Writes the block containing the serialized form of the
898/// preprocessor.
899///
Chris Lattner850eabd2009-04-10 18:08:30 +0000900void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000901 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000902
Chris Lattner4b21c202009-04-13 01:29:17 +0000903 // If the preprocessor __COUNTER__ value has been bumped, remember it.
904 if (PP.getCounterValue() != 0) {
905 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000906 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000907 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000908 }
909
910 // Enter the preprocessor block.
911 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000912
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000913 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
914 // FIXME: use diagnostics subsystem for localization etc.
915 if (PP.SawDateOrTime())
916 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
917
Chris Lattner1b094952009-04-10 18:00:12 +0000918 // Loop over all the macro definitions that are live at the end of the file,
919 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000920 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
921 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000922 // FIXME: This emits macros in hash table order, we should do it in a stable
923 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000924 MacroInfo *MI = I->second;
925
926 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
927 // been redefined by the header (in which case they are not isBuiltinMacro).
928 if (MI->isBuiltinMacro())
929 continue;
930
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000931 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000932 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000933 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000934 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
935 Record.push_back(MI->isUsed());
936
937 unsigned Code;
938 if (MI->isObjectLike()) {
939 Code = pch::PP_MACRO_OBJECT_LIKE;
940 } else {
941 Code = pch::PP_MACRO_FUNCTION_LIKE;
942
943 Record.push_back(MI->isC99Varargs());
944 Record.push_back(MI->isGNUVarargs());
945 Record.push_back(MI->getNumArgs());
946 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
947 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000948 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000949 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000950 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000951 Record.clear();
952
Chris Lattner850eabd2009-04-10 18:08:30 +0000953 // Emit the tokens array.
954 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
955 // Note that we know that the preprocessor does not have any annotation
956 // tokens in it because they are created by the parser, and thus can't be
957 // in a macro definition.
958 const Token &Tok = MI->getReplacementToken(TokNo);
959
960 Record.push_back(Tok.getLocation().getRawEncoding());
961 Record.push_back(Tok.getLength());
962
Chris Lattner850eabd2009-04-10 18:08:30 +0000963 // FIXME: When reading literal tokens, reconstruct the literal pointer if
964 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000965 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000966
967 // FIXME: Should translate token kind to a stable encoding.
968 Record.push_back(Tok.getKind());
969 // FIXME: Should translate token flags to a stable encoding.
970 Record.push_back(Tok.getFlags());
971
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000972 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000973 Record.clear();
974 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000975 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000976 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000977 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000978}
979
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000980//===----------------------------------------------------------------------===//
981// Type Serialization
982//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000983
Douglas Gregorc34897d2009-04-09 22:27:44 +0000984/// \brief Write the representation of a type to the PCH stream.
985void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000986 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000987 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000988 ID = NextTypeID++;
989
990 // Record the offset for this type.
991 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000992 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000993 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
994 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000995 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000996 }
997
998 RecordData Record;
999
1000 // Emit the type's representation.
1001 PCHTypeWriter W(*this, Record);
1002 switch (T->getTypeClass()) {
1003 // For all of the concrete, non-dependent types, call the
1004 // appropriate visitor function.
1005#define TYPE(Class, Base) \
1006 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1007#define ABSTRACT_TYPE(Class, Base)
1008#define DEPENDENT_TYPE(Class, Base)
1009#include "clang/AST/TypeNodes.def"
1010
1011 // For all of the dependent type nodes (which only occur in C++
1012 // templates), produce an error.
1013#define TYPE(Class, Base)
1014#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1015#include "clang/AST/TypeNodes.def"
1016 assert(false && "Cannot serialize dependent type nodes");
1017 break;
1018 }
1019
1020 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001021 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001022
1023 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001024 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001025}
1026
1027/// \brief Write a block containing all of the types.
1028void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001029 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001030 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001031
Douglas Gregore43f0972009-04-26 03:49:13 +00001032 // Emit all of the types that need to be emitted (so far).
1033 while (!TypesToEmit.empty()) {
1034 const Type *T = TypesToEmit.front();
1035 TypesToEmit.pop();
1036 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1037 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001038 }
1039
1040 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001041 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001042}
1043
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001044//===----------------------------------------------------------------------===//
1045// Declaration Serialization
1046//===----------------------------------------------------------------------===//
1047
Douglas Gregorc34897d2009-04-09 22:27:44 +00001048/// \brief Write the block containing all of the declaration IDs
1049/// lexically declared within the given DeclContext.
1050///
1051/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1052/// bistream, or 0 if no block was written.
1053uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1054 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001055 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001056 return 0;
1057
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001058 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001059 RecordData Record;
1060 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1061 DEnd = DC->decls_end(Context);
1062 D != DEnd; ++D)
1063 AddDeclRef(*D, Record);
1064
Douglas Gregoraf136d92009-04-22 22:34:57 +00001065 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001066 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001067 return Offset;
1068}
1069
1070/// \brief Write the block containing all of the declaration IDs
1071/// visible from the given DeclContext.
1072///
1073/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1074/// bistream, or 0 if no block was written.
1075uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1076 DeclContext *DC) {
1077 if (DC->getPrimaryContext() != DC)
1078 return 0;
1079
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001080 // Since there is no name lookup into functions or methods, and we
1081 // perform name lookup for the translation unit via the
1082 // IdentifierInfo chains, don't bother to build a
1083 // visible-declarations table for these entities.
1084 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001085 return 0;
1086
Douglas Gregorc34897d2009-04-09 22:27:44 +00001087 // Force the DeclContext to build a its name-lookup table.
1088 DC->lookup(Context, DeclarationName());
1089
1090 // Serialize the contents of the mapping used for lookup. Note that,
1091 // although we have two very different code paths, the serialized
1092 // representation is the same for both cases: a declaration name,
1093 // followed by a size, followed by references to the visible
1094 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001095 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001096 RecordData Record;
1097 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001098 if (!Map)
1099 return 0;
1100
Douglas Gregorc34897d2009-04-09 22:27:44 +00001101 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1102 D != DEnd; ++D) {
1103 AddDeclarationName(D->first, Record);
1104 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1105 Record.push_back(Result.second - Result.first);
1106 for(; Result.first != Result.second; ++Result.first)
1107 AddDeclRef(*Result.first, Record);
1108 }
1109
1110 if (Record.size() == 0)
1111 return 0;
1112
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001113 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001114 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001115 return Offset;
1116}
1117
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001118//===----------------------------------------------------------------------===//
1119// Global Method Pool and Selector Serialization
1120//===----------------------------------------------------------------------===//
1121
Douglas Gregorff9a6092009-04-20 20:36:09 +00001122namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001123// Trait used for the on-disk hash table used in the method pool.
1124class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1125 PCHWriter &Writer;
1126
1127public:
1128 typedef Selector key_type;
1129 typedef key_type key_type_ref;
1130
1131 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1132 typedef const data_type& data_type_ref;
1133
1134 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1135
1136 static unsigned ComputeHash(Selector Sel) {
1137 unsigned N = Sel.getNumArgs();
1138 if (N == 0)
1139 ++N;
1140 unsigned R = 5381;
1141 for (unsigned I = 0; I != N; ++I)
1142 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1143 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1144 return R;
1145 }
1146
1147 std::pair<unsigned,unsigned>
1148 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1149 data_type_ref Methods) {
1150 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1151 clang::io::Emit16(Out, KeyLen);
1152 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1153 for (const ObjCMethodList *Method = &Methods.first; Method;
1154 Method = Method->Next)
1155 if (Method->Method)
1156 DataLen += 4;
1157 for (const ObjCMethodList *Method = &Methods.second; Method;
1158 Method = Method->Next)
1159 if (Method->Method)
1160 DataLen += 4;
1161 clang::io::Emit16(Out, DataLen);
1162 return std::make_pair(KeyLen, DataLen);
1163 }
1164
Douglas Gregor2d711832009-04-25 17:48:32 +00001165 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1166 uint64_t Start = Out.tell();
1167 assert((Start >> 32) == 0 && "Selector key offset too large");
1168 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001169 unsigned N = Sel.getNumArgs();
1170 clang::io::Emit16(Out, N);
1171 if (N == 0)
1172 N = 1;
1173 for (unsigned I = 0; I != N; ++I)
1174 clang::io::Emit32(Out,
1175 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1176 }
1177
1178 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001179 data_type_ref Methods, unsigned DataLen) {
1180 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001181 unsigned NumInstanceMethods = 0;
1182 for (const ObjCMethodList *Method = &Methods.first; Method;
1183 Method = Method->Next)
1184 if (Method->Method)
1185 ++NumInstanceMethods;
1186
1187 unsigned NumFactoryMethods = 0;
1188 for (const ObjCMethodList *Method = &Methods.second; Method;
1189 Method = Method->Next)
1190 if (Method->Method)
1191 ++NumFactoryMethods;
1192
1193 clang::io::Emit16(Out, NumInstanceMethods);
1194 clang::io::Emit16(Out, NumFactoryMethods);
1195 for (const ObjCMethodList *Method = &Methods.first; Method;
1196 Method = Method->Next)
1197 if (Method->Method)
1198 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001199 for (const ObjCMethodList *Method = &Methods.second; Method;
1200 Method = Method->Next)
1201 if (Method->Method)
1202 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001203
1204 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001205 }
1206};
1207} // end anonymous namespace
1208
1209/// \brief Write the method pool into the PCH file.
1210///
1211/// The method pool contains both instance and factory methods, stored
1212/// in an on-disk hash table indexed by the selector.
1213void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1214 using namespace llvm;
1215
1216 // Create and write out the blob that contains the instance and
1217 // factor method pools.
1218 bool Empty = true;
1219 {
1220 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1221
1222 // Create the on-disk hash table representation. Start by
1223 // iterating through the instance method pool.
1224 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001225 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001226 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1227 Instance = SemaRef.InstanceMethodPool.begin(),
1228 InstanceEnd = SemaRef.InstanceMethodPool.end();
1229 Instance != InstanceEnd; ++Instance) {
1230 // Check whether there is a factory method with the same
1231 // selector.
1232 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1233 = SemaRef.FactoryMethodPool.find(Instance->first);
1234
1235 if (Factory == SemaRef.FactoryMethodPool.end())
1236 Generator.insert(Instance->first,
1237 std::make_pair(Instance->second,
1238 ObjCMethodList()));
1239 else
1240 Generator.insert(Instance->first,
1241 std::make_pair(Instance->second, Factory->second));
1242
Douglas Gregor2d711832009-04-25 17:48:32 +00001243 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001244 Empty = false;
1245 }
1246
1247 // Now iterate through the factory method pool, to pick up any
1248 // selectors that weren't already in the instance method pool.
1249 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1250 Factory = SemaRef.FactoryMethodPool.begin(),
1251 FactoryEnd = SemaRef.FactoryMethodPool.end();
1252 Factory != FactoryEnd; ++Factory) {
1253 // Check whether there is an instance method with the same
1254 // selector. If so, there is no work to do here.
1255 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1256 = SemaRef.InstanceMethodPool.find(Factory->first);
1257
Douglas Gregor2d711832009-04-25 17:48:32 +00001258 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001259 Generator.insert(Factory->first,
1260 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001261 ++NumSelectorsInMethodPool;
1262 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001263
1264 Empty = false;
1265 }
1266
Douglas Gregor2d711832009-04-25 17:48:32 +00001267 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001268 return;
1269
1270 // Create the on-disk hash table in a buffer.
1271 llvm::SmallVector<char, 4096> MethodPool;
1272 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001273 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001274 {
1275 PCHMethodPoolTrait Trait(*this);
1276 llvm::raw_svector_ostream Out(MethodPool);
1277 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001278 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001279 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001280
1281 // For every selector that we have seen but which was not
1282 // written into the hash table, write the selector itself and
1283 // record it's offset.
1284 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1285 if (SelectorOffsets[I] == 0)
1286 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001287 }
1288
1289 // Create a blob abbreviation
1290 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1291 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1292 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001293 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001294 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1295 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1296
Douglas Gregor2d711832009-04-25 17:48:32 +00001297 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001298 RecordData Record;
1299 Record.push_back(pch::METHOD_POOL);
1300 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001301 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001302 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1303 &MethodPool.front(),
1304 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001305
1306 // Create a blob abbreviation for the selector table offsets.
1307 Abbrev = new BitCodeAbbrev();
1308 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1309 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1310 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1311 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1312
1313 // Write the selector offsets table.
1314 Record.clear();
1315 Record.push_back(pch::SELECTOR_OFFSETS);
1316 Record.push_back(SelectorOffsets.size());
1317 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1318 (const char *)&SelectorOffsets.front(),
1319 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001320 }
1321}
1322
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001323//===----------------------------------------------------------------------===//
1324// Identifier Table Serialization
1325//===----------------------------------------------------------------------===//
1326
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001327namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001328class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1329 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001330 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001331
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001332 /// \brief Determines whether this is an "interesting" identifier
1333 /// that needs a full IdentifierInfo structure written into the hash
1334 /// table.
1335 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1336 return II->isPoisoned() ||
1337 II->isExtensionToken() ||
1338 II->hasMacroDefinition() ||
1339 II->getObjCOrBuiltinID() ||
1340 II->getFETokenInfo<void>();
1341 }
1342
Douglas Gregorff9a6092009-04-20 20:36:09 +00001343public:
1344 typedef const IdentifierInfo* key_type;
1345 typedef key_type key_type_ref;
1346
1347 typedef pch::IdentID data_type;
1348 typedef data_type data_type_ref;
1349
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001350 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1351 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001352
1353 static unsigned ComputeHash(const IdentifierInfo* II) {
1354 return clang::BernsteinHash(II->getName());
1355 }
1356
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001357 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001358 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1359 pch::IdentID ID) {
1360 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001361 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1362 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001363 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001364 if (II->hasMacroDefinition() &&
1365 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001366 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001367 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1368 DEnd = IdentifierResolver::end();
1369 D != DEnd; ++D)
1370 DataLen += sizeof(pch::DeclID);
1371 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001372 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001373 // We emit the key length after the data length so that every
1374 // string is preceded by a 16-bit length. This matches the PTH
1375 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001376 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001377 return std::make_pair(KeyLen, DataLen);
1378 }
1379
1380 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1381 unsigned KeyLen) {
1382 // Record the location of the key data. This is used when generating
1383 // the mapping from persistent IDs to strings.
1384 Writer.SetIdentifierOffset(II, Out.tell());
1385 Out.write(II->getName(), KeyLen);
1386 }
1387
1388 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1389 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001390 if (!isInterestingIdentifier(II)) {
1391 clang::io::Emit32(Out, ID << 1);
1392 return;
1393 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001394
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001395 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001396 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001397 bool hasMacroDefinition =
1398 II->hasMacroDefinition() &&
1399 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001400 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001401 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001402 Bits = (Bits << 1) | II->isExtensionToken();
1403 Bits = (Bits << 1) | II->isPoisoned();
1404 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001405 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001406
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001407 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001408 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001409
Douglas Gregorc713da92009-04-21 22:25:48 +00001410 // Emit the declaration IDs in reverse order, because the
1411 // IdentifierResolver provides the declarations as they would be
1412 // visible (e.g., the function "stat" would come before the struct
1413 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1414 // adds declarations to the end of the list (so we need to see the
1415 // struct "status" before the function "status").
1416 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1417 IdentifierResolver::end());
1418 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1419 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001420 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001421 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001422 }
1423};
1424} // end anonymous namespace
1425
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001426/// \brief Write the identifier table into the PCH file.
1427///
1428/// The identifier table consists of a blob containing string data
1429/// (the actual identifiers themselves) and a separate "offsets" index
1430/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001431void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001432 using namespace llvm;
1433
1434 // Create and write out the blob that contains the identifier
1435 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001436 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001437 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1438
Douglas Gregor91137812009-04-28 20:33:11 +00001439 // Look for any identifiers that were named while processing the
1440 // headers, but are otherwise not needed. We add these to the hash
1441 // table to enable checking of the predefines buffer in the case
1442 // where the user adds new macro definitions when building the PCH
1443 // file.
1444 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1445 IDEnd = PP.getIdentifierTable().end();
1446 ID != IDEnd; ++ID)
1447 getIdentifierRef(ID->second);
1448
Douglas Gregorff9a6092009-04-20 20:36:09 +00001449 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001450 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001451 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1452 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1453 ID != IDEnd; ++ID) {
1454 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001455 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001456 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001457
Douglas Gregorff9a6092009-04-20 20:36:09 +00001458 // Create the on-disk hash table in a buffer.
1459 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001460 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001461 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001462 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001463 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001464 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001465 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001466 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001467 }
1468
1469 // Create a blob abbreviation
1470 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1471 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001472 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001473 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001474 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001475
1476 // Write the identifier table
1477 RecordData Record;
1478 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001479 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001480 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1481 &IdentifierTable.front(),
1482 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001483 }
1484
1485 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001486 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1487 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1488 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1490 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1491
1492 RecordData Record;
1493 Record.push_back(pch::IDENTIFIER_OFFSET);
1494 Record.push_back(IdentifierOffsets.size());
1495 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1496 (const char *)&IdentifierOffsets.front(),
1497 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001498}
1499
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001500//===----------------------------------------------------------------------===//
1501// General Serialization Routines
1502//===----------------------------------------------------------------------===//
1503
Douglas Gregor1c507882009-04-15 21:30:51 +00001504/// \brief Write a record containing the given attributes.
1505void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1506 RecordData Record;
1507 for (; Attr; Attr = Attr->getNext()) {
1508 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1509 Record.push_back(Attr->isInherited());
1510 switch (Attr->getKind()) {
1511 case Attr::Alias:
1512 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1513 break;
1514
1515 case Attr::Aligned:
1516 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1517 break;
1518
1519 case Attr::AlwaysInline:
1520 break;
1521
1522 case Attr::AnalyzerNoReturn:
1523 break;
1524
1525 case Attr::Annotate:
1526 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1527 break;
1528
1529 case Attr::AsmLabel:
1530 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1531 break;
1532
1533 case Attr::Blocks:
1534 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1535 break;
1536
1537 case Attr::Cleanup:
1538 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1539 break;
1540
1541 case Attr::Const:
1542 break;
1543
1544 case Attr::Constructor:
1545 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1546 break;
1547
1548 case Attr::DLLExport:
1549 case Attr::DLLImport:
1550 case Attr::Deprecated:
1551 break;
1552
1553 case Attr::Destructor:
1554 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1555 break;
1556
1557 case Attr::FastCall:
1558 break;
1559
1560 case Attr::Format: {
1561 const FormatAttr *Format = cast<FormatAttr>(Attr);
1562 AddString(Format->getType(), Record);
1563 Record.push_back(Format->getFormatIdx());
1564 Record.push_back(Format->getFirstArg());
1565 break;
1566 }
1567
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001568 case Attr::FormatArg: {
1569 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1570 Record.push_back(Format->getFormatIdx());
1571 break;
1572 }
1573
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001574 case Attr::Sentinel : {
1575 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1576 Record.push_back(Sentinel->getSentinel());
1577 Record.push_back(Sentinel->getNullPos());
1578 break;
1579 }
1580
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001581 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001582 case Attr::IBOutletKind:
1583 case Attr::NoReturn:
1584 case Attr::NoThrow:
1585 case Attr::Nodebug:
1586 case Attr::Noinline:
1587 break;
1588
1589 case Attr::NonNull: {
1590 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1591 Record.push_back(NonNull->size());
1592 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1593 break;
1594 }
1595
1596 case Attr::ObjCException:
1597 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001598 case Attr::CFReturnsRetained:
1599 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001600 case Attr::Overloadable:
1601 break;
1602
1603 case Attr::Packed:
1604 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1605 break;
1606
1607 case Attr::Pure:
1608 break;
1609
1610 case Attr::Regparm:
1611 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1612 break;
1613
1614 case Attr::Section:
1615 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1616 break;
1617
1618 case Attr::StdCall:
1619 case Attr::TransparentUnion:
1620 case Attr::Unavailable:
1621 case Attr::Unused:
1622 case Attr::Used:
1623 break;
1624
1625 case Attr::Visibility:
1626 // FIXME: stable encoding
1627 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1628 break;
1629
1630 case Attr::WarnUnusedResult:
1631 case Attr::Weak:
1632 case Attr::WeakImport:
1633 break;
1634 }
1635 }
1636
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001637 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001638}
1639
1640void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1641 Record.push_back(Str.size());
1642 Record.insert(Record.end(), Str.begin(), Str.end());
1643}
1644
Douglas Gregorff9a6092009-04-20 20:36:09 +00001645/// \brief Note that the identifier II occurs at the given offset
1646/// within the identifier table.
1647void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001648 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001649}
1650
Douglas Gregor2d711832009-04-25 17:48:32 +00001651/// \brief Note that the selector Sel occurs at the given offset
1652/// within the method pool/selector table.
1653void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1654 unsigned ID = SelectorIDs[Sel];
1655 assert(ID && "Unknown selector");
1656 SelectorOffsets[ID - 1] = Offset;
1657}
1658
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001659PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001660 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001661 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1662 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001663
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001664void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001665 using namespace llvm;
1666
Douglas Gregor87887da2009-04-20 15:53:59 +00001667 ASTContext &Context = SemaRef.Context;
1668 Preprocessor &PP = SemaRef.PP;
1669
Douglas Gregorc34897d2009-04-09 22:27:44 +00001670 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001671 Stream.Emit((unsigned)'C', 8);
1672 Stream.Emit((unsigned)'P', 8);
1673 Stream.Emit((unsigned)'C', 8);
1674 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001675
1676 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001677
1678 // The translation unit is the first declaration we'll emit.
1679 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1680 DeclsToEmit.push(Context.getTranslationUnitDecl());
1681
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001682 // Make sure that we emit IdentifierInfos (and any attached
1683 // declarations) for builtins.
1684 {
1685 IdentifierTable &Table = PP.getIdentifierTable();
1686 llvm::SmallVector<const char *, 32> BuiltinNames;
1687 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1688 Context.getLangOptions().NoBuiltin);
1689 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1690 getIdentifierRef(&Table.get(BuiltinNames[I]));
1691 }
1692
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001693 // Build a record containing all of the tentative definitions in
1694 // this header file. Generally, this record will be empty.
1695 RecordData TentativeDefinitions;
1696 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1697 TD = SemaRef.TentativeDefinitions.begin(),
1698 TDEnd = SemaRef.TentativeDefinitions.end();
1699 TD != TDEnd; ++TD)
1700 AddDeclRef(TD->second, TentativeDefinitions);
1701
Douglas Gregor062d9482009-04-22 22:18:58 +00001702 // Build a record containing all of the locally-scoped external
1703 // declarations in this header file. Generally, this record will be
1704 // empty.
1705 RecordData LocallyScopedExternalDecls;
1706 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1707 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1708 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1709 TD != TDEnd; ++TD)
1710 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1711
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001712 // Build a record containing all of the ext_vector declarations.
1713 RecordData ExtVectorDecls;
1714 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1715 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1716
1717 // Build a record containing all of the Objective-C category
1718 // implementations.
1719 RecordData ObjCCategoryImpls;
1720 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1721 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1722
Douglas Gregorc34897d2009-04-09 22:27:44 +00001723 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001724 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001725 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001726 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001727 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001728 if (StatCalls)
1729 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001730 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001731 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001732
1733 // Keep writing types and declarations until all types and
1734 // declarations have been written.
1735 do {
1736 if (!DeclsToEmit.empty())
1737 WriteDeclsBlock(Context);
1738 if (!TypesToEmit.empty())
1739 WriteTypesBlock(Context);
1740 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1741
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001742 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001743 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001744
1745 // Write the type offsets array
1746 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1747 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1750 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1751 Record.clear();
1752 Record.push_back(pch::TYPE_OFFSET);
1753 Record.push_back(TypeOffsets.size());
1754 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1755 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001756 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001757
1758 // Write the declaration offsets array
1759 Abbrev = new BitCodeAbbrev();
1760 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1763 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1764 Record.clear();
1765 Record.push_back(pch::DECL_OFFSET);
1766 Record.push_back(DeclOffsets.size());
1767 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1768 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001769 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001770
1771 // Write the record of special types.
1772 Record.clear();
1773 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001774 AddTypeRef(Context.getObjCIdType(), Record);
1775 AddTypeRef(Context.getObjCSelType(), Record);
1776 AddTypeRef(Context.getObjCProtoType(), Record);
1777 AddTypeRef(Context.getObjCClassType(), Record);
1778 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1779 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001780 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1781
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001782 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001783 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001784 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001785
1786 // Write the record containing tentative definitions.
1787 if (!TentativeDefinitions.empty())
1788 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001789
1790 // Write the record containing locally-scoped external definitions.
1791 if (!LocallyScopedExternalDecls.empty())
1792 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1793 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001794
1795 // Write the record containing ext_vector type names.
1796 if (!ExtVectorDecls.empty())
1797 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1798
1799 // Write the record containing Objective-C category implementations.
1800 if (!ObjCCategoryImpls.empty())
1801 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001802
1803 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001804 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001805 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001806 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001807 Record.push_back(NumLexicalDeclContexts);
1808 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001809 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001810 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001811}
1812
1813void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1814 Record.push_back(Loc.getRawEncoding());
1815}
1816
1817void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1818 Record.push_back(Value.getBitWidth());
1819 unsigned N = Value.getNumWords();
1820 const uint64_t* Words = Value.getRawData();
1821 for (unsigned I = 0; I != N; ++I)
1822 Record.push_back(Words[I]);
1823}
1824
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001825void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1826 Record.push_back(Value.isUnsigned());
1827 AddAPInt(Value, Record);
1828}
1829
Douglas Gregore2f37202009-04-14 21:55:33 +00001830void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1831 AddAPInt(Value.bitcastToAPInt(), Record);
1832}
1833
Douglas Gregorc34897d2009-04-09 22:27:44 +00001834void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001835 Record.push_back(getIdentifierRef(II));
1836}
1837
1838pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1839 if (II == 0)
1840 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001841
1842 pch::IdentID &ID = IdentifierIDs[II];
1843 if (ID == 0)
1844 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001845 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001846}
1847
Steve Naroff9e84d782009-04-23 10:39:46 +00001848void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1849 if (SelRef.getAsOpaquePtr() == 0) {
1850 Record.push_back(0);
1851 return;
1852 }
1853
1854 pch::SelectorID &SID = SelectorIDs[SelRef];
1855 if (SID == 0) {
1856 SID = SelectorIDs.size();
1857 SelVector.push_back(SelRef);
1858 }
1859 Record.push_back(SID);
1860}
1861
Douglas Gregorc34897d2009-04-09 22:27:44 +00001862void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1863 if (T.isNull()) {
1864 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1865 return;
1866 }
1867
1868 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001869 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001870 switch (BT->getKind()) {
1871 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1872 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1873 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1874 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1875 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1876 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1877 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1878 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001879 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001880 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1881 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1882 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1883 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1884 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1885 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1886 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001887 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001888 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1889 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1890 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001891 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001892 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1893 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1894 }
1895
1896 Record.push_back((ID << 3) | T.getCVRQualifiers());
1897 return;
1898 }
1899
Douglas Gregorac8f2802009-04-10 17:25:41 +00001900 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001901 if (ID == 0) {
1902 // We haven't seen this type before. Assign it a new ID and put it
1903 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001904 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001905 TypesToEmit.push(T.getTypePtr());
1906 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001907
1908 // Encode the type qualifiers in the type reference.
1909 Record.push_back((ID << 3) | T.getCVRQualifiers());
1910}
1911
1912void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1913 if (D == 0) {
1914 Record.push_back(0);
1915 return;
1916 }
1917
Douglas Gregorac8f2802009-04-10 17:25:41 +00001918 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001919 if (ID == 0) {
1920 // We haven't seen this declaration before. Give it a new ID and
1921 // enqueue it in the list of declarations to emit.
1922 ID = DeclIDs.size();
1923 DeclsToEmit.push(const_cast<Decl *>(D));
1924 }
1925
1926 Record.push_back(ID);
1927}
1928
Douglas Gregorff9a6092009-04-20 20:36:09 +00001929pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1930 if (D == 0)
1931 return 0;
1932
1933 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1934 return DeclIDs[D];
1935}
1936
Douglas Gregorc34897d2009-04-09 22:27:44 +00001937void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001938 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001939 Record.push_back(Name.getNameKind());
1940 switch (Name.getNameKind()) {
1941 case DeclarationName::Identifier:
1942 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1943 break;
1944
1945 case DeclarationName::ObjCZeroArgSelector:
1946 case DeclarationName::ObjCOneArgSelector:
1947 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001948 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001949 break;
1950
1951 case DeclarationName::CXXConstructorName:
1952 case DeclarationName::CXXDestructorName:
1953 case DeclarationName::CXXConversionFunctionName:
1954 AddTypeRef(Name.getCXXNameType(), Record);
1955 break;
1956
1957 case DeclarationName::CXXOperatorName:
1958 Record.push_back(Name.getCXXOverloadedOperator());
1959 break;
1960
1961 case DeclarationName::CXXUsingDirective:
1962 // No extra data to emit
1963 break;
1964 }
1965}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001966