blob: 808df70df30d1272210f8c236c5cd4264975b665 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregor3251ceb2009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregorb64c1932009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000043
Douglas Gregor2cf26342009-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 Gregor4fed3f42009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-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 Gregorc9490c02009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-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 Redl465226e2009-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 Gregor2cf26342009-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 Gregorc9490c02009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-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
Anders Carlsson395b4752009-06-24 19:06:50 +0000188void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
189 Writer.AddStmt(T->getUnderlyingExpr());
190 Code = pch::TYPE_DECLTYPE;
191}
192
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193void PCHTypeWriter::VisitTagType(const TagType *T) {
194 Writer.AddDeclRef(T->getDecl(), Record);
195 assert(!T->isBeingDefined() &&
196 "Cannot serialize in the middle of a type definition");
197}
198
199void PCHTypeWriter::VisitRecordType(const RecordType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_RECORD;
202}
203
204void PCHTypeWriter::VisitEnumType(const EnumType *T) {
205 VisitTagType(T);
206 Code = pch::TYPE_ENUM;
207}
208
209void
210PCHTypeWriter::VisitTemplateSpecializationType(
211 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize template specialization types");
214}
215
216void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000217 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000218 assert(false && "Cannot serialize qualified name types");
219}
220
221void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
222 Writer.AddDeclRef(T->getDecl(), Record);
223 Code = pch::TYPE_OBJC_INTERFACE;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedInterfaceType(
228 const ObjCQualifiedInterfaceType *T) {
229 VisitObjCInterfaceType(T);
230 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000231 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
232 E = T->qual_end(); I != E; ++I)
233 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000234 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
235}
236
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000237void
238PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
239 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000240 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000241 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000242 E = T->qual_end(); I != E; ++I)
243 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000244 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000245}
246
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000247//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000248// PCHWriter Implementation
249//===----------------------------------------------------------------------===//
250
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000251static void EmitBlockID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
257
258 // Emit the block name if present.
259 if (Name == 0 || Name[0] == 0) return;
260 Record.clear();
261 while (*Name)
262 Record.push_back(*Name++);
263 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
264}
265
266static void EmitRecordID(unsigned ID, const char *Name,
267 llvm::BitstreamWriter &Stream,
268 PCHWriter::RecordData &Record) {
269 Record.clear();
270 Record.push_back(ID);
271 while (*Name)
272 Record.push_back(*Name++);
273 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000274}
275
276static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
277 PCHWriter::RecordData &Record) {
278#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
279 RECORD(STMT_STOP);
280 RECORD(STMT_NULL_PTR);
281 RECORD(STMT_NULL);
282 RECORD(STMT_COMPOUND);
283 RECORD(STMT_CASE);
284 RECORD(STMT_DEFAULT);
285 RECORD(STMT_LABEL);
286 RECORD(STMT_IF);
287 RECORD(STMT_SWITCH);
288 RECORD(STMT_WHILE);
289 RECORD(STMT_DO);
290 RECORD(STMT_FOR);
291 RECORD(STMT_GOTO);
292 RECORD(STMT_INDIRECT_GOTO);
293 RECORD(STMT_CONTINUE);
294 RECORD(STMT_BREAK);
295 RECORD(STMT_RETURN);
296 RECORD(STMT_DECL);
297 RECORD(STMT_ASM);
298 RECORD(EXPR_PREDEFINED);
299 RECORD(EXPR_DECL_REF);
300 RECORD(EXPR_INTEGER_LITERAL);
301 RECORD(EXPR_FLOATING_LITERAL);
302 RECORD(EXPR_IMAGINARY_LITERAL);
303 RECORD(EXPR_STRING_LITERAL);
304 RECORD(EXPR_CHARACTER_LITERAL);
305 RECORD(EXPR_PAREN);
306 RECORD(EXPR_UNARY_OPERATOR);
307 RECORD(EXPR_SIZEOF_ALIGN_OF);
308 RECORD(EXPR_ARRAY_SUBSCRIPT);
309 RECORD(EXPR_CALL);
310 RECORD(EXPR_MEMBER);
311 RECORD(EXPR_BINARY_OPERATOR);
312 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
313 RECORD(EXPR_CONDITIONAL_OPERATOR);
314 RECORD(EXPR_IMPLICIT_CAST);
315 RECORD(EXPR_CSTYLE_CAST);
316 RECORD(EXPR_COMPOUND_LITERAL);
317 RECORD(EXPR_EXT_VECTOR_ELEMENT);
318 RECORD(EXPR_INIT_LIST);
319 RECORD(EXPR_DESIGNATED_INIT);
320 RECORD(EXPR_IMPLICIT_VALUE_INIT);
321 RECORD(EXPR_VA_ARG);
322 RECORD(EXPR_ADDR_LABEL);
323 RECORD(EXPR_STMT);
324 RECORD(EXPR_TYPES_COMPATIBLE);
325 RECORD(EXPR_CHOOSE);
326 RECORD(EXPR_GNU_NULL);
327 RECORD(EXPR_SHUFFLE_VECTOR);
328 RECORD(EXPR_BLOCK);
329 RECORD(EXPR_BLOCK_DECL_REF);
330 RECORD(EXPR_OBJC_STRING_LITERAL);
331 RECORD(EXPR_OBJC_ENCODE);
332 RECORD(EXPR_OBJC_SELECTOR_EXPR);
333 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
334 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
335 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
336 RECORD(EXPR_OBJC_KVC_REF_EXPR);
337 RECORD(EXPR_OBJC_MESSAGE_EXPR);
338 RECORD(EXPR_OBJC_SUPER_EXPR);
339 RECORD(STMT_OBJC_FOR_COLLECTION);
340 RECORD(STMT_OBJC_CATCH);
341 RECORD(STMT_OBJC_FINALLY);
342 RECORD(STMT_OBJC_AT_TRY);
343 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
344 RECORD(STMT_OBJC_AT_THROW);
345#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000346}
347
348void PCHWriter::WriteBlockInfoBlock() {
349 RecordData Record;
350 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
351
Chris Lattner2f4efd12009-04-27 00:40:25 +0000352#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000353#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
354
355 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000356 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000357 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000358 RECORD(TYPE_OFFSET);
359 RECORD(DECL_OFFSET);
360 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000361 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000362 RECORD(IDENTIFIER_OFFSET);
363 RECORD(IDENTIFIER_TABLE);
364 RECORD(EXTERNAL_DEFINITIONS);
365 RECORD(SPECIAL_TYPES);
366 RECORD(STATISTICS);
367 RECORD(TENTATIVE_DEFINITIONS);
368 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
369 RECORD(SELECTOR_OFFSETS);
370 RECORD(METHOD_POOL);
371 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000372 RECORD(SOURCE_LOCATION_OFFSETS);
373 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000374 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000375 RECORD(EXT_VECTOR_DECLS);
376 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000377
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000378 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000379 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000380 RECORD(SM_SLOC_FILE_ENTRY);
381 RECORD(SM_SLOC_BUFFER_ENTRY);
382 RECORD(SM_SLOC_BUFFER_BLOB);
383 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
384 RECORD(SM_LINE_TABLE);
385 RECORD(SM_HEADER_FILE_INFO);
386
387 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000388 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000389 RECORD(PP_MACRO_OBJECT_LIKE);
390 RECORD(PP_MACRO_FUNCTION_LIKE);
391 RECORD(PP_TOKEN);
392
393 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000394 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000395 RECORD(TYPE_EXT_QUAL);
396 RECORD(TYPE_FIXED_WIDTH_INT);
397 RECORD(TYPE_COMPLEX);
398 RECORD(TYPE_POINTER);
399 RECORD(TYPE_BLOCK_POINTER);
400 RECORD(TYPE_LVALUE_REFERENCE);
401 RECORD(TYPE_RVALUE_REFERENCE);
402 RECORD(TYPE_MEMBER_POINTER);
403 RECORD(TYPE_CONSTANT_ARRAY);
404 RECORD(TYPE_INCOMPLETE_ARRAY);
405 RECORD(TYPE_VARIABLE_ARRAY);
406 RECORD(TYPE_VECTOR);
407 RECORD(TYPE_EXT_VECTOR);
408 RECORD(TYPE_FUNCTION_PROTO);
409 RECORD(TYPE_FUNCTION_NO_PROTO);
410 RECORD(TYPE_TYPEDEF);
411 RECORD(TYPE_TYPEOF_EXPR);
412 RECORD(TYPE_TYPEOF);
413 RECORD(TYPE_RECORD);
414 RECORD(TYPE_ENUM);
415 RECORD(TYPE_OBJC_INTERFACE);
416 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000417 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000418 // Statements and Exprs can occur in the Types block.
419 AddStmtsExprs(Stream, Record);
420
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000421 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000422 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000423 RECORD(DECL_ATTR);
424 RECORD(DECL_TRANSLATION_UNIT);
425 RECORD(DECL_TYPEDEF);
426 RECORD(DECL_ENUM);
427 RECORD(DECL_RECORD);
428 RECORD(DECL_ENUM_CONSTANT);
429 RECORD(DECL_FUNCTION);
430 RECORD(DECL_OBJC_METHOD);
431 RECORD(DECL_OBJC_INTERFACE);
432 RECORD(DECL_OBJC_PROTOCOL);
433 RECORD(DECL_OBJC_IVAR);
434 RECORD(DECL_OBJC_AT_DEFS_FIELD);
435 RECORD(DECL_OBJC_CLASS);
436 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
437 RECORD(DECL_OBJC_CATEGORY);
438 RECORD(DECL_OBJC_CATEGORY_IMPL);
439 RECORD(DECL_OBJC_IMPLEMENTATION);
440 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
441 RECORD(DECL_OBJC_PROPERTY);
442 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000443 RECORD(DECL_FIELD);
444 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000445 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000446 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000447 RECORD(DECL_ORIGINAL_PARM_VAR);
448 RECORD(DECL_FILE_SCOPE_ASM);
449 RECORD(DECL_BLOCK);
450 RECORD(DECL_CONTEXT_LEXICAL);
451 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000452 // Statements and Exprs can occur in the Decls block.
453 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000454#undef RECORD
455#undef BLOCK
456 Stream.ExitBlock();
457}
458
459
Douglas Gregorab41e632009-04-27 22:23:34 +0000460/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregorb64c1932009-05-12 01:31:05 +0000461void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000462 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000463
464 // Original file name
465 SourceManager &SM = Context.getSourceManager();
466 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
467 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
468 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
469 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
470 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
471
472 llvm::sys::Path MainFilePath(MainFile->getName());
473 std::string MainFileName;
474
475 if (!MainFilePath.isAbsolute()) {
476 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
477 P.appendComponent(MainFilePath.toString());
478 MainFileName = P.toString();
479 } else {
480 MainFileName = MainFilePath.toString();
481 }
482
483 RecordData Record;
484 Record.push_back(pch::ORIGINAL_FILE_NAME);
485 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
486 MainFileName.size());
487 }
488
489 // Metadata
490 const TargetInfo &Target = Context.Target;
491 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
492 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
493 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
494 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
495 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
496 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
497 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
498 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000499
500 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000501 Record.push_back(pch::METADATA);
502 Record.push_back(pch::VERSION_MAJOR);
503 Record.push_back(pch::VERSION_MINOR);
504 Record.push_back(CLANG_VERSION_MAJOR);
505 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000506 const char *Triple = Target.getTargetTriple();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000507 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000508}
509
510/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000511void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
512 RecordData Record;
513 Record.push_back(LangOpts.Trigraphs);
514 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
515 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
516 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
517 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
518 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
519 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
520 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
521 Record.push_back(LangOpts.C99); // C99 Support
522 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
523 Record.push_back(LangOpts.CPlusPlus); // C++ Support
524 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000525 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
526
527 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
528 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
529 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
530
531 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000532 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
533 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000534 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000535 Record.push_back(LangOpts.Exceptions); // Support exception handling.
536
537 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
538 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
539 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
540
Chris Lattnerea5ce472009-04-27 07:35:58 +0000541 // Whether static initializers are protected by locks.
542 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000543 Record.push_back(LangOpts.Blocks); // block extension to C
544 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
545 // they are unused.
546 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
547 // (modulo the platform support).
548
549 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
550 // signed integer arithmetic overflows.
551
552 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
553 // may be ripped out at any time.
554
555 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
556 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
557 // defined.
558 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
559 // opposed to __DYNAMIC__).
560 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
561
562 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
563 // used (instead of C99 semantics).
564 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000565 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
566 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000567 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
568 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000569 Record.push_back(LangOpts.getGCMode());
570 Record.push_back(LangOpts.getVisibilityMode());
571 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000572 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000573 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000574}
575
Douglas Gregor14f79002009-04-10 03:52:48 +0000576//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000577// stat cache Serialization
578//===----------------------------------------------------------------------===//
579
580namespace {
581// Trait used for the on-disk hash table of stat cache results.
582class VISIBILITY_HIDDEN PCHStatCacheTrait {
583public:
584 typedef const char * key_type;
585 typedef key_type key_type_ref;
586
587 typedef std::pair<int, struct stat> data_type;
588 typedef const data_type& data_type_ref;
589
590 static unsigned ComputeHash(const char *path) {
591 return BernsteinHash(path);
592 }
593
594 std::pair<unsigned,unsigned>
595 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
596 data_type_ref Data) {
597 unsigned StrLen = strlen(path);
598 clang::io::Emit16(Out, StrLen);
599 unsigned DataLen = 1; // result value
600 if (Data.first == 0)
601 DataLen += 4 + 4 + 2 + 8 + 8;
602 clang::io::Emit8(Out, DataLen);
603 return std::make_pair(StrLen + 1, DataLen);
604 }
605
606 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
607 Out.write(path, KeyLen);
608 }
609
610 void EmitData(llvm::raw_ostream& Out, key_type_ref,
611 data_type_ref Data, unsigned DataLen) {
612 using namespace clang::io;
613 uint64_t Start = Out.tell(); (void)Start;
614
615 // Result of stat()
616 Emit8(Out, Data.first? 1 : 0);
617
618 if (Data.first == 0) {
619 Emit32(Out, (uint32_t) Data.second.st_ino);
620 Emit32(Out, (uint32_t) Data.second.st_dev);
621 Emit16(Out, (uint16_t) Data.second.st_mode);
622 Emit64(Out, (uint64_t) Data.second.st_mtime);
623 Emit64(Out, (uint64_t) Data.second.st_size);
624 }
625
626 assert(Out.tell() - Start == DataLen && "Wrong data length");
627 }
628};
629} // end anonymous namespace
630
631/// \brief Write the stat() system call cache to the PCH file.
632void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
633 // Build the on-disk hash table containing information about every
634 // stat() call.
635 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
636 unsigned NumStatEntries = 0;
637 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
638 StatEnd = StatCalls.end();
639 Stat != StatEnd; ++Stat, ++NumStatEntries)
640 Generator.insert(Stat->first(), Stat->second);
641
642 // Create the on-disk hash table in a buffer.
643 llvm::SmallVector<char, 4096> StatCacheData;
644 uint32_t BucketOffset;
645 {
646 llvm::raw_svector_ostream Out(StatCacheData);
647 // Make sure that no bucket is at offset 0
648 clang::io::Emit32(Out, 0);
649 BucketOffset = Generator.Emit(Out);
650 }
651
652 // Create a blob abbreviation
653 using namespace llvm;
654 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
655 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
656 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
657 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
659 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
660
661 // Write the stat cache
662 RecordData Record;
663 Record.push_back(pch::STAT_CACHE);
664 Record.push_back(BucketOffset);
665 Record.push_back(NumStatEntries);
666 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
667 &StatCacheData.front(),
668 StatCacheData.size());
669}
670
671//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000672// Source Manager Serialization
673//===----------------------------------------------------------------------===//
674
675/// \brief Create an abbreviation for the SLocEntry that refers to a
676/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000677static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000678 using namespace llvm;
679 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
680 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
681 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000686 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000687}
688
689/// \brief Create an abbreviation for the SLocEntry that refers to a
690/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000691static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000692 using namespace llvm;
693 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
694 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000700 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000701}
702
703/// \brief Create an abbreviation for the SLocEntry that refers to a
704/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000705static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000706 using namespace llvm;
707 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
708 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
709 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000710 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000711}
712
713/// \brief Create an abbreviation for the SLocEntry that refers to an
714/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000715static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000716 using namespace llvm;
717 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
718 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000724 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000725}
726
727/// \brief Writes the block containing the serialized form of the
728/// source manager.
729///
730/// TODO: We should probably use an on-disk hash table (stored in a
731/// blob), indexed based on the file name, so that we only create
732/// entries for files that we actually need. In the common case (no
733/// errors), we probably won't have to create file entries for any of
734/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000735void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
736 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000737 RecordData Record;
738
Chris Lattnerf04ad692009-04-10 17:16:57 +0000739 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000740 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000741
742 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000743 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
744 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
745 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
746 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000747
Douglas Gregorbd945002009-04-13 16:31:14 +0000748 // Write the line table.
749 if (SourceMgr.hasLineTable()) {
750 LineTableInfo &LineTable = SourceMgr.getLineTable();
751
752 // Emit the file names
753 Record.push_back(LineTable.getNumFilenames());
754 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
755 // Emit the file name
756 const char *Filename = LineTable.getFilename(I);
757 unsigned FilenameLen = Filename? strlen(Filename) : 0;
758 Record.push_back(FilenameLen);
759 if (FilenameLen)
760 Record.insert(Record.end(), Filename, Filename + FilenameLen);
761 }
762
763 // Emit the line entries
764 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
765 L != LEnd; ++L) {
766 // Emit the file ID
767 Record.push_back(L->first);
768
769 // Emit the line entries
770 Record.push_back(L->second.size());
771 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
772 LEEnd = L->second.end();
773 LE != LEEnd; ++LE) {
774 Record.push_back(LE->FileOffset);
775 Record.push_back(LE->LineNo);
776 Record.push_back(LE->FilenameID);
777 Record.push_back((unsigned)LE->FileKind);
778 Record.push_back(LE->IncludeOffset);
779 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000780 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000781 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000782 }
783
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000784 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000785 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000786 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000787 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
788 E = HS.header_file_end();
789 I != E; ++I) {
790 Record.push_back(I->isImport);
791 Record.push_back(I->DirInfo);
792 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000793 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000794 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
795 Record.clear();
796 }
797
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000798 // Write out the source location entry table. We skip the first
799 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000800 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000801 RecordData PreloadSLocs;
802 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
803 for (SourceManager::sloc_entry_iterator
804 SLoc = SourceMgr.sloc_entry_begin() + 1,
805 SLocEnd = SourceMgr.sloc_entry_end();
806 SLoc != SLocEnd; ++SLoc) {
807 // Record the offset of this source-location entry.
808 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
809
810 // Figure out which record code to use.
811 unsigned Code;
812 if (SLoc->isFile()) {
813 if (SLoc->getFile().getContentCache()->Entry)
814 Code = pch::SM_SLOC_FILE_ENTRY;
815 else
816 Code = pch::SM_SLOC_BUFFER_ENTRY;
817 } else
818 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
819 Record.clear();
820 Record.push_back(Code);
821
822 Record.push_back(SLoc->getOffset());
823 if (SLoc->isFile()) {
824 const SrcMgr::FileInfo &File = SLoc->getFile();
825 Record.push_back(File.getIncludeLoc().getRawEncoding());
826 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
827 Record.push_back(File.hasLineDirectives());
828
829 const SrcMgr::ContentCache *Content = File.getContentCache();
830 if (Content->Entry) {
831 // The source location entry is a file. The blob associated
832 // with this entry is the file name.
833 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
834 Content->Entry->getName(),
835 strlen(Content->Entry->getName()));
836
837 // FIXME: For now, preload all file source locations, so that
838 // we get the appropriate File entries in the reader. This is
839 // a temporary measure.
840 PreloadSLocs.push_back(SLocEntryOffsets.size());
841 } else {
842 // The source location entry is a buffer. The blob associated
843 // with this entry contains the contents of the buffer.
844
845 // We add one to the size so that we capture the trailing NULL
846 // that is required by llvm::MemoryBuffer::getMemBuffer (on
847 // the reader side).
848 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
849 const char *Name = Buffer->getBufferIdentifier();
850 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
851 Record.clear();
852 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
853 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
854 Buffer->getBufferStart(),
855 Buffer->getBufferSize() + 1);
856
857 if (strcmp(Name, "<built-in>") == 0)
858 PreloadSLocs.push_back(SLocEntryOffsets.size());
859 }
860 } else {
861 // The source location entry is an instantiation.
862 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
863 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
864 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
865 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
866
867 // Compute the token length for this macro expansion.
868 unsigned NextOffset = SourceMgr.getNextOffset();
869 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
870 if (++NextSLoc != SLocEnd)
871 NextOffset = NextSLoc->getOffset();
872 Record.push_back(NextOffset - SLoc->getOffset() - 1);
873 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
874 }
875 }
876
Douglas Gregorc9490c02009-04-16 22:23:12 +0000877 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000878
879 if (SLocEntryOffsets.empty())
880 return;
881
882 // Write the source-location offsets table into the PCH block. This
883 // table is used for lazily loading source-location information.
884 using namespace llvm;
885 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
886 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
888 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
890 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
891
892 Record.clear();
893 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
894 Record.push_back(SLocEntryOffsets.size());
895 Record.push_back(SourceMgr.getNextOffset());
896 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
897 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000898 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000899
900 // Write the source location entry preloads array, telling the PCH
901 // reader which source locations entries it should load eagerly.
902 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000903}
904
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000905//===----------------------------------------------------------------------===//
906// Preprocessor Serialization
907//===----------------------------------------------------------------------===//
908
Chris Lattner0b1fb982009-04-10 17:15:23 +0000909/// \brief Writes the block containing the serialized form of the
910/// preprocessor.
911///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000912void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000913 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000914
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000915 // If the preprocessor __COUNTER__ value has been bumped, remember it.
916 if (PP.getCounterValue() != 0) {
917 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000918 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000919 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000920 }
921
922 // Enter the preprocessor block.
923 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000924
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000925 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
926 // FIXME: use diagnostics subsystem for localization etc.
927 if (PP.SawDateOrTime())
928 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
929
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000930 // Loop over all the macro definitions that are live at the end of the file,
931 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000932 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
933 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000934 // FIXME: This emits macros in hash table order, we should do it in a stable
935 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000936 MacroInfo *MI = I->second;
937
938 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
939 // been redefined by the header (in which case they are not isBuiltinMacro).
940 if (MI->isBuiltinMacro())
941 continue;
942
Douglas Gregor37e26842009-04-21 23:56:24 +0000943 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000944 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000945 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000946 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
947 Record.push_back(MI->isUsed());
948
949 unsigned Code;
950 if (MI->isObjectLike()) {
951 Code = pch::PP_MACRO_OBJECT_LIKE;
952 } else {
953 Code = pch::PP_MACRO_FUNCTION_LIKE;
954
955 Record.push_back(MI->isC99Varargs());
956 Record.push_back(MI->isGNUVarargs());
957 Record.push_back(MI->getNumArgs());
958 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
959 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000960 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000961 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000962 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000963 Record.clear();
964
Chris Lattnerdf961c22009-04-10 18:08:30 +0000965 // Emit the tokens array.
966 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
967 // Note that we know that the preprocessor does not have any annotation
968 // tokens in it because they are created by the parser, and thus can't be
969 // in a macro definition.
970 const Token &Tok = MI->getReplacementToken(TokNo);
971
972 Record.push_back(Tok.getLocation().getRawEncoding());
973 Record.push_back(Tok.getLength());
974
Chris Lattnerdf961c22009-04-10 18:08:30 +0000975 // FIXME: When reading literal tokens, reconstruct the literal pointer if
976 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000977 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000978
979 // FIXME: Should translate token kind to a stable encoding.
980 Record.push_back(Tok.getKind());
981 // FIXME: Should translate token flags to a stable encoding.
982 Record.push_back(Tok.getFlags());
983
Douglas Gregorc9490c02009-04-16 22:23:12 +0000984 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000985 Record.clear();
986 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000987 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000988 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000989 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000990}
991
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000992//===----------------------------------------------------------------------===//
993// Type Serialization
994//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000995
Douglas Gregor2cf26342009-04-09 22:27:44 +0000996/// \brief Write the representation of a type to the PCH stream.
997void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000998 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000999 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001000 ID = NextTypeID++;
1001
1002 // Record the offset for this type.
1003 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001004 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1006 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001007 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001008 }
1009
1010 RecordData Record;
1011
1012 // Emit the type's representation.
1013 PCHTypeWriter W(*this, Record);
1014 switch (T->getTypeClass()) {
1015 // For all of the concrete, non-dependent types, call the
1016 // appropriate visitor function.
1017#define TYPE(Class, Base) \
1018 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1019#define ABSTRACT_TYPE(Class, Base)
1020#define DEPENDENT_TYPE(Class, Base)
1021#include "clang/AST/TypeNodes.def"
1022
1023 // For all of the dependent type nodes (which only occur in C++
1024 // templates), produce an error.
1025#define TYPE(Class, Base)
1026#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1027#include "clang/AST/TypeNodes.def"
1028 assert(false && "Cannot serialize dependent type nodes");
1029 break;
1030 }
1031
1032 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001033 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001034
1035 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001036 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001037}
1038
1039/// \brief Write a block containing all of the types.
1040void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001041 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001042 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001043
Douglas Gregor366809a2009-04-26 03:49:13 +00001044 // Emit all of the types that need to be emitted (so far).
1045 while (!TypesToEmit.empty()) {
1046 const Type *T = TypesToEmit.front();
1047 TypesToEmit.pop();
1048 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1049 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001050 }
1051
1052 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001053 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001054}
1055
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001056//===----------------------------------------------------------------------===//
1057// Declaration Serialization
1058//===----------------------------------------------------------------------===//
1059
Douglas Gregor2cf26342009-04-09 22:27:44 +00001060/// \brief Write the block containing all of the declaration IDs
1061/// lexically declared within the given DeclContext.
1062///
1063/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1064/// bistream, or 0 if no block was written.
1065uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1066 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001067 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001068 return 0;
1069
Douglas Gregorc9490c02009-04-16 22:23:12 +00001070 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001071 RecordData Record;
1072 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1073 DEnd = DC->decls_end(Context);
1074 D != DEnd; ++D)
1075 AddDeclRef(*D, Record);
1076
Douglas Gregor25123082009-04-22 22:34:57 +00001077 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001078 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001079 return Offset;
1080}
1081
1082/// \brief Write the block containing all of the declaration IDs
1083/// visible from the given DeclContext.
1084///
1085/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1086/// bistream, or 0 if no block was written.
1087uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1088 DeclContext *DC) {
1089 if (DC->getPrimaryContext() != DC)
1090 return 0;
1091
Douglas Gregoraff22df2009-04-21 22:32:33 +00001092 // Since there is no name lookup into functions or methods, and we
1093 // perform name lookup for the translation unit via the
1094 // IdentifierInfo chains, don't bother to build a
1095 // visible-declarations table for these entities.
1096 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001097 return 0;
1098
Douglas Gregor2cf26342009-04-09 22:27:44 +00001099 // Force the DeclContext to build a its name-lookup table.
1100 DC->lookup(Context, DeclarationName());
1101
1102 // Serialize the contents of the mapping used for lookup. Note that,
1103 // although we have two very different code paths, the serialized
1104 // representation is the same for both cases: a declaration name,
1105 // followed by a size, followed by references to the visible
1106 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001107 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001108 RecordData Record;
1109 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001110 if (!Map)
1111 return 0;
1112
Douglas Gregor2cf26342009-04-09 22:27:44 +00001113 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1114 D != DEnd; ++D) {
1115 AddDeclarationName(D->first, Record);
1116 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1117 Record.push_back(Result.second - Result.first);
1118 for(; Result.first != Result.second; ++Result.first)
1119 AddDeclRef(*Result.first, Record);
1120 }
1121
1122 if (Record.size() == 0)
1123 return 0;
1124
Douglas Gregorc9490c02009-04-16 22:23:12 +00001125 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001126 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001127 return Offset;
1128}
1129
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001130//===----------------------------------------------------------------------===//
1131// Global Method Pool and Selector Serialization
1132//===----------------------------------------------------------------------===//
1133
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001134namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001135// Trait used for the on-disk hash table used in the method pool.
1136class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1137 PCHWriter &Writer;
1138
1139public:
1140 typedef Selector key_type;
1141 typedef key_type key_type_ref;
1142
1143 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1144 typedef const data_type& data_type_ref;
1145
1146 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1147
1148 static unsigned ComputeHash(Selector Sel) {
1149 unsigned N = Sel.getNumArgs();
1150 if (N == 0)
1151 ++N;
1152 unsigned R = 5381;
1153 for (unsigned I = 0; I != N; ++I)
1154 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1155 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1156 return R;
1157 }
1158
1159 std::pair<unsigned,unsigned>
1160 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1161 data_type_ref Methods) {
1162 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1163 clang::io::Emit16(Out, KeyLen);
1164 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1165 for (const ObjCMethodList *Method = &Methods.first; Method;
1166 Method = Method->Next)
1167 if (Method->Method)
1168 DataLen += 4;
1169 for (const ObjCMethodList *Method = &Methods.second; Method;
1170 Method = Method->Next)
1171 if (Method->Method)
1172 DataLen += 4;
1173 clang::io::Emit16(Out, DataLen);
1174 return std::make_pair(KeyLen, DataLen);
1175 }
1176
Douglas Gregor83941df2009-04-25 17:48:32 +00001177 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1178 uint64_t Start = Out.tell();
1179 assert((Start >> 32) == 0 && "Selector key offset too large");
1180 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001181 unsigned N = Sel.getNumArgs();
1182 clang::io::Emit16(Out, N);
1183 if (N == 0)
1184 N = 1;
1185 for (unsigned I = 0; I != N; ++I)
1186 clang::io::Emit32(Out,
1187 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1188 }
1189
1190 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001191 data_type_ref Methods, unsigned DataLen) {
1192 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001193 unsigned NumInstanceMethods = 0;
1194 for (const ObjCMethodList *Method = &Methods.first; Method;
1195 Method = Method->Next)
1196 if (Method->Method)
1197 ++NumInstanceMethods;
1198
1199 unsigned NumFactoryMethods = 0;
1200 for (const ObjCMethodList *Method = &Methods.second; Method;
1201 Method = Method->Next)
1202 if (Method->Method)
1203 ++NumFactoryMethods;
1204
1205 clang::io::Emit16(Out, NumInstanceMethods);
1206 clang::io::Emit16(Out, NumFactoryMethods);
1207 for (const ObjCMethodList *Method = &Methods.first; Method;
1208 Method = Method->Next)
1209 if (Method->Method)
1210 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001211 for (const ObjCMethodList *Method = &Methods.second; Method;
1212 Method = Method->Next)
1213 if (Method->Method)
1214 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001215
1216 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001217 }
1218};
1219} // end anonymous namespace
1220
1221/// \brief Write the method pool into the PCH file.
1222///
1223/// The method pool contains both instance and factory methods, stored
1224/// in an on-disk hash table indexed by the selector.
1225void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1226 using namespace llvm;
1227
1228 // Create and write out the blob that contains the instance and
1229 // factor method pools.
1230 bool Empty = true;
1231 {
1232 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1233
1234 // Create the on-disk hash table representation. Start by
1235 // iterating through the instance method pool.
1236 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001237 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001238 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1239 Instance = SemaRef.InstanceMethodPool.begin(),
1240 InstanceEnd = SemaRef.InstanceMethodPool.end();
1241 Instance != InstanceEnd; ++Instance) {
1242 // Check whether there is a factory method with the same
1243 // selector.
1244 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1245 = SemaRef.FactoryMethodPool.find(Instance->first);
1246
1247 if (Factory == SemaRef.FactoryMethodPool.end())
1248 Generator.insert(Instance->first,
1249 std::make_pair(Instance->second,
1250 ObjCMethodList()));
1251 else
1252 Generator.insert(Instance->first,
1253 std::make_pair(Instance->second, Factory->second));
1254
Douglas Gregor83941df2009-04-25 17:48:32 +00001255 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001256 Empty = false;
1257 }
1258
1259 // Now iterate through the factory method pool, to pick up any
1260 // selectors that weren't already in the instance method pool.
1261 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1262 Factory = SemaRef.FactoryMethodPool.begin(),
1263 FactoryEnd = SemaRef.FactoryMethodPool.end();
1264 Factory != FactoryEnd; ++Factory) {
1265 // Check whether there is an instance method with the same
1266 // selector. If so, there is no work to do here.
1267 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1268 = SemaRef.InstanceMethodPool.find(Factory->first);
1269
Douglas Gregor83941df2009-04-25 17:48:32 +00001270 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001271 Generator.insert(Factory->first,
1272 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001273 ++NumSelectorsInMethodPool;
1274 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001275
1276 Empty = false;
1277 }
1278
Douglas Gregor83941df2009-04-25 17:48:32 +00001279 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001280 return;
1281
1282 // Create the on-disk hash table in a buffer.
1283 llvm::SmallVector<char, 4096> MethodPool;
1284 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001285 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001286 {
1287 PCHMethodPoolTrait Trait(*this);
1288 llvm::raw_svector_ostream Out(MethodPool);
1289 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001290 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001291 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001292
1293 // For every selector that we have seen but which was not
1294 // written into the hash table, write the selector itself and
1295 // record it's offset.
1296 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1297 if (SelectorOffsets[I] == 0)
1298 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001299 }
1300
1301 // Create a blob abbreviation
1302 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1303 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001306 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1307 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1308
Douglas Gregor83941df2009-04-25 17:48:32 +00001309 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001310 RecordData Record;
1311 Record.push_back(pch::METHOD_POOL);
1312 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001313 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001314 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1315 &MethodPool.front(),
1316 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001317
1318 // Create a blob abbreviation for the selector table offsets.
1319 Abbrev = new BitCodeAbbrev();
1320 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1321 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1322 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1323 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1324
1325 // Write the selector offsets table.
1326 Record.clear();
1327 Record.push_back(pch::SELECTOR_OFFSETS);
1328 Record.push_back(SelectorOffsets.size());
1329 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1330 (const char *)&SelectorOffsets.front(),
1331 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001332 }
1333}
1334
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001335//===----------------------------------------------------------------------===//
1336// Identifier Table Serialization
1337//===----------------------------------------------------------------------===//
1338
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001339namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001340class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1341 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001342 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001343
Douglas Gregora92193e2009-04-28 21:18:29 +00001344 /// \brief Determines whether this is an "interesting" identifier
1345 /// that needs a full IdentifierInfo structure written into the hash
1346 /// table.
1347 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1348 return II->isPoisoned() ||
1349 II->isExtensionToken() ||
1350 II->hasMacroDefinition() ||
1351 II->getObjCOrBuiltinID() ||
1352 II->getFETokenInfo<void>();
1353 }
1354
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001355public:
1356 typedef const IdentifierInfo* key_type;
1357 typedef key_type key_type_ref;
1358
1359 typedef pch::IdentID data_type;
1360 typedef data_type data_type_ref;
1361
Douglas Gregor37e26842009-04-21 23:56:24 +00001362 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1363 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001364
1365 static unsigned ComputeHash(const IdentifierInfo* II) {
1366 return clang::BernsteinHash(II->getName());
1367 }
1368
Douglas Gregor37e26842009-04-21 23:56:24 +00001369 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001370 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1371 pch::IdentID ID) {
1372 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001373 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1374 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001375 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001376 if (II->hasMacroDefinition() &&
1377 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001378 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001379 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1380 DEnd = IdentifierResolver::end();
1381 D != DEnd; ++D)
1382 DataLen += sizeof(pch::DeclID);
1383 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001384 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001385 // We emit the key length after the data length so that every
1386 // string is preceded by a 16-bit length. This matches the PTH
1387 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001388 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001389 return std::make_pair(KeyLen, DataLen);
1390 }
1391
1392 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1393 unsigned KeyLen) {
1394 // Record the location of the key data. This is used when generating
1395 // the mapping from persistent IDs to strings.
1396 Writer.SetIdentifierOffset(II, Out.tell());
1397 Out.write(II->getName(), KeyLen);
1398 }
1399
1400 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1401 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001402 if (!isInterestingIdentifier(II)) {
1403 clang::io::Emit32(Out, ID << 1);
1404 return;
1405 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001406
Douglas Gregora92193e2009-04-28 21:18:29 +00001407 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001408 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001409 bool hasMacroDefinition =
1410 II->hasMacroDefinition() &&
1411 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001412 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001413 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001414 Bits = (Bits << 1) | II->isExtensionToken();
1415 Bits = (Bits << 1) | II->isPoisoned();
1416 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001417 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001418
Douglas Gregor37e26842009-04-21 23:56:24 +00001419 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001420 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001421
Douglas Gregor668c1a42009-04-21 22:25:48 +00001422 // Emit the declaration IDs in reverse order, because the
1423 // IdentifierResolver provides the declarations as they would be
1424 // visible (e.g., the function "stat" would come before the struct
1425 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1426 // adds declarations to the end of the list (so we need to see the
1427 // struct "status" before the function "status").
1428 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1429 IdentifierResolver::end());
1430 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1431 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001432 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001433 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001434 }
1435};
1436} // end anonymous namespace
1437
Douglas Gregorafaf3082009-04-11 00:14:32 +00001438/// \brief Write the identifier table into the PCH file.
1439///
1440/// The identifier table consists of a blob containing string data
1441/// (the actual identifiers themselves) and a separate "offsets" index
1442/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001443void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001444 using namespace llvm;
1445
1446 // Create and write out the blob that contains the identifier
1447 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001448 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001449 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1450
Douglas Gregor92b059e2009-04-28 20:33:11 +00001451 // Look for any identifiers that were named while processing the
1452 // headers, but are otherwise not needed. We add these to the hash
1453 // table to enable checking of the predefines buffer in the case
1454 // where the user adds new macro definitions when building the PCH
1455 // file.
1456 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1457 IDEnd = PP.getIdentifierTable().end();
1458 ID != IDEnd; ++ID)
1459 getIdentifierRef(ID->second);
1460
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001461 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001462 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001463 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1464 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1465 ID != IDEnd; ++ID) {
1466 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001467 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001468 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001469
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001470 // Create the on-disk hash table in a buffer.
1471 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001472 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001473 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001474 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001475 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001476 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001477 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001478 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001479 }
1480
1481 // Create a blob abbreviation
1482 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1483 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001485 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001486 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001487
1488 // Write the identifier table
1489 RecordData Record;
1490 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001491 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001492 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1493 &IdentifierTable.front(),
1494 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001495 }
1496
1497 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001498 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1499 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1501 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1502 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1503
1504 RecordData Record;
1505 Record.push_back(pch::IDENTIFIER_OFFSET);
1506 Record.push_back(IdentifierOffsets.size());
1507 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1508 (const char *)&IdentifierOffsets.front(),
1509 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001510}
1511
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001512//===----------------------------------------------------------------------===//
1513// General Serialization Routines
1514//===----------------------------------------------------------------------===//
1515
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001516/// \brief Write a record containing the given attributes.
1517void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1518 RecordData Record;
1519 for (; Attr; Attr = Attr->getNext()) {
1520 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1521 Record.push_back(Attr->isInherited());
1522 switch (Attr->getKind()) {
1523 case Attr::Alias:
1524 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1525 break;
1526
1527 case Attr::Aligned:
1528 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1529 break;
1530
1531 case Attr::AlwaysInline:
1532 break;
1533
1534 case Attr::AnalyzerNoReturn:
1535 break;
1536
1537 case Attr::Annotate:
1538 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1539 break;
1540
1541 case Attr::AsmLabel:
1542 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1543 break;
1544
1545 case Attr::Blocks:
1546 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1547 break;
1548
1549 case Attr::Cleanup:
1550 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1551 break;
1552
1553 case Attr::Const:
1554 break;
1555
1556 case Attr::Constructor:
1557 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1558 break;
1559
1560 case Attr::DLLExport:
1561 case Attr::DLLImport:
1562 case Attr::Deprecated:
1563 break;
1564
1565 case Attr::Destructor:
1566 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1567 break;
1568
1569 case Attr::FastCall:
1570 break;
1571
1572 case Attr::Format: {
1573 const FormatAttr *Format = cast<FormatAttr>(Attr);
1574 AddString(Format->getType(), Record);
1575 Record.push_back(Format->getFormatIdx());
1576 Record.push_back(Format->getFirstArg());
1577 break;
1578 }
1579
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001580 case Attr::FormatArg: {
1581 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1582 Record.push_back(Format->getFormatIdx());
1583 break;
1584 }
1585
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001586 case Attr::Sentinel : {
1587 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1588 Record.push_back(Sentinel->getSentinel());
1589 Record.push_back(Sentinel->getNullPos());
1590 break;
1591 }
1592
Chris Lattnercf2a7212009-04-20 19:12:28 +00001593 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001594 case Attr::IBOutletKind:
1595 case Attr::NoReturn:
1596 case Attr::NoThrow:
1597 case Attr::Nodebug:
1598 case Attr::Noinline:
1599 break;
1600
1601 case Attr::NonNull: {
1602 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1603 Record.push_back(NonNull->size());
1604 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1605 break;
1606 }
1607
1608 case Attr::ObjCException:
1609 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001610 case Attr::CFReturnsRetained:
1611 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001612 case Attr::Overloadable:
1613 break;
1614
1615 case Attr::Packed:
1616 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1617 break;
1618
1619 case Attr::Pure:
1620 break;
1621
1622 case Attr::Regparm:
1623 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1624 break;
Nate Begeman6f3d8382009-06-26 06:32:41 +00001625
1626 case Attr::ReqdWorkGroupSize:
1627 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1628 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1629 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1630 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001631
1632 case Attr::Section:
1633 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1634 break;
1635
1636 case Attr::StdCall:
1637 case Attr::TransparentUnion:
1638 case Attr::Unavailable:
1639 case Attr::Unused:
1640 case Attr::Used:
1641 break;
1642
1643 case Attr::Visibility:
1644 // FIXME: stable encoding
1645 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1646 break;
1647
1648 case Attr::WarnUnusedResult:
1649 case Attr::Weak:
1650 case Attr::WeakImport:
1651 break;
1652 }
1653 }
1654
Douglas Gregorc9490c02009-04-16 22:23:12 +00001655 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001656}
1657
1658void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1659 Record.push_back(Str.size());
1660 Record.insert(Record.end(), Str.begin(), Str.end());
1661}
1662
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001663/// \brief Note that the identifier II occurs at the given offset
1664/// within the identifier table.
1665void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001666 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001667}
1668
Douglas Gregor83941df2009-04-25 17:48:32 +00001669/// \brief Note that the selector Sel occurs at the given offset
1670/// within the method pool/selector table.
1671void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1672 unsigned ID = SelectorIDs[Sel];
1673 assert(ID && "Unknown selector");
1674 SelectorOffsets[ID - 1] = Offset;
1675}
1676
Douglas Gregorc9490c02009-04-16 22:23:12 +00001677PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001678 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001679 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1680 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001681
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001682void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001683 using namespace llvm;
1684
Douglas Gregore7785042009-04-20 15:53:59 +00001685 ASTContext &Context = SemaRef.Context;
1686 Preprocessor &PP = SemaRef.PP;
1687
Douglas Gregor2cf26342009-04-09 22:27:44 +00001688 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001689 Stream.Emit((unsigned)'C', 8);
1690 Stream.Emit((unsigned)'P', 8);
1691 Stream.Emit((unsigned)'C', 8);
1692 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001693
1694 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001695
1696 // The translation unit is the first declaration we'll emit.
1697 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1698 DeclsToEmit.push(Context.getTranslationUnitDecl());
1699
Douglas Gregor2deaea32009-04-22 18:49:13 +00001700 // Make sure that we emit IdentifierInfos (and any attached
1701 // declarations) for builtins.
1702 {
1703 IdentifierTable &Table = PP.getIdentifierTable();
1704 llvm::SmallVector<const char *, 32> BuiltinNames;
1705 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1706 Context.getLangOptions().NoBuiltin);
1707 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1708 getIdentifierRef(&Table.get(BuiltinNames[I]));
1709 }
1710
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001711 // Build a record containing all of the tentative definitions in
1712 // this header file. Generally, this record will be empty.
1713 RecordData TentativeDefinitions;
1714 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1715 TD = SemaRef.TentativeDefinitions.begin(),
1716 TDEnd = SemaRef.TentativeDefinitions.end();
1717 TD != TDEnd; ++TD)
1718 AddDeclRef(TD->second, TentativeDefinitions);
1719
Douglas Gregor14c22f22009-04-22 22:18:58 +00001720 // Build a record containing all of the locally-scoped external
1721 // declarations in this header file. Generally, this record will be
1722 // empty.
1723 RecordData LocallyScopedExternalDecls;
1724 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1725 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1726 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1727 TD != TDEnd; ++TD)
1728 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1729
Douglas Gregorb81c1702009-04-27 20:06:05 +00001730 // Build a record containing all of the ext_vector declarations.
1731 RecordData ExtVectorDecls;
1732 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1733 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1734
1735 // Build a record containing all of the Objective-C category
1736 // implementations.
1737 RecordData ObjCCategoryImpls;
1738 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1739 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1740
Douglas Gregor2cf26342009-04-09 22:27:44 +00001741 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001742 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001743 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001744 WriteMetadata(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001745 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001746 if (StatCalls)
1747 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001748 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001749 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001750
1751 // Keep writing types and declarations until all types and
1752 // declarations have been written.
1753 do {
1754 if (!DeclsToEmit.empty())
1755 WriteDeclsBlock(Context);
1756 if (!TypesToEmit.empty())
1757 WriteTypesBlock(Context);
1758 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1759
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001760 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001761 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001762
1763 // Write the type offsets array
1764 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1765 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1766 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1767 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1768 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1769 Record.clear();
1770 Record.push_back(pch::TYPE_OFFSET);
1771 Record.push_back(TypeOffsets.size());
1772 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1773 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001774 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001775
1776 // Write the declaration offsets array
1777 Abbrev = new BitCodeAbbrev();
1778 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1780 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1781 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1782 Record.clear();
1783 Record.push_back(pch::DECL_OFFSET);
1784 Record.push_back(DeclOffsets.size());
1785 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1786 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001787 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001788
1789 // Write the record of special types.
1790 Record.clear();
1791 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001792 AddTypeRef(Context.getObjCIdType(), Record);
1793 AddTypeRef(Context.getObjCSelType(), Record);
1794 AddTypeRef(Context.getObjCProtoType(), Record);
1795 AddTypeRef(Context.getObjCClassType(), Record);
1796 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1797 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001798 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1799
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001800 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001801 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001802 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001803
1804 // Write the record containing tentative definitions.
1805 if (!TentativeDefinitions.empty())
1806 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001807
1808 // Write the record containing locally-scoped external definitions.
1809 if (!LocallyScopedExternalDecls.empty())
1810 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1811 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001812
1813 // Write the record containing ext_vector type names.
1814 if (!ExtVectorDecls.empty())
1815 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1816
1817 // Write the record containing Objective-C category implementations.
1818 if (!ObjCCategoryImpls.empty())
1819 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001820
1821 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001822 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001823 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001824 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001825 Record.push_back(NumLexicalDeclContexts);
1826 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001827 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001828 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001829}
1830
1831void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1832 Record.push_back(Loc.getRawEncoding());
1833}
1834
1835void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1836 Record.push_back(Value.getBitWidth());
1837 unsigned N = Value.getNumWords();
1838 const uint64_t* Words = Value.getRawData();
1839 for (unsigned I = 0; I != N; ++I)
1840 Record.push_back(Words[I]);
1841}
1842
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001843void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1844 Record.push_back(Value.isUnsigned());
1845 AddAPInt(Value, Record);
1846}
1847
Douglas Gregor17fc2232009-04-14 21:55:33 +00001848void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1849 AddAPInt(Value.bitcastToAPInt(), Record);
1850}
1851
Douglas Gregor2cf26342009-04-09 22:27:44 +00001852void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001853 Record.push_back(getIdentifierRef(II));
1854}
1855
1856pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1857 if (II == 0)
1858 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001859
1860 pch::IdentID &ID = IdentifierIDs[II];
1861 if (ID == 0)
1862 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001863 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001864}
1865
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001866void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1867 if (SelRef.getAsOpaquePtr() == 0) {
1868 Record.push_back(0);
1869 return;
1870 }
1871
1872 pch::SelectorID &SID = SelectorIDs[SelRef];
1873 if (SID == 0) {
1874 SID = SelectorIDs.size();
1875 SelVector.push_back(SelRef);
1876 }
1877 Record.push_back(SID);
1878}
1879
Douglas Gregor2cf26342009-04-09 22:27:44 +00001880void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1881 if (T.isNull()) {
1882 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1883 return;
1884 }
1885
1886 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001887 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001888 switch (BT->getKind()) {
1889 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1890 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1891 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1892 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1893 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1894 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1895 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1896 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001897 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001898 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1899 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1900 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1901 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1902 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1903 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1904 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001905 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001906 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1907 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1908 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001909 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001910 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1911 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1912 }
1913
1914 Record.push_back((ID << 3) | T.getCVRQualifiers());
1915 return;
1916 }
1917
Douglas Gregor8038d512009-04-10 17:25:41 +00001918 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001919 if (ID == 0) {
1920 // We haven't seen this type before. Assign it a new ID and put it
1921 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001922 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001923 TypesToEmit.push(T.getTypePtr());
1924 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001925
1926 // Encode the type qualifiers in the type reference.
1927 Record.push_back((ID << 3) | T.getCVRQualifiers());
1928}
1929
1930void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1931 if (D == 0) {
1932 Record.push_back(0);
1933 return;
1934 }
1935
Douglas Gregor8038d512009-04-10 17:25:41 +00001936 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001937 if (ID == 0) {
1938 // We haven't seen this declaration before. Give it a new ID and
1939 // enqueue it in the list of declarations to emit.
1940 ID = DeclIDs.size();
1941 DeclsToEmit.push(const_cast<Decl *>(D));
1942 }
1943
1944 Record.push_back(ID);
1945}
1946
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001947pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1948 if (D == 0)
1949 return 0;
1950
1951 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1952 return DeclIDs[D];
1953}
1954
Douglas Gregor2cf26342009-04-09 22:27:44 +00001955void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001956 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001957 Record.push_back(Name.getNameKind());
1958 switch (Name.getNameKind()) {
1959 case DeclarationName::Identifier:
1960 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1961 break;
1962
1963 case DeclarationName::ObjCZeroArgSelector:
1964 case DeclarationName::ObjCOneArgSelector:
1965 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001966 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001967 break;
1968
1969 case DeclarationName::CXXConstructorName:
1970 case DeclarationName::CXXDestructorName:
1971 case DeclarationName::CXXConversionFunctionName:
1972 AddTypeRef(Name.getCXXNameType(), Record);
1973 break;
1974
1975 case DeclarationName::CXXOperatorName:
1976 Record.push_back(Name.getCXXOverloadedOperator());
1977 break;
1978
1979 case DeclarationName::CXXUsingDirective:
1980 // No extra data to emit
1981 break;
1982 }
1983}
Douglas Gregor0b748912009-04-14 21:18:50 +00001984