blob: 765fecbf852fad720e607a7b7acf4d86b7e0ed09 [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
188void PCHTypeWriter::VisitTagType(const TagType *T) {
189 Writer.AddDeclRef(T->getDecl(), Record);
190 assert(!T->isBeingDefined() &&
191 "Cannot serialize in the middle of a type definition");
192}
193
194void PCHTypeWriter::VisitRecordType(const RecordType *T) {
195 VisitTagType(T);
196 Code = pch::TYPE_RECORD;
197}
198
199void PCHTypeWriter::VisitEnumType(const EnumType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_ENUM;
202}
203
204void
205PCHTypeWriter::VisitTemplateSpecializationType(
206 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000207 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000208 assert(false && "Cannot serialize template specialization types");
209}
210
211void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *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 qualified name types");
214}
215
216void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
217 Writer.AddDeclRef(T->getDecl(), Record);
218 Code = pch::TYPE_OBJC_INTERFACE;
219}
220
221void
222PCHTypeWriter::VisitObjCQualifiedInterfaceType(
223 const ObjCQualifiedInterfaceType *T) {
224 VisitObjCInterfaceType(T);
225 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000226 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
227 E = T->qual_end(); I != E; ++I)
228 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000229 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
230}
231
232void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
233 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000234 for (ObjCQualifiedIdType::qual_iterator I = T->qual_begin(),
235 E = T->qual_end(); I != E; ++I)
236 Writer.AddDeclRef(*I, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000237 Code = pch::TYPE_OBJC_QUALIFIED_ID;
238}
239
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000240//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000241// PCHWriter Implementation
242//===----------------------------------------------------------------------===//
243
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000244static void EmitBlockID(unsigned ID, const char *Name,
245 llvm::BitstreamWriter &Stream,
246 PCHWriter::RecordData &Record) {
247 Record.clear();
248 Record.push_back(ID);
249 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
250
251 // Emit the block name if present.
252 if (Name == 0 || Name[0] == 0) return;
253 Record.clear();
254 while (*Name)
255 Record.push_back(*Name++);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
257}
258
259static void EmitRecordID(unsigned ID, const char *Name,
260 llvm::BitstreamWriter &Stream,
261 PCHWriter::RecordData &Record) {
262 Record.clear();
263 Record.push_back(ID);
264 while (*Name)
265 Record.push_back(*Name++);
266 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000267}
268
269static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
270 PCHWriter::RecordData &Record) {
271#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
272 RECORD(STMT_STOP);
273 RECORD(STMT_NULL_PTR);
274 RECORD(STMT_NULL);
275 RECORD(STMT_COMPOUND);
276 RECORD(STMT_CASE);
277 RECORD(STMT_DEFAULT);
278 RECORD(STMT_LABEL);
279 RECORD(STMT_IF);
280 RECORD(STMT_SWITCH);
281 RECORD(STMT_WHILE);
282 RECORD(STMT_DO);
283 RECORD(STMT_FOR);
284 RECORD(STMT_GOTO);
285 RECORD(STMT_INDIRECT_GOTO);
286 RECORD(STMT_CONTINUE);
287 RECORD(STMT_BREAK);
288 RECORD(STMT_RETURN);
289 RECORD(STMT_DECL);
290 RECORD(STMT_ASM);
291 RECORD(EXPR_PREDEFINED);
292 RECORD(EXPR_DECL_REF);
293 RECORD(EXPR_INTEGER_LITERAL);
294 RECORD(EXPR_FLOATING_LITERAL);
295 RECORD(EXPR_IMAGINARY_LITERAL);
296 RECORD(EXPR_STRING_LITERAL);
297 RECORD(EXPR_CHARACTER_LITERAL);
298 RECORD(EXPR_PAREN);
299 RECORD(EXPR_UNARY_OPERATOR);
300 RECORD(EXPR_SIZEOF_ALIGN_OF);
301 RECORD(EXPR_ARRAY_SUBSCRIPT);
302 RECORD(EXPR_CALL);
303 RECORD(EXPR_MEMBER);
304 RECORD(EXPR_BINARY_OPERATOR);
305 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
306 RECORD(EXPR_CONDITIONAL_OPERATOR);
307 RECORD(EXPR_IMPLICIT_CAST);
308 RECORD(EXPR_CSTYLE_CAST);
309 RECORD(EXPR_COMPOUND_LITERAL);
310 RECORD(EXPR_EXT_VECTOR_ELEMENT);
311 RECORD(EXPR_INIT_LIST);
312 RECORD(EXPR_DESIGNATED_INIT);
313 RECORD(EXPR_IMPLICIT_VALUE_INIT);
314 RECORD(EXPR_VA_ARG);
315 RECORD(EXPR_ADDR_LABEL);
316 RECORD(EXPR_STMT);
317 RECORD(EXPR_TYPES_COMPATIBLE);
318 RECORD(EXPR_CHOOSE);
319 RECORD(EXPR_GNU_NULL);
320 RECORD(EXPR_SHUFFLE_VECTOR);
321 RECORD(EXPR_BLOCK);
322 RECORD(EXPR_BLOCK_DECL_REF);
323 RECORD(EXPR_OBJC_STRING_LITERAL);
324 RECORD(EXPR_OBJC_ENCODE);
325 RECORD(EXPR_OBJC_SELECTOR_EXPR);
326 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
327 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
328 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
329 RECORD(EXPR_OBJC_KVC_REF_EXPR);
330 RECORD(EXPR_OBJC_MESSAGE_EXPR);
331 RECORD(EXPR_OBJC_SUPER_EXPR);
332 RECORD(STMT_OBJC_FOR_COLLECTION);
333 RECORD(STMT_OBJC_CATCH);
334 RECORD(STMT_OBJC_FINALLY);
335 RECORD(STMT_OBJC_AT_TRY);
336 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
337 RECORD(STMT_OBJC_AT_THROW);
338#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000339}
340
341void PCHWriter::WriteBlockInfoBlock() {
342 RecordData Record;
343 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
344
Chris Lattner2f4efd12009-04-27 00:40:25 +0000345#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000346#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
347
348 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000349 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000350 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000351 RECORD(TYPE_OFFSET);
352 RECORD(DECL_OFFSET);
353 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000354 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000355 RECORD(IDENTIFIER_OFFSET);
356 RECORD(IDENTIFIER_TABLE);
357 RECORD(EXTERNAL_DEFINITIONS);
358 RECORD(SPECIAL_TYPES);
359 RECORD(STATISTICS);
360 RECORD(TENTATIVE_DEFINITIONS);
361 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
362 RECORD(SELECTOR_OFFSETS);
363 RECORD(METHOD_POOL);
364 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000365 RECORD(SOURCE_LOCATION_OFFSETS);
366 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000367 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000368 RECORD(EXT_VECTOR_DECLS);
369 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000370
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000371 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000372 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000373 RECORD(SM_SLOC_FILE_ENTRY);
374 RECORD(SM_SLOC_BUFFER_ENTRY);
375 RECORD(SM_SLOC_BUFFER_BLOB);
376 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
377 RECORD(SM_LINE_TABLE);
378 RECORD(SM_HEADER_FILE_INFO);
379
380 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000381 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000382 RECORD(PP_MACRO_OBJECT_LIKE);
383 RECORD(PP_MACRO_FUNCTION_LIKE);
384 RECORD(PP_TOKEN);
385
386 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000387 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000388 RECORD(TYPE_EXT_QUAL);
389 RECORD(TYPE_FIXED_WIDTH_INT);
390 RECORD(TYPE_COMPLEX);
391 RECORD(TYPE_POINTER);
392 RECORD(TYPE_BLOCK_POINTER);
393 RECORD(TYPE_LVALUE_REFERENCE);
394 RECORD(TYPE_RVALUE_REFERENCE);
395 RECORD(TYPE_MEMBER_POINTER);
396 RECORD(TYPE_CONSTANT_ARRAY);
397 RECORD(TYPE_INCOMPLETE_ARRAY);
398 RECORD(TYPE_VARIABLE_ARRAY);
399 RECORD(TYPE_VECTOR);
400 RECORD(TYPE_EXT_VECTOR);
401 RECORD(TYPE_FUNCTION_PROTO);
402 RECORD(TYPE_FUNCTION_NO_PROTO);
403 RECORD(TYPE_TYPEDEF);
404 RECORD(TYPE_TYPEOF_EXPR);
405 RECORD(TYPE_TYPEOF);
406 RECORD(TYPE_RECORD);
407 RECORD(TYPE_ENUM);
408 RECORD(TYPE_OBJC_INTERFACE);
409 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
410 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000411 // Statements and Exprs can occur in the Types block.
412 AddStmtsExprs(Stream, Record);
413
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000414 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000415 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000416 RECORD(DECL_ATTR);
417 RECORD(DECL_TRANSLATION_UNIT);
418 RECORD(DECL_TYPEDEF);
419 RECORD(DECL_ENUM);
420 RECORD(DECL_RECORD);
421 RECORD(DECL_ENUM_CONSTANT);
422 RECORD(DECL_FUNCTION);
423 RECORD(DECL_OBJC_METHOD);
424 RECORD(DECL_OBJC_INTERFACE);
425 RECORD(DECL_OBJC_PROTOCOL);
426 RECORD(DECL_OBJC_IVAR);
427 RECORD(DECL_OBJC_AT_DEFS_FIELD);
428 RECORD(DECL_OBJC_CLASS);
429 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
430 RECORD(DECL_OBJC_CATEGORY);
431 RECORD(DECL_OBJC_CATEGORY_IMPL);
432 RECORD(DECL_OBJC_IMPLEMENTATION);
433 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
434 RECORD(DECL_OBJC_PROPERTY);
435 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000436 RECORD(DECL_FIELD);
437 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000438 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000439 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000440 RECORD(DECL_ORIGINAL_PARM_VAR);
441 RECORD(DECL_FILE_SCOPE_ASM);
442 RECORD(DECL_BLOCK);
443 RECORD(DECL_CONTEXT_LEXICAL);
444 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000445 // Statements and Exprs can occur in the Decls block.
446 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000447#undef RECORD
448#undef BLOCK
449 Stream.ExitBlock();
450}
451
452
Douglas Gregorab41e632009-04-27 22:23:34 +0000453/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregorb64c1932009-05-12 01:31:05 +0000454void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000455 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000456
457 // Original file name
458 SourceManager &SM = Context.getSourceManager();
459 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
460 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
461 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
462 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
463 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
464
465 llvm::sys::Path MainFilePath(MainFile->getName());
466 std::string MainFileName;
467
468 if (!MainFilePath.isAbsolute()) {
469 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
470 P.appendComponent(MainFilePath.toString());
471 MainFileName = P.toString();
472 } else {
473 MainFileName = MainFilePath.toString();
474 }
475
476 RecordData Record;
477 Record.push_back(pch::ORIGINAL_FILE_NAME);
478 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
479 MainFileName.size());
480 }
481
482 // Metadata
483 const TargetInfo &Target = Context.Target;
484 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
485 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
486 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
487 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
488 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
489 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
490 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
491 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000492
493 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000494 Record.push_back(pch::METADATA);
495 Record.push_back(pch::VERSION_MAJOR);
496 Record.push_back(pch::VERSION_MINOR);
497 Record.push_back(CLANG_VERSION_MAJOR);
498 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000499 const char *Triple = Target.getTargetTriple();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000500 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000501}
502
503/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000504void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
505 RecordData Record;
506 Record.push_back(LangOpts.Trigraphs);
507 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
508 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
509 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
510 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
511 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
512 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
513 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
514 Record.push_back(LangOpts.C99); // C99 Support
515 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
516 Record.push_back(LangOpts.CPlusPlus); // C++ Support
517 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000518 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
519
520 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
521 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
522 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
523
524 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000525 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
526 Record.push_back(LangOpts.LaxVectorConversions);
527 Record.push_back(LangOpts.Exceptions); // Support exception handling.
528
529 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
530 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
531 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
532
Chris Lattnerea5ce472009-04-27 07:35:58 +0000533 // Whether static initializers are protected by locks.
534 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000535 Record.push_back(LangOpts.Blocks); // block extension to C
536 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
537 // they are unused.
538 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
539 // (modulo the platform support).
540
541 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
542 // signed integer arithmetic overflows.
543
544 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
545 // may be ripped out at any time.
546
547 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
548 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
549 // defined.
550 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
551 // opposed to __DYNAMIC__).
552 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
553
554 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
555 // used (instead of C99 semantics).
556 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000557 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
558 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000559 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
560 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000561 Record.push_back(LangOpts.getGCMode());
562 Record.push_back(LangOpts.getVisibilityMode());
563 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000564 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000565}
566
Douglas Gregor14f79002009-04-10 03:52:48 +0000567//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000568// stat cache Serialization
569//===----------------------------------------------------------------------===//
570
571namespace {
572// Trait used for the on-disk hash table of stat cache results.
573class VISIBILITY_HIDDEN PCHStatCacheTrait {
574public:
575 typedef const char * key_type;
576 typedef key_type key_type_ref;
577
578 typedef std::pair<int, struct stat> data_type;
579 typedef const data_type& data_type_ref;
580
581 static unsigned ComputeHash(const char *path) {
582 return BernsteinHash(path);
583 }
584
585 std::pair<unsigned,unsigned>
586 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
587 data_type_ref Data) {
588 unsigned StrLen = strlen(path);
589 clang::io::Emit16(Out, StrLen);
590 unsigned DataLen = 1; // result value
591 if (Data.first == 0)
592 DataLen += 4 + 4 + 2 + 8 + 8;
593 clang::io::Emit8(Out, DataLen);
594 return std::make_pair(StrLen + 1, DataLen);
595 }
596
597 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
598 Out.write(path, KeyLen);
599 }
600
601 void EmitData(llvm::raw_ostream& Out, key_type_ref,
602 data_type_ref Data, unsigned DataLen) {
603 using namespace clang::io;
604 uint64_t Start = Out.tell(); (void)Start;
605
606 // Result of stat()
607 Emit8(Out, Data.first? 1 : 0);
608
609 if (Data.first == 0) {
610 Emit32(Out, (uint32_t) Data.second.st_ino);
611 Emit32(Out, (uint32_t) Data.second.st_dev);
612 Emit16(Out, (uint16_t) Data.second.st_mode);
613 Emit64(Out, (uint64_t) Data.second.st_mtime);
614 Emit64(Out, (uint64_t) Data.second.st_size);
615 }
616
617 assert(Out.tell() - Start == DataLen && "Wrong data length");
618 }
619};
620} // end anonymous namespace
621
622/// \brief Write the stat() system call cache to the PCH file.
623void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
624 // Build the on-disk hash table containing information about every
625 // stat() call.
626 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
627 unsigned NumStatEntries = 0;
628 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
629 StatEnd = StatCalls.end();
630 Stat != StatEnd; ++Stat, ++NumStatEntries)
631 Generator.insert(Stat->first(), Stat->second);
632
633 // Create the on-disk hash table in a buffer.
634 llvm::SmallVector<char, 4096> StatCacheData;
635 uint32_t BucketOffset;
636 {
637 llvm::raw_svector_ostream Out(StatCacheData);
638 // Make sure that no bucket is at offset 0
639 clang::io::Emit32(Out, 0);
640 BucketOffset = Generator.Emit(Out);
641 }
642
643 // Create a blob abbreviation
644 using namespace llvm;
645 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
646 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
650 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
651
652 // Write the stat cache
653 RecordData Record;
654 Record.push_back(pch::STAT_CACHE);
655 Record.push_back(BucketOffset);
656 Record.push_back(NumStatEntries);
657 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
658 &StatCacheData.front(),
659 StatCacheData.size());
660}
661
662//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000663// Source Manager Serialization
664//===----------------------------------------------------------------------===//
665
666/// \brief Create an abbreviation for the SLocEntry that refers to a
667/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000668static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000669 using namespace llvm;
670 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
671 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
672 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
673 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000677 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000678}
679
680/// \brief Create an abbreviation for the SLocEntry that refers to a
681/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000682static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000683 using namespace llvm;
684 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
685 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
687 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
689 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
690 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000691 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000692}
693
694/// \brief Create an abbreviation for the SLocEntry that refers to a
695/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000696static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000697 using namespace llvm;
698 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
699 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000701 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000702}
703
704/// \brief Create an abbreviation for the SLocEntry that refers to an
705/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000706static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000707 using namespace llvm;
708 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
709 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
711 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000715 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000716}
717
718/// \brief Writes the block containing the serialized form of the
719/// source manager.
720///
721/// TODO: We should probably use an on-disk hash table (stored in a
722/// blob), indexed based on the file name, so that we only create
723/// entries for files that we actually need. In the common case (no
724/// errors), we probably won't have to create file entries for any of
725/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000726void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
727 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000728 RecordData Record;
729
Chris Lattnerf04ad692009-04-10 17:16:57 +0000730 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000731 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000732
733 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000734 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
735 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
736 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
737 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000738
Douglas Gregorbd945002009-04-13 16:31:14 +0000739 // Write the line table.
740 if (SourceMgr.hasLineTable()) {
741 LineTableInfo &LineTable = SourceMgr.getLineTable();
742
743 // Emit the file names
744 Record.push_back(LineTable.getNumFilenames());
745 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
746 // Emit the file name
747 const char *Filename = LineTable.getFilename(I);
748 unsigned FilenameLen = Filename? strlen(Filename) : 0;
749 Record.push_back(FilenameLen);
750 if (FilenameLen)
751 Record.insert(Record.end(), Filename, Filename + FilenameLen);
752 }
753
754 // Emit the line entries
755 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
756 L != LEnd; ++L) {
757 // Emit the file ID
758 Record.push_back(L->first);
759
760 // Emit the line entries
761 Record.push_back(L->second.size());
762 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
763 LEEnd = L->second.end();
764 LE != LEEnd; ++LE) {
765 Record.push_back(LE->FileOffset);
766 Record.push_back(LE->LineNo);
767 Record.push_back(LE->FilenameID);
768 Record.push_back((unsigned)LE->FileKind);
769 Record.push_back(LE->IncludeOffset);
770 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000771 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000772 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000773 }
774
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000775 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000776 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000777 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000778 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
779 E = HS.header_file_end();
780 I != E; ++I) {
781 Record.push_back(I->isImport);
782 Record.push_back(I->DirInfo);
783 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000784 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000785 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
786 Record.clear();
787 }
788
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000789 // Write out the source location entry table. We skip the first
790 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000791 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000792 RecordData PreloadSLocs;
793 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
794 for (SourceManager::sloc_entry_iterator
795 SLoc = SourceMgr.sloc_entry_begin() + 1,
796 SLocEnd = SourceMgr.sloc_entry_end();
797 SLoc != SLocEnd; ++SLoc) {
798 // Record the offset of this source-location entry.
799 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
800
801 // Figure out which record code to use.
802 unsigned Code;
803 if (SLoc->isFile()) {
804 if (SLoc->getFile().getContentCache()->Entry)
805 Code = pch::SM_SLOC_FILE_ENTRY;
806 else
807 Code = pch::SM_SLOC_BUFFER_ENTRY;
808 } else
809 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
810 Record.clear();
811 Record.push_back(Code);
812
813 Record.push_back(SLoc->getOffset());
814 if (SLoc->isFile()) {
815 const SrcMgr::FileInfo &File = SLoc->getFile();
816 Record.push_back(File.getIncludeLoc().getRawEncoding());
817 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
818 Record.push_back(File.hasLineDirectives());
819
820 const SrcMgr::ContentCache *Content = File.getContentCache();
821 if (Content->Entry) {
822 // The source location entry is a file. The blob associated
823 // with this entry is the file name.
824 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
825 Content->Entry->getName(),
826 strlen(Content->Entry->getName()));
827
828 // FIXME: For now, preload all file source locations, so that
829 // we get the appropriate File entries in the reader. This is
830 // a temporary measure.
831 PreloadSLocs.push_back(SLocEntryOffsets.size());
832 } else {
833 // The source location entry is a buffer. The blob associated
834 // with this entry contains the contents of the buffer.
835
836 // We add one to the size so that we capture the trailing NULL
837 // that is required by llvm::MemoryBuffer::getMemBuffer (on
838 // the reader side).
839 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
840 const char *Name = Buffer->getBufferIdentifier();
841 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
842 Record.clear();
843 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
844 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
845 Buffer->getBufferStart(),
846 Buffer->getBufferSize() + 1);
847
848 if (strcmp(Name, "<built-in>") == 0)
849 PreloadSLocs.push_back(SLocEntryOffsets.size());
850 }
851 } else {
852 // The source location entry is an instantiation.
853 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
854 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
855 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
856 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
857
858 // Compute the token length for this macro expansion.
859 unsigned NextOffset = SourceMgr.getNextOffset();
860 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
861 if (++NextSLoc != SLocEnd)
862 NextOffset = NextSLoc->getOffset();
863 Record.push_back(NextOffset - SLoc->getOffset() - 1);
864 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
865 }
866 }
867
Douglas Gregorc9490c02009-04-16 22:23:12 +0000868 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000869
870 if (SLocEntryOffsets.empty())
871 return;
872
873 // Write the source-location offsets table into the PCH block. This
874 // table is used for lazily loading source-location information.
875 using namespace llvm;
876 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
877 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
879 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
881 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
882
883 Record.clear();
884 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
885 Record.push_back(SLocEntryOffsets.size());
886 Record.push_back(SourceMgr.getNextOffset());
887 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
888 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000889 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000890
891 // Write the source location entry preloads array, telling the PCH
892 // reader which source locations entries it should load eagerly.
893 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000894}
895
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000896//===----------------------------------------------------------------------===//
897// Preprocessor Serialization
898//===----------------------------------------------------------------------===//
899
Chris Lattner0b1fb982009-04-10 17:15:23 +0000900/// \brief Writes the block containing the serialized form of the
901/// preprocessor.
902///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000903void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000904 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000905
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000906 // If the preprocessor __COUNTER__ value has been bumped, remember it.
907 if (PP.getCounterValue() != 0) {
908 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000909 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000910 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000911 }
912
913 // Enter the preprocessor block.
914 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000915
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000916 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
917 // FIXME: use diagnostics subsystem for localization etc.
918 if (PP.SawDateOrTime())
919 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
920
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000921 // Loop over all the macro definitions that are live at the end of the file,
922 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000923 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
924 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000925 // FIXME: This emits macros in hash table order, we should do it in a stable
926 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000927 MacroInfo *MI = I->second;
928
929 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
930 // been redefined by the header (in which case they are not isBuiltinMacro).
931 if (MI->isBuiltinMacro())
932 continue;
933
Douglas Gregor37e26842009-04-21 23:56:24 +0000934 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000935 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000936 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000937 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
938 Record.push_back(MI->isUsed());
939
940 unsigned Code;
941 if (MI->isObjectLike()) {
942 Code = pch::PP_MACRO_OBJECT_LIKE;
943 } else {
944 Code = pch::PP_MACRO_FUNCTION_LIKE;
945
946 Record.push_back(MI->isC99Varargs());
947 Record.push_back(MI->isGNUVarargs());
948 Record.push_back(MI->getNumArgs());
949 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
950 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000951 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000952 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000953 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000954 Record.clear();
955
Chris Lattnerdf961c22009-04-10 18:08:30 +0000956 // Emit the tokens array.
957 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
958 // Note that we know that the preprocessor does not have any annotation
959 // tokens in it because they are created by the parser, and thus can't be
960 // in a macro definition.
961 const Token &Tok = MI->getReplacementToken(TokNo);
962
963 Record.push_back(Tok.getLocation().getRawEncoding());
964 Record.push_back(Tok.getLength());
965
Chris Lattnerdf961c22009-04-10 18:08:30 +0000966 // FIXME: When reading literal tokens, reconstruct the literal pointer if
967 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000968 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000969
970 // FIXME: Should translate token kind to a stable encoding.
971 Record.push_back(Tok.getKind());
972 // FIXME: Should translate token flags to a stable encoding.
973 Record.push_back(Tok.getFlags());
974
Douglas Gregorc9490c02009-04-16 22:23:12 +0000975 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000976 Record.clear();
977 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000978 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000979 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000980 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000981}
982
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000983//===----------------------------------------------------------------------===//
984// Type Serialization
985//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000986
Douglas Gregor2cf26342009-04-09 22:27:44 +0000987/// \brief Write the representation of a type to the PCH stream.
988void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000989 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000990 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000991 ID = NextTypeID++;
992
993 // Record the offset for this type.
994 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000995 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000996 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
997 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000998 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000999 }
1000
1001 RecordData Record;
1002
1003 // Emit the type's representation.
1004 PCHTypeWriter W(*this, Record);
1005 switch (T->getTypeClass()) {
1006 // For all of the concrete, non-dependent types, call the
1007 // appropriate visitor function.
1008#define TYPE(Class, Base) \
1009 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1010#define ABSTRACT_TYPE(Class, Base)
1011#define DEPENDENT_TYPE(Class, Base)
1012#include "clang/AST/TypeNodes.def"
1013
1014 // For all of the dependent type nodes (which only occur in C++
1015 // templates), produce an error.
1016#define TYPE(Class, Base)
1017#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1018#include "clang/AST/TypeNodes.def"
1019 assert(false && "Cannot serialize dependent type nodes");
1020 break;
1021 }
1022
1023 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001024 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001025
1026 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001027 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001028}
1029
1030/// \brief Write a block containing all of the types.
1031void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001032 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001033 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001034
Douglas Gregor366809a2009-04-26 03:49:13 +00001035 // Emit all of the types that need to be emitted (so far).
1036 while (!TypesToEmit.empty()) {
1037 const Type *T = TypesToEmit.front();
1038 TypesToEmit.pop();
1039 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1040 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001041 }
1042
1043 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001044 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001045}
1046
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001047//===----------------------------------------------------------------------===//
1048// Declaration Serialization
1049//===----------------------------------------------------------------------===//
1050
Douglas Gregor2cf26342009-04-09 22:27:44 +00001051/// \brief Write the block containing all of the declaration IDs
1052/// lexically declared within the given DeclContext.
1053///
1054/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1055/// bistream, or 0 if no block was written.
1056uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1057 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001058 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001059 return 0;
1060
Douglas Gregorc9490c02009-04-16 22:23:12 +00001061 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001062 RecordData Record;
1063 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1064 DEnd = DC->decls_end(Context);
1065 D != DEnd; ++D)
1066 AddDeclRef(*D, Record);
1067
Douglas Gregor25123082009-04-22 22:34:57 +00001068 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001069 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001070 return Offset;
1071}
1072
1073/// \brief Write the block containing all of the declaration IDs
1074/// visible from the given DeclContext.
1075///
1076/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1077/// bistream, or 0 if no block was written.
1078uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1079 DeclContext *DC) {
1080 if (DC->getPrimaryContext() != DC)
1081 return 0;
1082
Douglas Gregoraff22df2009-04-21 22:32:33 +00001083 // Since there is no name lookup into functions or methods, and we
1084 // perform name lookup for the translation unit via the
1085 // IdentifierInfo chains, don't bother to build a
1086 // visible-declarations table for these entities.
1087 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001088 return 0;
1089
Douglas Gregor2cf26342009-04-09 22:27:44 +00001090 // Force the DeclContext to build a its name-lookup table.
1091 DC->lookup(Context, DeclarationName());
1092
1093 // Serialize the contents of the mapping used for lookup. Note that,
1094 // although we have two very different code paths, the serialized
1095 // representation is the same for both cases: a declaration name,
1096 // followed by a size, followed by references to the visible
1097 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001098 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001099 RecordData Record;
1100 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001101 if (!Map)
1102 return 0;
1103
Douglas Gregor2cf26342009-04-09 22:27:44 +00001104 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1105 D != DEnd; ++D) {
1106 AddDeclarationName(D->first, Record);
1107 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1108 Record.push_back(Result.second - Result.first);
1109 for(; Result.first != Result.second; ++Result.first)
1110 AddDeclRef(*Result.first, Record);
1111 }
1112
1113 if (Record.size() == 0)
1114 return 0;
1115
Douglas Gregorc9490c02009-04-16 22:23:12 +00001116 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001117 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001118 return Offset;
1119}
1120
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001121//===----------------------------------------------------------------------===//
1122// Global Method Pool and Selector Serialization
1123//===----------------------------------------------------------------------===//
1124
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001125namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001126// Trait used for the on-disk hash table used in the method pool.
1127class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1128 PCHWriter &Writer;
1129
1130public:
1131 typedef Selector key_type;
1132 typedef key_type key_type_ref;
1133
1134 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1135 typedef const data_type& data_type_ref;
1136
1137 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1138
1139 static unsigned ComputeHash(Selector Sel) {
1140 unsigned N = Sel.getNumArgs();
1141 if (N == 0)
1142 ++N;
1143 unsigned R = 5381;
1144 for (unsigned I = 0; I != N; ++I)
1145 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1146 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1147 return R;
1148 }
1149
1150 std::pair<unsigned,unsigned>
1151 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1152 data_type_ref Methods) {
1153 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1154 clang::io::Emit16(Out, KeyLen);
1155 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1156 for (const ObjCMethodList *Method = &Methods.first; Method;
1157 Method = Method->Next)
1158 if (Method->Method)
1159 DataLen += 4;
1160 for (const ObjCMethodList *Method = &Methods.second; Method;
1161 Method = Method->Next)
1162 if (Method->Method)
1163 DataLen += 4;
1164 clang::io::Emit16(Out, DataLen);
1165 return std::make_pair(KeyLen, DataLen);
1166 }
1167
Douglas Gregor83941df2009-04-25 17:48:32 +00001168 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1169 uint64_t Start = Out.tell();
1170 assert((Start >> 32) == 0 && "Selector key offset too large");
1171 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001172 unsigned N = Sel.getNumArgs();
1173 clang::io::Emit16(Out, N);
1174 if (N == 0)
1175 N = 1;
1176 for (unsigned I = 0; I != N; ++I)
1177 clang::io::Emit32(Out,
1178 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1179 }
1180
1181 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001182 data_type_ref Methods, unsigned DataLen) {
1183 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001184 unsigned NumInstanceMethods = 0;
1185 for (const ObjCMethodList *Method = &Methods.first; Method;
1186 Method = Method->Next)
1187 if (Method->Method)
1188 ++NumInstanceMethods;
1189
1190 unsigned NumFactoryMethods = 0;
1191 for (const ObjCMethodList *Method = &Methods.second; Method;
1192 Method = Method->Next)
1193 if (Method->Method)
1194 ++NumFactoryMethods;
1195
1196 clang::io::Emit16(Out, NumInstanceMethods);
1197 clang::io::Emit16(Out, NumFactoryMethods);
1198 for (const ObjCMethodList *Method = &Methods.first; Method;
1199 Method = Method->Next)
1200 if (Method->Method)
1201 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001202 for (const ObjCMethodList *Method = &Methods.second; Method;
1203 Method = Method->Next)
1204 if (Method->Method)
1205 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001206
1207 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001208 }
1209};
1210} // end anonymous namespace
1211
1212/// \brief Write the method pool into the PCH file.
1213///
1214/// The method pool contains both instance and factory methods, stored
1215/// in an on-disk hash table indexed by the selector.
1216void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1217 using namespace llvm;
1218
1219 // Create and write out the blob that contains the instance and
1220 // factor method pools.
1221 bool Empty = true;
1222 {
1223 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1224
1225 // Create the on-disk hash table representation. Start by
1226 // iterating through the instance method pool.
1227 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001228 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001229 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1230 Instance = SemaRef.InstanceMethodPool.begin(),
1231 InstanceEnd = SemaRef.InstanceMethodPool.end();
1232 Instance != InstanceEnd; ++Instance) {
1233 // Check whether there is a factory method with the same
1234 // selector.
1235 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1236 = SemaRef.FactoryMethodPool.find(Instance->first);
1237
1238 if (Factory == SemaRef.FactoryMethodPool.end())
1239 Generator.insert(Instance->first,
1240 std::make_pair(Instance->second,
1241 ObjCMethodList()));
1242 else
1243 Generator.insert(Instance->first,
1244 std::make_pair(Instance->second, Factory->second));
1245
Douglas Gregor83941df2009-04-25 17:48:32 +00001246 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001247 Empty = false;
1248 }
1249
1250 // Now iterate through the factory method pool, to pick up any
1251 // selectors that weren't already in the instance method pool.
1252 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1253 Factory = SemaRef.FactoryMethodPool.begin(),
1254 FactoryEnd = SemaRef.FactoryMethodPool.end();
1255 Factory != FactoryEnd; ++Factory) {
1256 // Check whether there is an instance method with the same
1257 // selector. If so, there is no work to do here.
1258 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1259 = SemaRef.InstanceMethodPool.find(Factory->first);
1260
Douglas Gregor83941df2009-04-25 17:48:32 +00001261 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001262 Generator.insert(Factory->first,
1263 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001264 ++NumSelectorsInMethodPool;
1265 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001266
1267 Empty = false;
1268 }
1269
Douglas Gregor83941df2009-04-25 17:48:32 +00001270 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001271 return;
1272
1273 // Create the on-disk hash table in a buffer.
1274 llvm::SmallVector<char, 4096> MethodPool;
1275 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001276 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001277 {
1278 PCHMethodPoolTrait Trait(*this);
1279 llvm::raw_svector_ostream Out(MethodPool);
1280 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001281 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001282 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001283
1284 // For every selector that we have seen but which was not
1285 // written into the hash table, write the selector itself and
1286 // record it's offset.
1287 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1288 if (SelectorOffsets[I] == 0)
1289 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001290 }
1291
1292 // Create a blob abbreviation
1293 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1294 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1295 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001296 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001297 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1298 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1299
Douglas Gregor83941df2009-04-25 17:48:32 +00001300 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001301 RecordData Record;
1302 Record.push_back(pch::METHOD_POOL);
1303 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001304 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001305 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1306 &MethodPool.front(),
1307 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001308
1309 // Create a blob abbreviation for the selector table offsets.
1310 Abbrev = new BitCodeAbbrev();
1311 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1312 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1313 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1314 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1315
1316 // Write the selector offsets table.
1317 Record.clear();
1318 Record.push_back(pch::SELECTOR_OFFSETS);
1319 Record.push_back(SelectorOffsets.size());
1320 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1321 (const char *)&SelectorOffsets.front(),
1322 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001323 }
1324}
1325
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001326//===----------------------------------------------------------------------===//
1327// Identifier Table Serialization
1328//===----------------------------------------------------------------------===//
1329
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001330namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001331class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1332 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001333 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001334
Douglas Gregora92193e2009-04-28 21:18:29 +00001335 /// \brief Determines whether this is an "interesting" identifier
1336 /// that needs a full IdentifierInfo structure written into the hash
1337 /// table.
1338 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1339 return II->isPoisoned() ||
1340 II->isExtensionToken() ||
1341 II->hasMacroDefinition() ||
1342 II->getObjCOrBuiltinID() ||
1343 II->getFETokenInfo<void>();
1344 }
1345
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001346public:
1347 typedef const IdentifierInfo* key_type;
1348 typedef key_type key_type_ref;
1349
1350 typedef pch::IdentID data_type;
1351 typedef data_type data_type_ref;
1352
Douglas Gregor37e26842009-04-21 23:56:24 +00001353 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1354 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001355
1356 static unsigned ComputeHash(const IdentifierInfo* II) {
1357 return clang::BernsteinHash(II->getName());
1358 }
1359
Douglas Gregor37e26842009-04-21 23:56:24 +00001360 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001361 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1362 pch::IdentID ID) {
1363 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001364 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1365 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001366 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001367 if (II->hasMacroDefinition() &&
1368 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001369 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001370 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1371 DEnd = IdentifierResolver::end();
1372 D != DEnd; ++D)
1373 DataLen += sizeof(pch::DeclID);
1374 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001375 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001376 // We emit the key length after the data length so that every
1377 // string is preceded by a 16-bit length. This matches the PTH
1378 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001379 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001380 return std::make_pair(KeyLen, DataLen);
1381 }
1382
1383 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1384 unsigned KeyLen) {
1385 // Record the location of the key data. This is used when generating
1386 // the mapping from persistent IDs to strings.
1387 Writer.SetIdentifierOffset(II, Out.tell());
1388 Out.write(II->getName(), KeyLen);
1389 }
1390
1391 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1392 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001393 if (!isInterestingIdentifier(II)) {
1394 clang::io::Emit32(Out, ID << 1);
1395 return;
1396 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001397
Douglas Gregora92193e2009-04-28 21:18:29 +00001398 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001399 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001400 bool hasMacroDefinition =
1401 II->hasMacroDefinition() &&
1402 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001403 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001404 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001405 Bits = (Bits << 1) | II->isExtensionToken();
1406 Bits = (Bits << 1) | II->isPoisoned();
1407 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001408 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001409
Douglas Gregor37e26842009-04-21 23:56:24 +00001410 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001411 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001412
Douglas Gregor668c1a42009-04-21 22:25:48 +00001413 // Emit the declaration IDs in reverse order, because the
1414 // IdentifierResolver provides the declarations as they would be
1415 // visible (e.g., the function "stat" would come before the struct
1416 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1417 // adds declarations to the end of the list (so we need to see the
1418 // struct "status" before the function "status").
1419 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1420 IdentifierResolver::end());
1421 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1422 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001423 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001424 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001425 }
1426};
1427} // end anonymous namespace
1428
Douglas Gregorafaf3082009-04-11 00:14:32 +00001429/// \brief Write the identifier table into the PCH file.
1430///
1431/// The identifier table consists of a blob containing string data
1432/// (the actual identifiers themselves) and a separate "offsets" index
1433/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001434void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001435 using namespace llvm;
1436
1437 // Create and write out the blob that contains the identifier
1438 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001439 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001440 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1441
Douglas Gregor92b059e2009-04-28 20:33:11 +00001442 // Look for any identifiers that were named while processing the
1443 // headers, but are otherwise not needed. We add these to the hash
1444 // table to enable checking of the predefines buffer in the case
1445 // where the user adds new macro definitions when building the PCH
1446 // file.
1447 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1448 IDEnd = PP.getIdentifierTable().end();
1449 ID != IDEnd; ++ID)
1450 getIdentifierRef(ID->second);
1451
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001452 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001453 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001454 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1455 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1456 ID != IDEnd; ++ID) {
1457 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001458 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001459 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001460
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001461 // Create the on-disk hash table in a buffer.
1462 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001463 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001464 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001465 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001466 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001467 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001468 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001469 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001470 }
1471
1472 // Create a blob abbreviation
1473 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1474 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001475 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001476 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001477 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001478
1479 // Write the identifier table
1480 RecordData Record;
1481 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001482 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001483 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1484 &IdentifierTable.front(),
1485 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001486 }
1487
1488 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001489 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1490 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1491 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1492 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1493 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1494
1495 RecordData Record;
1496 Record.push_back(pch::IDENTIFIER_OFFSET);
1497 Record.push_back(IdentifierOffsets.size());
1498 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1499 (const char *)&IdentifierOffsets.front(),
1500 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001501}
1502
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001503//===----------------------------------------------------------------------===//
1504// General Serialization Routines
1505//===----------------------------------------------------------------------===//
1506
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001507/// \brief Write a record containing the given attributes.
1508void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1509 RecordData Record;
1510 for (; Attr; Attr = Attr->getNext()) {
1511 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1512 Record.push_back(Attr->isInherited());
1513 switch (Attr->getKind()) {
1514 case Attr::Alias:
1515 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1516 break;
1517
1518 case Attr::Aligned:
1519 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1520 break;
1521
1522 case Attr::AlwaysInline:
1523 break;
1524
1525 case Attr::AnalyzerNoReturn:
1526 break;
1527
1528 case Attr::Annotate:
1529 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1530 break;
1531
1532 case Attr::AsmLabel:
1533 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1534 break;
1535
1536 case Attr::Blocks:
1537 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1538 break;
1539
1540 case Attr::Cleanup:
1541 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1542 break;
1543
1544 case Attr::Const:
1545 break;
1546
1547 case Attr::Constructor:
1548 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1549 break;
1550
1551 case Attr::DLLExport:
1552 case Attr::DLLImport:
1553 case Attr::Deprecated:
1554 break;
1555
1556 case Attr::Destructor:
1557 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1558 break;
1559
1560 case Attr::FastCall:
1561 break;
1562
1563 case Attr::Format: {
1564 const FormatAttr *Format = cast<FormatAttr>(Attr);
1565 AddString(Format->getType(), Record);
1566 Record.push_back(Format->getFormatIdx());
1567 Record.push_back(Format->getFirstArg());
1568 break;
1569 }
1570
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001571 case Attr::FormatArg: {
1572 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1573 Record.push_back(Format->getFormatIdx());
1574 break;
1575 }
1576
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001577 case Attr::Sentinel : {
1578 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1579 Record.push_back(Sentinel->getSentinel());
1580 Record.push_back(Sentinel->getNullPos());
1581 break;
1582 }
1583
Chris Lattnercf2a7212009-04-20 19:12:28 +00001584 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001585 case Attr::IBOutletKind:
1586 case Attr::NoReturn:
1587 case Attr::NoThrow:
1588 case Attr::Nodebug:
1589 case Attr::Noinline:
1590 break;
1591
1592 case Attr::NonNull: {
1593 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1594 Record.push_back(NonNull->size());
1595 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1596 break;
1597 }
1598
1599 case Attr::ObjCException:
1600 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001601 case Attr::CFReturnsRetained:
1602 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001603 case Attr::Overloadable:
1604 break;
1605
1606 case Attr::Packed:
1607 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1608 break;
1609
1610 case Attr::Pure:
1611 break;
1612
1613 case Attr::Regparm:
1614 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1615 break;
1616
1617 case Attr::Section:
1618 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1619 break;
1620
1621 case Attr::StdCall:
1622 case Attr::TransparentUnion:
1623 case Attr::Unavailable:
1624 case Attr::Unused:
1625 case Attr::Used:
1626 break;
1627
1628 case Attr::Visibility:
1629 // FIXME: stable encoding
1630 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1631 break;
1632
1633 case Attr::WarnUnusedResult:
1634 case Attr::Weak:
1635 case Attr::WeakImport:
1636 break;
1637 }
1638 }
1639
Douglas Gregorc9490c02009-04-16 22:23:12 +00001640 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001641}
1642
1643void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1644 Record.push_back(Str.size());
1645 Record.insert(Record.end(), Str.begin(), Str.end());
1646}
1647
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001648/// \brief Note that the identifier II occurs at the given offset
1649/// within the identifier table.
1650void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001651 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001652}
1653
Douglas Gregor83941df2009-04-25 17:48:32 +00001654/// \brief Note that the selector Sel occurs at the given offset
1655/// within the method pool/selector table.
1656void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1657 unsigned ID = SelectorIDs[Sel];
1658 assert(ID && "Unknown selector");
1659 SelectorOffsets[ID - 1] = Offset;
1660}
1661
Douglas Gregorc9490c02009-04-16 22:23:12 +00001662PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001663 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001664 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1665 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001666
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001667void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001668 using namespace llvm;
1669
Douglas Gregore7785042009-04-20 15:53:59 +00001670 ASTContext &Context = SemaRef.Context;
1671 Preprocessor &PP = SemaRef.PP;
1672
Douglas Gregor2cf26342009-04-09 22:27:44 +00001673 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001674 Stream.Emit((unsigned)'C', 8);
1675 Stream.Emit((unsigned)'P', 8);
1676 Stream.Emit((unsigned)'C', 8);
1677 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001678
1679 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001680
1681 // The translation unit is the first declaration we'll emit.
1682 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1683 DeclsToEmit.push(Context.getTranslationUnitDecl());
1684
Douglas Gregor2deaea32009-04-22 18:49:13 +00001685 // Make sure that we emit IdentifierInfos (and any attached
1686 // declarations) for builtins.
1687 {
1688 IdentifierTable &Table = PP.getIdentifierTable();
1689 llvm::SmallVector<const char *, 32> BuiltinNames;
1690 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1691 Context.getLangOptions().NoBuiltin);
1692 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1693 getIdentifierRef(&Table.get(BuiltinNames[I]));
1694 }
1695
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001696 // Build a record containing all of the tentative definitions in
1697 // this header file. Generally, this record will be empty.
1698 RecordData TentativeDefinitions;
1699 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1700 TD = SemaRef.TentativeDefinitions.begin(),
1701 TDEnd = SemaRef.TentativeDefinitions.end();
1702 TD != TDEnd; ++TD)
1703 AddDeclRef(TD->second, TentativeDefinitions);
1704
Douglas Gregor14c22f22009-04-22 22:18:58 +00001705 // Build a record containing all of the locally-scoped external
1706 // declarations in this header file. Generally, this record will be
1707 // empty.
1708 RecordData LocallyScopedExternalDecls;
1709 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1710 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1711 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1712 TD != TDEnd; ++TD)
1713 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1714
Douglas Gregorb81c1702009-04-27 20:06:05 +00001715 // Build a record containing all of the ext_vector declarations.
1716 RecordData ExtVectorDecls;
1717 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1718 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1719
1720 // Build a record containing all of the Objective-C category
1721 // implementations.
1722 RecordData ObjCCategoryImpls;
1723 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1724 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1725
Douglas Gregor2cf26342009-04-09 22:27:44 +00001726 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001727 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001728 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001729 WriteMetadata(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001730 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001731 if (StatCalls)
1732 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001733 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001734 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001735
1736 // Keep writing types and declarations until all types and
1737 // declarations have been written.
1738 do {
1739 if (!DeclsToEmit.empty())
1740 WriteDeclsBlock(Context);
1741 if (!TypesToEmit.empty())
1742 WriteTypesBlock(Context);
1743 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1744
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001745 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001746 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001747
1748 // Write the type offsets array
1749 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1750 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1753 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1754 Record.clear();
1755 Record.push_back(pch::TYPE_OFFSET);
1756 Record.push_back(TypeOffsets.size());
1757 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1758 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001759 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001760
1761 // Write the declaration offsets array
1762 Abbrev = new BitCodeAbbrev();
1763 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1764 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1765 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1766 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1767 Record.clear();
1768 Record.push_back(pch::DECL_OFFSET);
1769 Record.push_back(DeclOffsets.size());
1770 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1771 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001772 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001773
1774 // Write the record of special types.
1775 Record.clear();
1776 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001777 AddTypeRef(Context.getObjCIdType(), Record);
1778 AddTypeRef(Context.getObjCSelType(), Record);
1779 AddTypeRef(Context.getObjCProtoType(), Record);
1780 AddTypeRef(Context.getObjCClassType(), Record);
1781 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1782 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001783 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1784
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001785 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001786 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001787 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001788
1789 // Write the record containing tentative definitions.
1790 if (!TentativeDefinitions.empty())
1791 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001792
1793 // Write the record containing locally-scoped external definitions.
1794 if (!LocallyScopedExternalDecls.empty())
1795 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1796 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001797
1798 // Write the record containing ext_vector type names.
1799 if (!ExtVectorDecls.empty())
1800 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1801
1802 // Write the record containing Objective-C category implementations.
1803 if (!ObjCCategoryImpls.empty())
1804 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001805
1806 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001807 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001808 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001809 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001810 Record.push_back(NumLexicalDeclContexts);
1811 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001812 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001813 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001814}
1815
1816void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1817 Record.push_back(Loc.getRawEncoding());
1818}
1819
1820void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1821 Record.push_back(Value.getBitWidth());
1822 unsigned N = Value.getNumWords();
1823 const uint64_t* Words = Value.getRawData();
1824 for (unsigned I = 0; I != N; ++I)
1825 Record.push_back(Words[I]);
1826}
1827
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001828void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1829 Record.push_back(Value.isUnsigned());
1830 AddAPInt(Value, Record);
1831}
1832
Douglas Gregor17fc2232009-04-14 21:55:33 +00001833void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1834 AddAPInt(Value.bitcastToAPInt(), Record);
1835}
1836
Douglas Gregor2cf26342009-04-09 22:27:44 +00001837void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001838 Record.push_back(getIdentifierRef(II));
1839}
1840
1841pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1842 if (II == 0)
1843 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001844
1845 pch::IdentID &ID = IdentifierIDs[II];
1846 if (ID == 0)
1847 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001848 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001849}
1850
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001851void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1852 if (SelRef.getAsOpaquePtr() == 0) {
1853 Record.push_back(0);
1854 return;
1855 }
1856
1857 pch::SelectorID &SID = SelectorIDs[SelRef];
1858 if (SID == 0) {
1859 SID = SelectorIDs.size();
1860 SelVector.push_back(SelRef);
1861 }
1862 Record.push_back(SID);
1863}
1864
Douglas Gregor2cf26342009-04-09 22:27:44 +00001865void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1866 if (T.isNull()) {
1867 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1868 return;
1869 }
1870
1871 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001872 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001873 switch (BT->getKind()) {
1874 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1875 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1876 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1877 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1878 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1879 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1880 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1881 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001882 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001883 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1884 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1885 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1886 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1887 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1888 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1889 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001890 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001891 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1892 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1893 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001894 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001895 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1896 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1897 }
1898
1899 Record.push_back((ID << 3) | T.getCVRQualifiers());
1900 return;
1901 }
1902
Douglas Gregor8038d512009-04-10 17:25:41 +00001903 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001904 if (ID == 0) {
1905 // We haven't seen this type before. Assign it a new ID and put it
1906 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001907 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001908 TypesToEmit.push(T.getTypePtr());
1909 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001910
1911 // Encode the type qualifiers in the type reference.
1912 Record.push_back((ID << 3) | T.getCVRQualifiers());
1913}
1914
1915void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1916 if (D == 0) {
1917 Record.push_back(0);
1918 return;
1919 }
1920
Douglas Gregor8038d512009-04-10 17:25:41 +00001921 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001922 if (ID == 0) {
1923 // We haven't seen this declaration before. Give it a new ID and
1924 // enqueue it in the list of declarations to emit.
1925 ID = DeclIDs.size();
1926 DeclsToEmit.push(const_cast<Decl *>(D));
1927 }
1928
1929 Record.push_back(ID);
1930}
1931
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001932pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1933 if (D == 0)
1934 return 0;
1935
1936 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1937 return DeclIDs[D];
1938}
1939
Douglas Gregor2cf26342009-04-09 22:27:44 +00001940void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001941 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001942 Record.push_back(Name.getNameKind());
1943 switch (Name.getNameKind()) {
1944 case DeclarationName::Identifier:
1945 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1946 break;
1947
1948 case DeclarationName::ObjCZeroArgSelector:
1949 case DeclarationName::ObjCOneArgSelector:
1950 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001951 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001952 break;
1953
1954 case DeclarationName::CXXConstructorName:
1955 case DeclarationName::CXXDestructorName:
1956 case DeclarationName::CXXConversionFunctionName:
1957 AddTypeRef(Name.getCXXNameType(), Record);
1958 break;
1959
1960 case DeclarationName::CXXOperatorName:
1961 Record.push_back(Name.getCXXOverloadedOperator());
1962 break;
1963
1964 case DeclarationName::CXXUsingDirective:
1965 // No extra data to emit
1966 break;
1967 }
1968}
Douglas Gregor0b748912009-04-14 21:18:50 +00001969