blob: e05a73568f4ec0683f476289ea053e04e4e04e3c [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());
165 Code = pch::TYPE_FUNCTION_PROTO;
166}
167
168void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
169 Writer.AddDeclRef(T->getDecl(), Record);
170 Code = pch::TYPE_TYPEDEF;
171}
172
173void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000174 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000175 Code = pch::TYPE_TYPEOF_EXPR;
176}
177
178void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
179 Writer.AddTypeRef(T->getUnderlyingType(), Record);
180 Code = pch::TYPE_TYPEOF;
181}
182
183void PCHTypeWriter::VisitTagType(const TagType *T) {
184 Writer.AddDeclRef(T->getDecl(), Record);
185 assert(!T->isBeingDefined() &&
186 "Cannot serialize in the middle of a type definition");
187}
188
189void PCHTypeWriter::VisitRecordType(const RecordType *T) {
190 VisitTagType(T);
191 Code = pch::TYPE_RECORD;
192}
193
194void PCHTypeWriter::VisitEnumType(const EnumType *T) {
195 VisitTagType(T);
196 Code = pch::TYPE_ENUM;
197}
198
199void
200PCHTypeWriter::VisitTemplateSpecializationType(
201 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000202 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000203 assert(false && "Cannot serialize template specialization types");
204}
205
206void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *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 qualified name types");
209}
210
211void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
212 Writer.AddDeclRef(T->getDecl(), Record);
213 Code = pch::TYPE_OBJC_INTERFACE;
214}
215
216void
217PCHTypeWriter::VisitObjCQualifiedInterfaceType(
218 const ObjCQualifiedInterfaceType *T) {
219 VisitObjCInterfaceType(T);
220 Record.push_back(T->getNumProtocols());
221 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
222 Writer.AddDeclRef(T->getProtocol(I), Record);
223 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
224}
225
226void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
227 Record.push_back(T->getNumProtocols());
228 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
229 Writer.AddDeclRef(T->getProtocols(I), Record);
230 Code = pch::TYPE_OBJC_QUALIFIED_ID;
231}
232
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000233//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000234// PCHWriter Implementation
235//===----------------------------------------------------------------------===//
236
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000237static void EmitBlockID(unsigned ID, const char *Name,
238 llvm::BitstreamWriter &Stream,
239 PCHWriter::RecordData &Record) {
240 Record.clear();
241 Record.push_back(ID);
242 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
243
244 // Emit the block name if present.
245 if (Name == 0 || Name[0] == 0) return;
246 Record.clear();
247 while (*Name)
248 Record.push_back(*Name++);
249 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
250}
251
252static void EmitRecordID(unsigned ID, const char *Name,
253 llvm::BitstreamWriter &Stream,
254 PCHWriter::RecordData &Record) {
255 Record.clear();
256 Record.push_back(ID);
257 while (*Name)
258 Record.push_back(*Name++);
259 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000260}
261
262static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
263 PCHWriter::RecordData &Record) {
264#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
265 RECORD(STMT_STOP);
266 RECORD(STMT_NULL_PTR);
267 RECORD(STMT_NULL);
268 RECORD(STMT_COMPOUND);
269 RECORD(STMT_CASE);
270 RECORD(STMT_DEFAULT);
271 RECORD(STMT_LABEL);
272 RECORD(STMT_IF);
273 RECORD(STMT_SWITCH);
274 RECORD(STMT_WHILE);
275 RECORD(STMT_DO);
276 RECORD(STMT_FOR);
277 RECORD(STMT_GOTO);
278 RECORD(STMT_INDIRECT_GOTO);
279 RECORD(STMT_CONTINUE);
280 RECORD(STMT_BREAK);
281 RECORD(STMT_RETURN);
282 RECORD(STMT_DECL);
283 RECORD(STMT_ASM);
284 RECORD(EXPR_PREDEFINED);
285 RECORD(EXPR_DECL_REF);
286 RECORD(EXPR_INTEGER_LITERAL);
287 RECORD(EXPR_FLOATING_LITERAL);
288 RECORD(EXPR_IMAGINARY_LITERAL);
289 RECORD(EXPR_STRING_LITERAL);
290 RECORD(EXPR_CHARACTER_LITERAL);
291 RECORD(EXPR_PAREN);
292 RECORD(EXPR_UNARY_OPERATOR);
293 RECORD(EXPR_SIZEOF_ALIGN_OF);
294 RECORD(EXPR_ARRAY_SUBSCRIPT);
295 RECORD(EXPR_CALL);
296 RECORD(EXPR_MEMBER);
297 RECORD(EXPR_BINARY_OPERATOR);
298 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
299 RECORD(EXPR_CONDITIONAL_OPERATOR);
300 RECORD(EXPR_IMPLICIT_CAST);
301 RECORD(EXPR_CSTYLE_CAST);
302 RECORD(EXPR_COMPOUND_LITERAL);
303 RECORD(EXPR_EXT_VECTOR_ELEMENT);
304 RECORD(EXPR_INIT_LIST);
305 RECORD(EXPR_DESIGNATED_INIT);
306 RECORD(EXPR_IMPLICIT_VALUE_INIT);
307 RECORD(EXPR_VA_ARG);
308 RECORD(EXPR_ADDR_LABEL);
309 RECORD(EXPR_STMT);
310 RECORD(EXPR_TYPES_COMPATIBLE);
311 RECORD(EXPR_CHOOSE);
312 RECORD(EXPR_GNU_NULL);
313 RECORD(EXPR_SHUFFLE_VECTOR);
314 RECORD(EXPR_BLOCK);
315 RECORD(EXPR_BLOCK_DECL_REF);
316 RECORD(EXPR_OBJC_STRING_LITERAL);
317 RECORD(EXPR_OBJC_ENCODE);
318 RECORD(EXPR_OBJC_SELECTOR_EXPR);
319 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
320 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
321 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
322 RECORD(EXPR_OBJC_KVC_REF_EXPR);
323 RECORD(EXPR_OBJC_MESSAGE_EXPR);
324 RECORD(EXPR_OBJC_SUPER_EXPR);
325 RECORD(STMT_OBJC_FOR_COLLECTION);
326 RECORD(STMT_OBJC_CATCH);
327 RECORD(STMT_OBJC_FINALLY);
328 RECORD(STMT_OBJC_AT_TRY);
329 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
330 RECORD(STMT_OBJC_AT_THROW);
331#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000332}
333
334void PCHWriter::WriteBlockInfoBlock() {
335 RecordData Record;
336 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
337
Chris Lattner2f4efd12009-04-27 00:40:25 +0000338#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000339#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
340
341 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000342 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000343 RECORD(TYPE_OFFSET);
344 RECORD(DECL_OFFSET);
345 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000346 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000347 RECORD(IDENTIFIER_OFFSET);
348 RECORD(IDENTIFIER_TABLE);
349 RECORD(EXTERNAL_DEFINITIONS);
350 RECORD(SPECIAL_TYPES);
351 RECORD(STATISTICS);
352 RECORD(TENTATIVE_DEFINITIONS);
353 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
354 RECORD(SELECTOR_OFFSETS);
355 RECORD(METHOD_POOL);
356 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000357 RECORD(SOURCE_LOCATION_OFFSETS);
358 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000359 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000360 RECORD(EXT_VECTOR_DECLS);
361 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000362
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000363 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000364 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000365 RECORD(SM_SLOC_FILE_ENTRY);
366 RECORD(SM_SLOC_BUFFER_ENTRY);
367 RECORD(SM_SLOC_BUFFER_BLOB);
368 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
369 RECORD(SM_LINE_TABLE);
370 RECORD(SM_HEADER_FILE_INFO);
371
372 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000373 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000374 RECORD(PP_MACRO_OBJECT_LIKE);
375 RECORD(PP_MACRO_FUNCTION_LIKE);
376 RECORD(PP_TOKEN);
377
378 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000379 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000380 RECORD(TYPE_EXT_QUAL);
381 RECORD(TYPE_FIXED_WIDTH_INT);
382 RECORD(TYPE_COMPLEX);
383 RECORD(TYPE_POINTER);
384 RECORD(TYPE_BLOCK_POINTER);
385 RECORD(TYPE_LVALUE_REFERENCE);
386 RECORD(TYPE_RVALUE_REFERENCE);
387 RECORD(TYPE_MEMBER_POINTER);
388 RECORD(TYPE_CONSTANT_ARRAY);
389 RECORD(TYPE_INCOMPLETE_ARRAY);
390 RECORD(TYPE_VARIABLE_ARRAY);
391 RECORD(TYPE_VECTOR);
392 RECORD(TYPE_EXT_VECTOR);
393 RECORD(TYPE_FUNCTION_PROTO);
394 RECORD(TYPE_FUNCTION_NO_PROTO);
395 RECORD(TYPE_TYPEDEF);
396 RECORD(TYPE_TYPEOF_EXPR);
397 RECORD(TYPE_TYPEOF);
398 RECORD(TYPE_RECORD);
399 RECORD(TYPE_ENUM);
400 RECORD(TYPE_OBJC_INTERFACE);
401 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
402 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000403 // Statements and Exprs can occur in the Types block.
404 AddStmtsExprs(Stream, Record);
405
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000406 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000407 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000408 RECORD(DECL_ATTR);
409 RECORD(DECL_TRANSLATION_UNIT);
410 RECORD(DECL_TYPEDEF);
411 RECORD(DECL_ENUM);
412 RECORD(DECL_RECORD);
413 RECORD(DECL_ENUM_CONSTANT);
414 RECORD(DECL_FUNCTION);
415 RECORD(DECL_OBJC_METHOD);
416 RECORD(DECL_OBJC_INTERFACE);
417 RECORD(DECL_OBJC_PROTOCOL);
418 RECORD(DECL_OBJC_IVAR);
419 RECORD(DECL_OBJC_AT_DEFS_FIELD);
420 RECORD(DECL_OBJC_CLASS);
421 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
422 RECORD(DECL_OBJC_CATEGORY);
423 RECORD(DECL_OBJC_CATEGORY_IMPL);
424 RECORD(DECL_OBJC_IMPLEMENTATION);
425 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
426 RECORD(DECL_OBJC_PROPERTY);
427 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000428 RECORD(DECL_FIELD);
429 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000430 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000431 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000432 RECORD(DECL_ORIGINAL_PARM_VAR);
433 RECORD(DECL_FILE_SCOPE_ASM);
434 RECORD(DECL_BLOCK);
435 RECORD(DECL_CONTEXT_LEXICAL);
436 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000437 // Statements and Exprs can occur in the Decls block.
438 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000439#undef RECORD
440#undef BLOCK
441 Stream.ExitBlock();
442}
443
444
Douglas Gregorab41e632009-04-27 22:23:34 +0000445/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregorb64c1932009-05-12 01:31:05 +0000446void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000447 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000448
449 // Original file name
450 SourceManager &SM = Context.getSourceManager();
451 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
452 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
453 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
454 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
455 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
456
457 llvm::sys::Path MainFilePath(MainFile->getName());
458 std::string MainFileName;
459
460 if (!MainFilePath.isAbsolute()) {
461 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
462 P.appendComponent(MainFilePath.toString());
463 MainFileName = P.toString();
464 } else {
465 MainFileName = MainFilePath.toString();
466 }
467
468 RecordData Record;
469 Record.push_back(pch::ORIGINAL_FILE_NAME);
470 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
471 MainFileName.size());
472 }
473
474 // Metadata
475 const TargetInfo &Target = Context.Target;
476 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
477 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
478 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
479 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
480 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
481 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
482 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
483 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000484
485 RecordData Record;
Douglas Gregorab41e632009-04-27 22:23:34 +0000486 Record.push_back(pch::METADATA);
487 Record.push_back(pch::VERSION_MAJOR);
488 Record.push_back(pch::VERSION_MINOR);
489 Record.push_back(CLANG_VERSION_MAJOR);
490 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000491 const char *Triple = Target.getTargetTriple();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000492 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000493}
494
495/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000496void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
497 RecordData Record;
498 Record.push_back(LangOpts.Trigraphs);
499 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
500 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
501 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
502 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
503 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
504 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
505 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
506 Record.push_back(LangOpts.C99); // C99 Support
507 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
508 Record.push_back(LangOpts.CPlusPlus); // C++ Support
509 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000510 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
511
512 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
513 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
514 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
515
516 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000517 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
518 Record.push_back(LangOpts.LaxVectorConversions);
519 Record.push_back(LangOpts.Exceptions); // Support exception handling.
520
521 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
522 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
523 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
524
Chris Lattnerea5ce472009-04-27 07:35:58 +0000525 // Whether static initializers are protected by locks.
526 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000527 Record.push_back(LangOpts.Blocks); // block extension to C
528 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
529 // they are unused.
530 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
531 // (modulo the platform support).
532
533 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
534 // signed integer arithmetic overflows.
535
536 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
537 // may be ripped out at any time.
538
539 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
540 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
541 // defined.
542 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
543 // opposed to __DYNAMIC__).
544 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
545
546 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
547 // used (instead of C99 semantics).
548 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
549 Record.push_back(LangOpts.getGCMode());
550 Record.push_back(LangOpts.getVisibilityMode());
551 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000552 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000553}
554
Douglas Gregor14f79002009-04-10 03:52:48 +0000555//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000556// stat cache Serialization
557//===----------------------------------------------------------------------===//
558
559namespace {
560// Trait used for the on-disk hash table of stat cache results.
561class VISIBILITY_HIDDEN PCHStatCacheTrait {
562public:
563 typedef const char * key_type;
564 typedef key_type key_type_ref;
565
566 typedef std::pair<int, struct stat> data_type;
567 typedef const data_type& data_type_ref;
568
569 static unsigned ComputeHash(const char *path) {
570 return BernsteinHash(path);
571 }
572
573 std::pair<unsigned,unsigned>
574 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
575 data_type_ref Data) {
576 unsigned StrLen = strlen(path);
577 clang::io::Emit16(Out, StrLen);
578 unsigned DataLen = 1; // result value
579 if (Data.first == 0)
580 DataLen += 4 + 4 + 2 + 8 + 8;
581 clang::io::Emit8(Out, DataLen);
582 return std::make_pair(StrLen + 1, DataLen);
583 }
584
585 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
586 Out.write(path, KeyLen);
587 }
588
589 void EmitData(llvm::raw_ostream& Out, key_type_ref,
590 data_type_ref Data, unsigned DataLen) {
591 using namespace clang::io;
592 uint64_t Start = Out.tell(); (void)Start;
593
594 // Result of stat()
595 Emit8(Out, Data.first? 1 : 0);
596
597 if (Data.first == 0) {
598 Emit32(Out, (uint32_t) Data.second.st_ino);
599 Emit32(Out, (uint32_t) Data.second.st_dev);
600 Emit16(Out, (uint16_t) Data.second.st_mode);
601 Emit64(Out, (uint64_t) Data.second.st_mtime);
602 Emit64(Out, (uint64_t) Data.second.st_size);
603 }
604
605 assert(Out.tell() - Start == DataLen && "Wrong data length");
606 }
607};
608} // end anonymous namespace
609
610/// \brief Write the stat() system call cache to the PCH file.
611void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
612 // Build the on-disk hash table containing information about every
613 // stat() call.
614 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
615 unsigned NumStatEntries = 0;
616 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
617 StatEnd = StatCalls.end();
618 Stat != StatEnd; ++Stat, ++NumStatEntries)
619 Generator.insert(Stat->first(), Stat->second);
620
621 // Create the on-disk hash table in a buffer.
622 llvm::SmallVector<char, 4096> StatCacheData;
623 uint32_t BucketOffset;
624 {
625 llvm::raw_svector_ostream Out(StatCacheData);
626 // Make sure that no bucket is at offset 0
627 clang::io::Emit32(Out, 0);
628 BucketOffset = Generator.Emit(Out);
629 }
630
631 // Create a blob abbreviation
632 using namespace llvm;
633 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
634 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
638 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
639
640 // Write the stat cache
641 RecordData Record;
642 Record.push_back(pch::STAT_CACHE);
643 Record.push_back(BucketOffset);
644 Record.push_back(NumStatEntries);
645 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
646 &StatCacheData.front(),
647 StatCacheData.size());
648}
649
650//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000651// Source Manager Serialization
652//===----------------------------------------------------------------------===//
653
654/// \brief Create an abbreviation for the SLocEntry that refers to a
655/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000656static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000657 using namespace llvm;
658 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
659 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000665 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000666}
667
668/// \brief Create an abbreviation for the SLocEntry that refers to a
669/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000670static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000671 using namespace llvm;
672 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
673 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
674 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
675 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000679 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000680}
681
682/// \brief Create an abbreviation for the SLocEntry that refers to a
683/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000684static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000685 using namespace llvm;
686 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
687 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
688 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000689 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000690}
691
692/// \brief Create an abbreviation for the SLocEntry that refers to an
693/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000694static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000695 using namespace llvm;
696 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
697 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
701 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000703 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000704}
705
706/// \brief Writes the block containing the serialized form of the
707/// source manager.
708///
709/// TODO: We should probably use an on-disk hash table (stored in a
710/// blob), indexed based on the file name, so that we only create
711/// entries for files that we actually need. In the common case (no
712/// errors), we probably won't have to create file entries for any of
713/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000714void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
715 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000716 RecordData Record;
717
Chris Lattnerf04ad692009-04-10 17:16:57 +0000718 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000719 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000720
721 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000722 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
723 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
724 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
725 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000726
Douglas Gregorbd945002009-04-13 16:31:14 +0000727 // Write the line table.
728 if (SourceMgr.hasLineTable()) {
729 LineTableInfo &LineTable = SourceMgr.getLineTable();
730
731 // Emit the file names
732 Record.push_back(LineTable.getNumFilenames());
733 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
734 // Emit the file name
735 const char *Filename = LineTable.getFilename(I);
736 unsigned FilenameLen = Filename? strlen(Filename) : 0;
737 Record.push_back(FilenameLen);
738 if (FilenameLen)
739 Record.insert(Record.end(), Filename, Filename + FilenameLen);
740 }
741
742 // Emit the line entries
743 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
744 L != LEnd; ++L) {
745 // Emit the file ID
746 Record.push_back(L->first);
747
748 // Emit the line entries
749 Record.push_back(L->second.size());
750 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
751 LEEnd = L->second.end();
752 LE != LEEnd; ++LE) {
753 Record.push_back(LE->FileOffset);
754 Record.push_back(LE->LineNo);
755 Record.push_back(LE->FilenameID);
756 Record.push_back((unsigned)LE->FileKind);
757 Record.push_back(LE->IncludeOffset);
758 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000759 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000760 }
761 }
762
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000763 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000764 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000765 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000766 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
767 E = HS.header_file_end();
768 I != E; ++I) {
769 Record.push_back(I->isImport);
770 Record.push_back(I->DirInfo);
771 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000772 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000773 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
774 Record.clear();
775 }
776
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000777 // Write out the source location entry table. We skip the first
778 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000779 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000780 RecordData PreloadSLocs;
781 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
782 for (SourceManager::sloc_entry_iterator
783 SLoc = SourceMgr.sloc_entry_begin() + 1,
784 SLocEnd = SourceMgr.sloc_entry_end();
785 SLoc != SLocEnd; ++SLoc) {
786 // Record the offset of this source-location entry.
787 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
788
789 // Figure out which record code to use.
790 unsigned Code;
791 if (SLoc->isFile()) {
792 if (SLoc->getFile().getContentCache()->Entry)
793 Code = pch::SM_SLOC_FILE_ENTRY;
794 else
795 Code = pch::SM_SLOC_BUFFER_ENTRY;
796 } else
797 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
798 Record.clear();
799 Record.push_back(Code);
800
801 Record.push_back(SLoc->getOffset());
802 if (SLoc->isFile()) {
803 const SrcMgr::FileInfo &File = SLoc->getFile();
804 Record.push_back(File.getIncludeLoc().getRawEncoding());
805 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
806 Record.push_back(File.hasLineDirectives());
807
808 const SrcMgr::ContentCache *Content = File.getContentCache();
809 if (Content->Entry) {
810 // The source location entry is a file. The blob associated
811 // with this entry is the file name.
812 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
813 Content->Entry->getName(),
814 strlen(Content->Entry->getName()));
815
816 // FIXME: For now, preload all file source locations, so that
817 // we get the appropriate File entries in the reader. This is
818 // a temporary measure.
819 PreloadSLocs.push_back(SLocEntryOffsets.size());
820 } else {
821 // The source location entry is a buffer. The blob associated
822 // with this entry contains the contents of the buffer.
823
824 // We add one to the size so that we capture the trailing NULL
825 // that is required by llvm::MemoryBuffer::getMemBuffer (on
826 // the reader side).
827 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
828 const char *Name = Buffer->getBufferIdentifier();
829 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
830 Record.clear();
831 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
832 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
833 Buffer->getBufferStart(),
834 Buffer->getBufferSize() + 1);
835
836 if (strcmp(Name, "<built-in>") == 0)
837 PreloadSLocs.push_back(SLocEntryOffsets.size());
838 }
839 } else {
840 // The source location entry is an instantiation.
841 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
842 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
843 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
844 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
845
846 // Compute the token length for this macro expansion.
847 unsigned NextOffset = SourceMgr.getNextOffset();
848 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
849 if (++NextSLoc != SLocEnd)
850 NextOffset = NextSLoc->getOffset();
851 Record.push_back(NextOffset - SLoc->getOffset() - 1);
852 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
853 }
854 }
855
Douglas Gregorc9490c02009-04-16 22:23:12 +0000856 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000857
858 if (SLocEntryOffsets.empty())
859 return;
860
861 // Write the source-location offsets table into the PCH block. This
862 // table is used for lazily loading source-location information.
863 using namespace llvm;
864 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
865 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
866 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
867 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
869 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
870
871 Record.clear();
872 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
873 Record.push_back(SLocEntryOffsets.size());
874 Record.push_back(SourceMgr.getNextOffset());
875 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
876 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000877 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000878
879 // Write the source location entry preloads array, telling the PCH
880 // reader which source locations entries it should load eagerly.
881 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000882}
883
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000884//===----------------------------------------------------------------------===//
885// Preprocessor Serialization
886//===----------------------------------------------------------------------===//
887
Chris Lattner0b1fb982009-04-10 17:15:23 +0000888/// \brief Writes the block containing the serialized form of the
889/// preprocessor.
890///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000891void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000892 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000893
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000894 // If the preprocessor __COUNTER__ value has been bumped, remember it.
895 if (PP.getCounterValue() != 0) {
896 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000897 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000898 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000899 }
900
901 // Enter the preprocessor block.
902 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000903
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000904 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
905 // FIXME: use diagnostics subsystem for localization etc.
906 if (PP.SawDateOrTime())
907 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
908
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000909 // Loop over all the macro definitions that are live at the end of the file,
910 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000911 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
912 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000913 // FIXME: This emits macros in hash table order, we should do it in a stable
914 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000915 MacroInfo *MI = I->second;
916
917 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
918 // been redefined by the header (in which case they are not isBuiltinMacro).
919 if (MI->isBuiltinMacro())
920 continue;
921
Douglas Gregor37e26842009-04-21 23:56:24 +0000922 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000923 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000924 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000925 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
926 Record.push_back(MI->isUsed());
927
928 unsigned Code;
929 if (MI->isObjectLike()) {
930 Code = pch::PP_MACRO_OBJECT_LIKE;
931 } else {
932 Code = pch::PP_MACRO_FUNCTION_LIKE;
933
934 Record.push_back(MI->isC99Varargs());
935 Record.push_back(MI->isGNUVarargs());
936 Record.push_back(MI->getNumArgs());
937 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
938 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000939 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000940 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000941 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000942 Record.clear();
943
Chris Lattnerdf961c22009-04-10 18:08:30 +0000944 // Emit the tokens array.
945 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
946 // Note that we know that the preprocessor does not have any annotation
947 // tokens in it because they are created by the parser, and thus can't be
948 // in a macro definition.
949 const Token &Tok = MI->getReplacementToken(TokNo);
950
951 Record.push_back(Tok.getLocation().getRawEncoding());
952 Record.push_back(Tok.getLength());
953
Chris Lattnerdf961c22009-04-10 18:08:30 +0000954 // FIXME: When reading literal tokens, reconstruct the literal pointer if
955 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000956 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000957
958 // FIXME: Should translate token kind to a stable encoding.
959 Record.push_back(Tok.getKind());
960 // FIXME: Should translate token flags to a stable encoding.
961 Record.push_back(Tok.getFlags());
962
Douglas Gregorc9490c02009-04-16 22:23:12 +0000963 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000964 Record.clear();
965 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000966 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000967 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000968 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000969}
970
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000971//===----------------------------------------------------------------------===//
972// Type Serialization
973//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +0000974
Douglas Gregor2cf26342009-04-09 22:27:44 +0000975/// \brief Write the representation of a type to the PCH stream.
976void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000977 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000978 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000979 ID = NextTypeID++;
980
981 // Record the offset for this type.
982 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000983 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000984 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
985 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000986 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000987 }
988
989 RecordData Record;
990
991 // Emit the type's representation.
992 PCHTypeWriter W(*this, Record);
993 switch (T->getTypeClass()) {
994 // For all of the concrete, non-dependent types, call the
995 // appropriate visitor function.
996#define TYPE(Class, Base) \
997 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
998#define ABSTRACT_TYPE(Class, Base)
999#define DEPENDENT_TYPE(Class, Base)
1000#include "clang/AST/TypeNodes.def"
1001
1002 // For all of the dependent type nodes (which only occur in C++
1003 // templates), produce an error.
1004#define TYPE(Class, Base)
1005#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1006#include "clang/AST/TypeNodes.def"
1007 assert(false && "Cannot serialize dependent type nodes");
1008 break;
1009 }
1010
1011 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001012 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001013
1014 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001015 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001016}
1017
1018/// \brief Write a block containing all of the types.
1019void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001020 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001021 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001022
Douglas Gregor366809a2009-04-26 03:49:13 +00001023 // Emit all of the types that need to be emitted (so far).
1024 while (!TypesToEmit.empty()) {
1025 const Type *T = TypesToEmit.front();
1026 TypesToEmit.pop();
1027 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1028 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001029 }
1030
1031 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001032 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001033}
1034
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001035//===----------------------------------------------------------------------===//
1036// Declaration Serialization
1037//===----------------------------------------------------------------------===//
1038
Douglas Gregor2cf26342009-04-09 22:27:44 +00001039/// \brief Write the block containing all of the declaration IDs
1040/// lexically declared within the given DeclContext.
1041///
1042/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1043/// bistream, or 0 if no block was written.
1044uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1045 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001046 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +00001047 return 0;
1048
Douglas Gregorc9490c02009-04-16 22:23:12 +00001049 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001050 RecordData Record;
1051 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1052 DEnd = DC->decls_end(Context);
1053 D != DEnd; ++D)
1054 AddDeclRef(*D, Record);
1055
Douglas Gregor25123082009-04-22 22:34:57 +00001056 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001057 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001058 return Offset;
1059}
1060
1061/// \brief Write the block containing all of the declaration IDs
1062/// visible from the given DeclContext.
1063///
1064/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1065/// bistream, or 0 if no block was written.
1066uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1067 DeclContext *DC) {
1068 if (DC->getPrimaryContext() != DC)
1069 return 0;
1070
Douglas Gregoraff22df2009-04-21 22:32:33 +00001071 // Since there is no name lookup into functions or methods, and we
1072 // perform name lookup for the translation unit via the
1073 // IdentifierInfo chains, don't bother to build a
1074 // visible-declarations table for these entities.
1075 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001076 return 0;
1077
Douglas Gregor2cf26342009-04-09 22:27:44 +00001078 // Force the DeclContext to build a its name-lookup table.
1079 DC->lookup(Context, DeclarationName());
1080
1081 // Serialize the contents of the mapping used for lookup. Note that,
1082 // although we have two very different code paths, the serialized
1083 // representation is the same for both cases: a declaration name,
1084 // followed by a size, followed by references to the visible
1085 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001086 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001087 RecordData Record;
1088 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001089 if (!Map)
1090 return 0;
1091
Douglas Gregor2cf26342009-04-09 22:27:44 +00001092 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1093 D != DEnd; ++D) {
1094 AddDeclarationName(D->first, Record);
1095 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1096 Record.push_back(Result.second - Result.first);
1097 for(; Result.first != Result.second; ++Result.first)
1098 AddDeclRef(*Result.first, Record);
1099 }
1100
1101 if (Record.size() == 0)
1102 return 0;
1103
Douglas Gregorc9490c02009-04-16 22:23:12 +00001104 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001105 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001106 return Offset;
1107}
1108
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001109//===----------------------------------------------------------------------===//
1110// Global Method Pool and Selector Serialization
1111//===----------------------------------------------------------------------===//
1112
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001113namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001114// Trait used for the on-disk hash table used in the method pool.
1115class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1116 PCHWriter &Writer;
1117
1118public:
1119 typedef Selector key_type;
1120 typedef key_type key_type_ref;
1121
1122 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1123 typedef const data_type& data_type_ref;
1124
1125 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1126
1127 static unsigned ComputeHash(Selector Sel) {
1128 unsigned N = Sel.getNumArgs();
1129 if (N == 0)
1130 ++N;
1131 unsigned R = 5381;
1132 for (unsigned I = 0; I != N; ++I)
1133 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1134 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1135 return R;
1136 }
1137
1138 std::pair<unsigned,unsigned>
1139 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1140 data_type_ref Methods) {
1141 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1142 clang::io::Emit16(Out, KeyLen);
1143 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1144 for (const ObjCMethodList *Method = &Methods.first; Method;
1145 Method = Method->Next)
1146 if (Method->Method)
1147 DataLen += 4;
1148 for (const ObjCMethodList *Method = &Methods.second; Method;
1149 Method = Method->Next)
1150 if (Method->Method)
1151 DataLen += 4;
1152 clang::io::Emit16(Out, DataLen);
1153 return std::make_pair(KeyLen, DataLen);
1154 }
1155
Douglas Gregor83941df2009-04-25 17:48:32 +00001156 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1157 uint64_t Start = Out.tell();
1158 assert((Start >> 32) == 0 && "Selector key offset too large");
1159 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001160 unsigned N = Sel.getNumArgs();
1161 clang::io::Emit16(Out, N);
1162 if (N == 0)
1163 N = 1;
1164 for (unsigned I = 0; I != N; ++I)
1165 clang::io::Emit32(Out,
1166 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1167 }
1168
1169 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001170 data_type_ref Methods, unsigned DataLen) {
1171 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001172 unsigned NumInstanceMethods = 0;
1173 for (const ObjCMethodList *Method = &Methods.first; Method;
1174 Method = Method->Next)
1175 if (Method->Method)
1176 ++NumInstanceMethods;
1177
1178 unsigned NumFactoryMethods = 0;
1179 for (const ObjCMethodList *Method = &Methods.second; Method;
1180 Method = Method->Next)
1181 if (Method->Method)
1182 ++NumFactoryMethods;
1183
1184 clang::io::Emit16(Out, NumInstanceMethods);
1185 clang::io::Emit16(Out, NumFactoryMethods);
1186 for (const ObjCMethodList *Method = &Methods.first; Method;
1187 Method = Method->Next)
1188 if (Method->Method)
1189 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001190 for (const ObjCMethodList *Method = &Methods.second; Method;
1191 Method = Method->Next)
1192 if (Method->Method)
1193 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001194
1195 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001196 }
1197};
1198} // end anonymous namespace
1199
1200/// \brief Write the method pool into the PCH file.
1201///
1202/// The method pool contains both instance and factory methods, stored
1203/// in an on-disk hash table indexed by the selector.
1204void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1205 using namespace llvm;
1206
1207 // Create and write out the blob that contains the instance and
1208 // factor method pools.
1209 bool Empty = true;
1210 {
1211 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1212
1213 // Create the on-disk hash table representation. Start by
1214 // iterating through the instance method pool.
1215 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001216 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001217 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1218 Instance = SemaRef.InstanceMethodPool.begin(),
1219 InstanceEnd = SemaRef.InstanceMethodPool.end();
1220 Instance != InstanceEnd; ++Instance) {
1221 // Check whether there is a factory method with the same
1222 // selector.
1223 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1224 = SemaRef.FactoryMethodPool.find(Instance->first);
1225
1226 if (Factory == SemaRef.FactoryMethodPool.end())
1227 Generator.insert(Instance->first,
1228 std::make_pair(Instance->second,
1229 ObjCMethodList()));
1230 else
1231 Generator.insert(Instance->first,
1232 std::make_pair(Instance->second, Factory->second));
1233
Douglas Gregor83941df2009-04-25 17:48:32 +00001234 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001235 Empty = false;
1236 }
1237
1238 // Now iterate through the factory method pool, to pick up any
1239 // selectors that weren't already in the instance method pool.
1240 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1241 Factory = SemaRef.FactoryMethodPool.begin(),
1242 FactoryEnd = SemaRef.FactoryMethodPool.end();
1243 Factory != FactoryEnd; ++Factory) {
1244 // Check whether there is an instance method with the same
1245 // selector. If so, there is no work to do here.
1246 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1247 = SemaRef.InstanceMethodPool.find(Factory->first);
1248
Douglas Gregor83941df2009-04-25 17:48:32 +00001249 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001250 Generator.insert(Factory->first,
1251 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001252 ++NumSelectorsInMethodPool;
1253 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001254
1255 Empty = false;
1256 }
1257
Douglas Gregor83941df2009-04-25 17:48:32 +00001258 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001259 return;
1260
1261 // Create the on-disk hash table in a buffer.
1262 llvm::SmallVector<char, 4096> MethodPool;
1263 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001264 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001265 {
1266 PCHMethodPoolTrait Trait(*this);
1267 llvm::raw_svector_ostream Out(MethodPool);
1268 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001269 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001270 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001271
1272 // For every selector that we have seen but which was not
1273 // written into the hash table, write the selector itself and
1274 // record it's offset.
1275 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1276 if (SelectorOffsets[I] == 0)
1277 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001278 }
1279
1280 // Create a blob abbreviation
1281 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1282 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1283 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001284 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001285 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1286 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1287
Douglas Gregor83941df2009-04-25 17:48:32 +00001288 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001289 RecordData Record;
1290 Record.push_back(pch::METHOD_POOL);
1291 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001292 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001293 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1294 &MethodPool.front(),
1295 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001296
1297 // Create a blob abbreviation for the selector table offsets.
1298 Abbrev = new BitCodeAbbrev();
1299 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1300 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1302 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1303
1304 // Write the selector offsets table.
1305 Record.clear();
1306 Record.push_back(pch::SELECTOR_OFFSETS);
1307 Record.push_back(SelectorOffsets.size());
1308 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1309 (const char *)&SelectorOffsets.front(),
1310 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001311 }
1312}
1313
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001314//===----------------------------------------------------------------------===//
1315// Identifier Table Serialization
1316//===----------------------------------------------------------------------===//
1317
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001318namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001319class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1320 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001321 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001322
Douglas Gregora92193e2009-04-28 21:18:29 +00001323 /// \brief Determines whether this is an "interesting" identifier
1324 /// that needs a full IdentifierInfo structure written into the hash
1325 /// table.
1326 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1327 return II->isPoisoned() ||
1328 II->isExtensionToken() ||
1329 II->hasMacroDefinition() ||
1330 II->getObjCOrBuiltinID() ||
1331 II->getFETokenInfo<void>();
1332 }
1333
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001334public:
1335 typedef const IdentifierInfo* key_type;
1336 typedef key_type key_type_ref;
1337
1338 typedef pch::IdentID data_type;
1339 typedef data_type data_type_ref;
1340
Douglas Gregor37e26842009-04-21 23:56:24 +00001341 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1342 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001343
1344 static unsigned ComputeHash(const IdentifierInfo* II) {
1345 return clang::BernsteinHash(II->getName());
1346 }
1347
Douglas Gregor37e26842009-04-21 23:56:24 +00001348 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001349 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1350 pch::IdentID ID) {
1351 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001352 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1353 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001354 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregora92193e2009-04-28 21:18:29 +00001355 if (II->hasMacroDefinition() &&
1356 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001357 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001358 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1359 DEnd = IdentifierResolver::end();
1360 D != DEnd; ++D)
1361 DataLen += sizeof(pch::DeclID);
1362 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001363 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001364 // We emit the key length after the data length so that every
1365 // string is preceded by a 16-bit length. This matches the PTH
1366 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001367 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001368 return std::make_pair(KeyLen, DataLen);
1369 }
1370
1371 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1372 unsigned KeyLen) {
1373 // Record the location of the key data. This is used when generating
1374 // the mapping from persistent IDs to strings.
1375 Writer.SetIdentifierOffset(II, Out.tell());
1376 Out.write(II->getName(), KeyLen);
1377 }
1378
1379 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1380 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001381 if (!isInterestingIdentifier(II)) {
1382 clang::io::Emit32(Out, ID << 1);
1383 return;
1384 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001385
Douglas Gregora92193e2009-04-28 21:18:29 +00001386 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001387 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001388 bool hasMacroDefinition =
1389 II->hasMacroDefinition() &&
1390 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001391 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001392 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001393 Bits = (Bits << 1) | II->isExtensionToken();
1394 Bits = (Bits << 1) | II->isPoisoned();
1395 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001396 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001397
Douglas Gregor37e26842009-04-21 23:56:24 +00001398 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001399 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001400
Douglas Gregor668c1a42009-04-21 22:25:48 +00001401 // Emit the declaration IDs in reverse order, because the
1402 // IdentifierResolver provides the declarations as they would be
1403 // visible (e.g., the function "stat" would come before the struct
1404 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1405 // adds declarations to the end of the list (so we need to see the
1406 // struct "status" before the function "status").
1407 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1408 IdentifierResolver::end());
1409 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1410 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001411 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001412 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001413 }
1414};
1415} // end anonymous namespace
1416
Douglas Gregorafaf3082009-04-11 00:14:32 +00001417/// \brief Write the identifier table into the PCH file.
1418///
1419/// The identifier table consists of a blob containing string data
1420/// (the actual identifiers themselves) and a separate "offsets" index
1421/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001422void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001423 using namespace llvm;
1424
1425 // Create and write out the blob that contains the identifier
1426 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001427 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001428 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1429
Douglas Gregor92b059e2009-04-28 20:33:11 +00001430 // Look for any identifiers that were named while processing the
1431 // headers, but are otherwise not needed. We add these to the hash
1432 // table to enable checking of the predefines buffer in the case
1433 // where the user adds new macro definitions when building the PCH
1434 // file.
1435 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1436 IDEnd = PP.getIdentifierTable().end();
1437 ID != IDEnd; ++ID)
1438 getIdentifierRef(ID->second);
1439
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001440 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001441 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001442 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1443 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1444 ID != IDEnd; ++ID) {
1445 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001446 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001447 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001448
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001449 // Create the on-disk hash table in a buffer.
1450 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001451 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001452 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001453 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001454 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001455 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001456 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001457 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001458 }
1459
1460 // Create a blob abbreviation
1461 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1462 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001464 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001465 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001466
1467 // Write the identifier table
1468 RecordData Record;
1469 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001470 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001471 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1472 &IdentifierTable.front(),
1473 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001474 }
1475
1476 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001477 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1478 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1479 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1480 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1481 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1482
1483 RecordData Record;
1484 Record.push_back(pch::IDENTIFIER_OFFSET);
1485 Record.push_back(IdentifierOffsets.size());
1486 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1487 (const char *)&IdentifierOffsets.front(),
1488 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001489}
1490
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001491//===----------------------------------------------------------------------===//
1492// General Serialization Routines
1493//===----------------------------------------------------------------------===//
1494
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001495/// \brief Write a record containing the given attributes.
1496void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1497 RecordData Record;
1498 for (; Attr; Attr = Attr->getNext()) {
1499 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1500 Record.push_back(Attr->isInherited());
1501 switch (Attr->getKind()) {
1502 case Attr::Alias:
1503 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1504 break;
1505
1506 case Attr::Aligned:
1507 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1508 break;
1509
1510 case Attr::AlwaysInline:
1511 break;
1512
1513 case Attr::AnalyzerNoReturn:
1514 break;
1515
1516 case Attr::Annotate:
1517 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1518 break;
1519
1520 case Attr::AsmLabel:
1521 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1522 break;
1523
1524 case Attr::Blocks:
1525 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1526 break;
1527
1528 case Attr::Cleanup:
1529 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1530 break;
1531
1532 case Attr::Const:
1533 break;
1534
1535 case Attr::Constructor:
1536 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1537 break;
1538
1539 case Attr::DLLExport:
1540 case Attr::DLLImport:
1541 case Attr::Deprecated:
1542 break;
1543
1544 case Attr::Destructor:
1545 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1546 break;
1547
1548 case Attr::FastCall:
1549 break;
1550
1551 case Attr::Format: {
1552 const FormatAttr *Format = cast<FormatAttr>(Attr);
1553 AddString(Format->getType(), Record);
1554 Record.push_back(Format->getFormatIdx());
1555 Record.push_back(Format->getFirstArg());
1556 break;
1557 }
1558
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001559 case Attr::Sentinel : {
1560 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1561 Record.push_back(Sentinel->getSentinel());
1562 Record.push_back(Sentinel->getNullPos());
1563 break;
1564 }
1565
Chris Lattnercf2a7212009-04-20 19:12:28 +00001566 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001567 case Attr::IBOutletKind:
1568 case Attr::NoReturn:
1569 case Attr::NoThrow:
1570 case Attr::Nodebug:
1571 case Attr::Noinline:
1572 break;
1573
1574 case Attr::NonNull: {
1575 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1576 Record.push_back(NonNull->size());
1577 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1578 break;
1579 }
1580
1581 case Attr::ObjCException:
1582 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001583 case Attr::CFReturnsRetained:
1584 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001585 case Attr::Overloadable:
1586 break;
1587
1588 case Attr::Packed:
1589 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1590 break;
1591
1592 case Attr::Pure:
1593 break;
1594
1595 case Attr::Regparm:
1596 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1597 break;
1598
1599 case Attr::Section:
1600 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1601 break;
1602
1603 case Attr::StdCall:
1604 case Attr::TransparentUnion:
1605 case Attr::Unavailable:
1606 case Attr::Unused:
1607 case Attr::Used:
1608 break;
1609
1610 case Attr::Visibility:
1611 // FIXME: stable encoding
1612 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1613 break;
1614
1615 case Attr::WarnUnusedResult:
1616 case Attr::Weak:
1617 case Attr::WeakImport:
1618 break;
1619 }
1620 }
1621
Douglas Gregorc9490c02009-04-16 22:23:12 +00001622 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001623}
1624
1625void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1626 Record.push_back(Str.size());
1627 Record.insert(Record.end(), Str.begin(), Str.end());
1628}
1629
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001630/// \brief Note that the identifier II occurs at the given offset
1631/// within the identifier table.
1632void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001633 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001634}
1635
Douglas Gregor83941df2009-04-25 17:48:32 +00001636/// \brief Note that the selector Sel occurs at the given offset
1637/// within the method pool/selector table.
1638void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1639 unsigned ID = SelectorIDs[Sel];
1640 assert(ID && "Unknown selector");
1641 SelectorOffsets[ID - 1] = Offset;
1642}
1643
Douglas Gregorc9490c02009-04-16 22:23:12 +00001644PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001645 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001646 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1647 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001648
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001649void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001650 using namespace llvm;
1651
Douglas Gregore7785042009-04-20 15:53:59 +00001652 ASTContext &Context = SemaRef.Context;
1653 Preprocessor &PP = SemaRef.PP;
1654
Douglas Gregor2cf26342009-04-09 22:27:44 +00001655 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001656 Stream.Emit((unsigned)'C', 8);
1657 Stream.Emit((unsigned)'P', 8);
1658 Stream.Emit((unsigned)'C', 8);
1659 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001660
1661 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001662
1663 // The translation unit is the first declaration we'll emit.
1664 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1665 DeclsToEmit.push(Context.getTranslationUnitDecl());
1666
Douglas Gregor2deaea32009-04-22 18:49:13 +00001667 // Make sure that we emit IdentifierInfos (and any attached
1668 // declarations) for builtins.
1669 {
1670 IdentifierTable &Table = PP.getIdentifierTable();
1671 llvm::SmallVector<const char *, 32> BuiltinNames;
1672 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1673 Context.getLangOptions().NoBuiltin);
1674 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1675 getIdentifierRef(&Table.get(BuiltinNames[I]));
1676 }
1677
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001678 // Build a record containing all of the tentative definitions in
1679 // this header file. Generally, this record will be empty.
1680 RecordData TentativeDefinitions;
1681 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1682 TD = SemaRef.TentativeDefinitions.begin(),
1683 TDEnd = SemaRef.TentativeDefinitions.end();
1684 TD != TDEnd; ++TD)
1685 AddDeclRef(TD->second, TentativeDefinitions);
1686
Douglas Gregor14c22f22009-04-22 22:18:58 +00001687 // Build a record containing all of the locally-scoped external
1688 // declarations in this header file. Generally, this record will be
1689 // empty.
1690 RecordData LocallyScopedExternalDecls;
1691 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1692 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1693 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1694 TD != TDEnd; ++TD)
1695 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1696
Douglas Gregorb81c1702009-04-27 20:06:05 +00001697 // Build a record containing all of the ext_vector declarations.
1698 RecordData ExtVectorDecls;
1699 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1700 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1701
1702 // Build a record containing all of the Objective-C category
1703 // implementations.
1704 RecordData ObjCCategoryImpls;
1705 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1706 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1707
Douglas Gregor2cf26342009-04-09 22:27:44 +00001708 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001709 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001710 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001711 WriteMetadata(Context);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001712 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001713 if (StatCalls)
1714 WriteStatCache(*StatCalls);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001715 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001716 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001717
1718 // Keep writing types and declarations until all types and
1719 // declarations have been written.
1720 do {
1721 if (!DeclsToEmit.empty())
1722 WriteDeclsBlock(Context);
1723 if (!TypesToEmit.empty())
1724 WriteTypesBlock(Context);
1725 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1726
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001727 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001728 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001729
1730 // Write the type offsets array
1731 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1732 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1733 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1735 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1736 Record.clear();
1737 Record.push_back(pch::TYPE_OFFSET);
1738 Record.push_back(TypeOffsets.size());
1739 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1740 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001741 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001742
1743 // Write the declaration offsets array
1744 Abbrev = new BitCodeAbbrev();
1745 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1748 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1749 Record.clear();
1750 Record.push_back(pch::DECL_OFFSET);
1751 Record.push_back(DeclOffsets.size());
1752 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1753 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001754 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001755
1756 // Write the record of special types.
1757 Record.clear();
1758 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001759 AddTypeRef(Context.getObjCIdType(), Record);
1760 AddTypeRef(Context.getObjCSelType(), Record);
1761 AddTypeRef(Context.getObjCProtoType(), Record);
1762 AddTypeRef(Context.getObjCClassType(), Record);
1763 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1764 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001765 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1766
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001767 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001768 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001769 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001770
1771 // Write the record containing tentative definitions.
1772 if (!TentativeDefinitions.empty())
1773 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001774
1775 // Write the record containing locally-scoped external definitions.
1776 if (!LocallyScopedExternalDecls.empty())
1777 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1778 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001779
1780 // Write the record containing ext_vector type names.
1781 if (!ExtVectorDecls.empty())
1782 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1783
1784 // Write the record containing Objective-C category implementations.
1785 if (!ObjCCategoryImpls.empty())
1786 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001787
1788 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001789 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001790 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001791 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001792 Record.push_back(NumLexicalDeclContexts);
1793 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001794 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001795 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001796}
1797
1798void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1799 Record.push_back(Loc.getRawEncoding());
1800}
1801
1802void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1803 Record.push_back(Value.getBitWidth());
1804 unsigned N = Value.getNumWords();
1805 const uint64_t* Words = Value.getRawData();
1806 for (unsigned I = 0; I != N; ++I)
1807 Record.push_back(Words[I]);
1808}
1809
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001810void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1811 Record.push_back(Value.isUnsigned());
1812 AddAPInt(Value, Record);
1813}
1814
Douglas Gregor17fc2232009-04-14 21:55:33 +00001815void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1816 AddAPInt(Value.bitcastToAPInt(), Record);
1817}
1818
Douglas Gregor2cf26342009-04-09 22:27:44 +00001819void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001820 Record.push_back(getIdentifierRef(II));
1821}
1822
1823pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1824 if (II == 0)
1825 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001826
1827 pch::IdentID &ID = IdentifierIDs[II];
1828 if (ID == 0)
1829 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001830 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001831}
1832
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001833void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1834 if (SelRef.getAsOpaquePtr() == 0) {
1835 Record.push_back(0);
1836 return;
1837 }
1838
1839 pch::SelectorID &SID = SelectorIDs[SelRef];
1840 if (SID == 0) {
1841 SID = SelectorIDs.size();
1842 SelVector.push_back(SelRef);
1843 }
1844 Record.push_back(SID);
1845}
1846
Douglas Gregor2cf26342009-04-09 22:27:44 +00001847void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1848 if (T.isNull()) {
1849 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1850 return;
1851 }
1852
1853 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001854 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001855 switch (BT->getKind()) {
1856 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1857 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1858 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1859 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1860 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1861 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1862 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1863 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001864 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001865 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1866 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1867 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1868 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1869 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1870 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1871 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001872 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001873 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1874 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1875 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001876 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001877 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1878 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1879 }
1880
1881 Record.push_back((ID << 3) | T.getCVRQualifiers());
1882 return;
1883 }
1884
Douglas Gregor8038d512009-04-10 17:25:41 +00001885 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001886 if (ID == 0) {
1887 // We haven't seen this type before. Assign it a new ID and put it
1888 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001889 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001890 TypesToEmit.push(T.getTypePtr());
1891 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001892
1893 // Encode the type qualifiers in the type reference.
1894 Record.push_back((ID << 3) | T.getCVRQualifiers());
1895}
1896
1897void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1898 if (D == 0) {
1899 Record.push_back(0);
1900 return;
1901 }
1902
Douglas Gregor8038d512009-04-10 17:25:41 +00001903 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001904 if (ID == 0) {
1905 // We haven't seen this declaration before. Give it a new ID and
1906 // enqueue it in the list of declarations to emit.
1907 ID = DeclIDs.size();
1908 DeclsToEmit.push(const_cast<Decl *>(D));
1909 }
1910
1911 Record.push_back(ID);
1912}
1913
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001914pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1915 if (D == 0)
1916 return 0;
1917
1918 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1919 return DeclIDs[D];
1920}
1921
Douglas Gregor2cf26342009-04-09 22:27:44 +00001922void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001923 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001924 Record.push_back(Name.getNameKind());
1925 switch (Name.getNameKind()) {
1926 case DeclarationName::Identifier:
1927 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1928 break;
1929
1930 case DeclarationName::ObjCZeroArgSelector:
1931 case DeclarationName::ObjCOneArgSelector:
1932 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001933 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001934 break;
1935
1936 case DeclarationName::CXXConstructorName:
1937 case DeclarationName::CXXDestructorName:
1938 case DeclarationName::CXXConversionFunctionName:
1939 AddTypeRef(Name.getCXXNameType(), Record);
1940 break;
1941
1942 case DeclarationName::CXXOperatorName:
1943 Record.push_back(Name.getCXXOverloadedOperator());
1944 break;
1945
1946 case DeclarationName::CXXUsingDirective:
1947 // No extra data to emit
1948 break;
1949 }
1950}
Douglas Gregor0b748912009-04-14 21:18:50 +00001951