blob: 5edf03c6ff1587e2d653adb47acf79701902cf65 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
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 Gregorc72f6c82009-04-16 22:23:12 +0000174 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-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 Gregor3c8ff3e2009-04-15 18:43:11 +0000202 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000203 assert(false && "Cannot serialize template specialization types");
204}
205
206void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000207 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000208 assert(false && "Cannot serialize 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 Lattner80f83c62009-04-22 05:57:30 +0000233//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000234// PCHWriter Implementation
235//===----------------------------------------------------------------------===//
236
Chris Lattner920673a2009-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 Lattnerd16afaa2009-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 Lattner920673a2009-04-26 22:26:21 +0000332}
333
334void PCHWriter::WriteBlockInfoBlock() {
335 RecordData Record;
336 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
337
Chris Lattner880f3f72009-04-27 00:40:25 +0000338#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000339#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
340
341 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000342 BLOCK(PCH_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000343 RECORD(TYPE_OFFSET);
344 RECORD(DECL_OFFSET);
345 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000346 RECORD(METADATA);
Chris Lattner920673a2009-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 Gregor32e231c2009-04-27 06:38:32 +0000357 RECORD(SOURCE_LOCATION_OFFSETS);
358 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000359 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000360 RECORD(EXT_VECTOR_DECLS);
361 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000362
Chris Lattner920673a2009-04-26 22:26:21 +0000363 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000364 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-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 Lattner880f3f72009-04-27 00:40:25 +0000373 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-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 Lattner880f3f72009-04-27 00:40:25 +0000379 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-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 Lattnerd16afaa2009-04-27 00:49:53 +0000403 // Statements and Exprs can occur in the Types block.
404 AddStmtsExprs(Stream, Record);
405
Chris Lattner920673a2009-04-26 22:26:21 +0000406 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000407 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-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 Lattner920673a2009-04-26 22:26:21 +0000428 RECORD(DECL_FIELD);
429 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000430 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000431 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-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 Lattnerd16afaa2009-04-27 00:49:53 +0000437 // Statements and Exprs can occur in the Decls block.
438 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000439#undef RECORD
440#undef BLOCK
441 Stream.ExitBlock();
442}
443
444
Douglas Gregorb7064742009-04-27 22:23:34 +0000445/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000446void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000447 using namespace llvm;
Douglas Gregoreccf0d12009-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 Gregorb5887f32009-04-10 21:16:55 +0000484
485 RecordData Record;
Douglas Gregorb7064742009-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 Gregorb5887f32009-04-10 21:16:55 +0000491 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000492 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000493}
494
495/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-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 Gregor179cfb12009-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 Gregor179cfb12009-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 Lattnercd4da472009-04-27 07:35:58 +0000525 // Whether static initializers are protected by locks.
526 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-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.
Anders Carlssonf2310142009-05-13 19:49:53 +0000549 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
550 // be enabled.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000551 Record.push_back(LangOpts.getGCMode());
552 Record.push_back(LangOpts.getVisibilityMode());
553 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000554 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000555}
556
Douglas Gregorab1cef72009-04-10 03:52:48 +0000557//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000558// stat cache Serialization
559//===----------------------------------------------------------------------===//
560
561namespace {
562// Trait used for the on-disk hash table of stat cache results.
563class VISIBILITY_HIDDEN PCHStatCacheTrait {
564public:
565 typedef const char * key_type;
566 typedef key_type key_type_ref;
567
568 typedef std::pair<int, struct stat> data_type;
569 typedef const data_type& data_type_ref;
570
571 static unsigned ComputeHash(const char *path) {
572 return BernsteinHash(path);
573 }
574
575 std::pair<unsigned,unsigned>
576 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
577 data_type_ref Data) {
578 unsigned StrLen = strlen(path);
579 clang::io::Emit16(Out, StrLen);
580 unsigned DataLen = 1; // result value
581 if (Data.first == 0)
582 DataLen += 4 + 4 + 2 + 8 + 8;
583 clang::io::Emit8(Out, DataLen);
584 return std::make_pair(StrLen + 1, DataLen);
585 }
586
587 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
588 Out.write(path, KeyLen);
589 }
590
591 void EmitData(llvm::raw_ostream& Out, key_type_ref,
592 data_type_ref Data, unsigned DataLen) {
593 using namespace clang::io;
594 uint64_t Start = Out.tell(); (void)Start;
595
596 // Result of stat()
597 Emit8(Out, Data.first? 1 : 0);
598
599 if (Data.first == 0) {
600 Emit32(Out, (uint32_t) Data.second.st_ino);
601 Emit32(Out, (uint32_t) Data.second.st_dev);
602 Emit16(Out, (uint16_t) Data.second.st_mode);
603 Emit64(Out, (uint64_t) Data.second.st_mtime);
604 Emit64(Out, (uint64_t) Data.second.st_size);
605 }
606
607 assert(Out.tell() - Start == DataLen && "Wrong data length");
608 }
609};
610} // end anonymous namespace
611
612/// \brief Write the stat() system call cache to the PCH file.
613void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
614 // Build the on-disk hash table containing information about every
615 // stat() call.
616 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
617 unsigned NumStatEntries = 0;
618 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
619 StatEnd = StatCalls.end();
620 Stat != StatEnd; ++Stat, ++NumStatEntries)
621 Generator.insert(Stat->first(), Stat->second);
622
623 // Create the on-disk hash table in a buffer.
624 llvm::SmallVector<char, 4096> StatCacheData;
625 uint32_t BucketOffset;
626 {
627 llvm::raw_svector_ostream Out(StatCacheData);
628 // Make sure that no bucket is at offset 0
629 clang::io::Emit32(Out, 0);
630 BucketOffset = Generator.Emit(Out);
631 }
632
633 // Create a blob abbreviation
634 using namespace llvm;
635 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
636 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
638 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
639 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
640 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
641
642 // Write the stat cache
643 RecordData Record;
644 Record.push_back(pch::STAT_CACHE);
645 Record.push_back(BucketOffset);
646 Record.push_back(NumStatEntries);
647 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
648 &StatCacheData.front(),
649 StatCacheData.size());
650}
651
652//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000653// Source Manager Serialization
654//===----------------------------------------------------------------------===//
655
656/// \brief Create an abbreviation for the SLocEntry that refers to a
657/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000658static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000659 using namespace llvm;
660 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
661 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000667 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000668}
669
670/// \brief Create an abbreviation for the SLocEntry that refers to a
671/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000672static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000673 using namespace llvm;
674 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
675 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
676 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
677 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
678 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
679 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
680 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000681 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000682}
683
684/// \brief Create an abbreviation for the SLocEntry that refers to a
685/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000686static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000687 using namespace llvm;
688 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
689 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
690 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000691 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000692}
693
694/// \brief Create an abbreviation for the SLocEntry that refers to an
695/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000696static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000697 using namespace llvm;
698 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
699 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
701 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
702 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000705 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000706}
707
708/// \brief Writes the block containing the serialized form of the
709/// source manager.
710///
711/// TODO: We should probably use an on-disk hash table (stored in a
712/// blob), indexed based on the file name, so that we only create
713/// entries for files that we actually need. In the common case (no
714/// errors), we probably won't have to create file entries for any of
715/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000716void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
717 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000718 RecordData Record;
719
Chris Lattner84b04f12009-04-10 17:16:57 +0000720 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000721 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000722
723 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000724 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
725 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
726 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
727 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000728
Douglas Gregor635f97f2009-04-13 16:31:14 +0000729 // Write the line table.
730 if (SourceMgr.hasLineTable()) {
731 LineTableInfo &LineTable = SourceMgr.getLineTable();
732
733 // Emit the file names
734 Record.push_back(LineTable.getNumFilenames());
735 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
736 // Emit the file name
737 const char *Filename = LineTable.getFilename(I);
738 unsigned FilenameLen = Filename? strlen(Filename) : 0;
739 Record.push_back(FilenameLen);
740 if (FilenameLen)
741 Record.insert(Record.end(), Filename, Filename + FilenameLen);
742 }
743
744 // Emit the line entries
745 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
746 L != LEnd; ++L) {
747 // Emit the file ID
748 Record.push_back(L->first);
749
750 // Emit the line entries
751 Record.push_back(L->second.size());
752 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
753 LEEnd = L->second.end();
754 LE != LEEnd; ++LE) {
755 Record.push_back(LE->FileOffset);
756 Record.push_back(LE->LineNo);
757 Record.push_back(LE->FilenameID);
758 Record.push_back((unsigned)LE->FileKind);
759 Record.push_back(LE->IncludeOffset);
760 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000761 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000762 }
763 }
764
Douglas Gregor32e231c2009-04-27 06:38:32 +0000765 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000766 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000767 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000768 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
769 E = HS.header_file_end();
770 I != E; ++I) {
771 Record.push_back(I->isImport);
772 Record.push_back(I->DirInfo);
773 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000774 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000775 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
776 Record.clear();
777 }
778
Douglas Gregor32e231c2009-04-27 06:38:32 +0000779 // Write out the source location entry table. We skip the first
780 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000781 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000782 RecordData PreloadSLocs;
783 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
784 for (SourceManager::sloc_entry_iterator
785 SLoc = SourceMgr.sloc_entry_begin() + 1,
786 SLocEnd = SourceMgr.sloc_entry_end();
787 SLoc != SLocEnd; ++SLoc) {
788 // Record the offset of this source-location entry.
789 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
790
791 // Figure out which record code to use.
792 unsigned Code;
793 if (SLoc->isFile()) {
794 if (SLoc->getFile().getContentCache()->Entry)
795 Code = pch::SM_SLOC_FILE_ENTRY;
796 else
797 Code = pch::SM_SLOC_BUFFER_ENTRY;
798 } else
799 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
800 Record.clear();
801 Record.push_back(Code);
802
803 Record.push_back(SLoc->getOffset());
804 if (SLoc->isFile()) {
805 const SrcMgr::FileInfo &File = SLoc->getFile();
806 Record.push_back(File.getIncludeLoc().getRawEncoding());
807 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
808 Record.push_back(File.hasLineDirectives());
809
810 const SrcMgr::ContentCache *Content = File.getContentCache();
811 if (Content->Entry) {
812 // The source location entry is a file. The blob associated
813 // with this entry is the file name.
814 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
815 Content->Entry->getName(),
816 strlen(Content->Entry->getName()));
817
818 // FIXME: For now, preload all file source locations, so that
819 // we get the appropriate File entries in the reader. This is
820 // a temporary measure.
821 PreloadSLocs.push_back(SLocEntryOffsets.size());
822 } else {
823 // The source location entry is a buffer. The blob associated
824 // with this entry contains the contents of the buffer.
825
826 // We add one to the size so that we capture the trailing NULL
827 // that is required by llvm::MemoryBuffer::getMemBuffer (on
828 // the reader side).
829 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
830 const char *Name = Buffer->getBufferIdentifier();
831 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
832 Record.clear();
833 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
834 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
835 Buffer->getBufferStart(),
836 Buffer->getBufferSize() + 1);
837
838 if (strcmp(Name, "<built-in>") == 0)
839 PreloadSLocs.push_back(SLocEntryOffsets.size());
840 }
841 } else {
842 // The source location entry is an instantiation.
843 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
844 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
845 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
846 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
847
848 // Compute the token length for this macro expansion.
849 unsigned NextOffset = SourceMgr.getNextOffset();
850 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
851 if (++NextSLoc != SLocEnd)
852 NextOffset = NextSLoc->getOffset();
853 Record.push_back(NextOffset - SLoc->getOffset() - 1);
854 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
855 }
856 }
857
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000858 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000859
860 if (SLocEntryOffsets.empty())
861 return;
862
863 // Write the source-location offsets table into the PCH block. This
864 // table is used for lazily loading source-location information.
865 using namespace llvm;
866 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
867 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
871 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
872
873 Record.clear();
874 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
875 Record.push_back(SLocEntryOffsets.size());
876 Record.push_back(SourceMgr.getNextOffset());
877 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
878 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000879 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000880
881 // Write the source location entry preloads array, telling the PCH
882 // reader which source locations entries it should load eagerly.
883 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000884}
885
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000886//===----------------------------------------------------------------------===//
887// Preprocessor Serialization
888//===----------------------------------------------------------------------===//
889
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000890/// \brief Writes the block containing the serialized form of the
891/// preprocessor.
892///
Chris Lattner850eabd2009-04-10 18:08:30 +0000893void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000894 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000895
Chris Lattner4b21c202009-04-13 01:29:17 +0000896 // If the preprocessor __COUNTER__ value has been bumped, remember it.
897 if (PP.getCounterValue() != 0) {
898 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000899 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000900 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000901 }
902
903 // Enter the preprocessor block.
904 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000905
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000906 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
907 // FIXME: use diagnostics subsystem for localization etc.
908 if (PP.SawDateOrTime())
909 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
910
Chris Lattner1b094952009-04-10 18:00:12 +0000911 // Loop over all the macro definitions that are live at the end of the file,
912 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000913 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
914 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000915 // FIXME: This emits macros in hash table order, we should do it in a stable
916 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000917 MacroInfo *MI = I->second;
918
919 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
920 // been redefined by the header (in which case they are not isBuiltinMacro).
921 if (MI->isBuiltinMacro())
922 continue;
923
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000924 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000925 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000926 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000927 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
928 Record.push_back(MI->isUsed());
929
930 unsigned Code;
931 if (MI->isObjectLike()) {
932 Code = pch::PP_MACRO_OBJECT_LIKE;
933 } else {
934 Code = pch::PP_MACRO_FUNCTION_LIKE;
935
936 Record.push_back(MI->isC99Varargs());
937 Record.push_back(MI->isGNUVarargs());
938 Record.push_back(MI->getNumArgs());
939 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
940 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000941 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000942 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000943 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000944 Record.clear();
945
Chris Lattner850eabd2009-04-10 18:08:30 +0000946 // Emit the tokens array.
947 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
948 // Note that we know that the preprocessor does not have any annotation
949 // tokens in it because they are created by the parser, and thus can't be
950 // in a macro definition.
951 const Token &Tok = MI->getReplacementToken(TokNo);
952
953 Record.push_back(Tok.getLocation().getRawEncoding());
954 Record.push_back(Tok.getLength());
955
Chris Lattner850eabd2009-04-10 18:08:30 +0000956 // FIXME: When reading literal tokens, reconstruct the literal pointer if
957 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000958 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000959
960 // FIXME: Should translate token kind to a stable encoding.
961 Record.push_back(Tok.getKind());
962 // FIXME: Should translate token flags to a stable encoding.
963 Record.push_back(Tok.getFlags());
964
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000965 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000966 Record.clear();
967 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000968 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000969 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000970 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000971}
972
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000973//===----------------------------------------------------------------------===//
974// Type Serialization
975//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000976
Douglas Gregorc34897d2009-04-09 22:27:44 +0000977/// \brief Write the representation of a type to the PCH stream.
978void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000979 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +0000980 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000981 ID = NextTypeID++;
982
983 // Record the offset for this type.
984 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000985 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000986 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
987 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000988 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +0000989 }
990
991 RecordData Record;
992
993 // Emit the type's representation.
994 PCHTypeWriter W(*this, Record);
995 switch (T->getTypeClass()) {
996 // For all of the concrete, non-dependent types, call the
997 // appropriate visitor function.
998#define TYPE(Class, Base) \
999 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1000#define ABSTRACT_TYPE(Class, Base)
1001#define DEPENDENT_TYPE(Class, Base)
1002#include "clang/AST/TypeNodes.def"
1003
1004 // For all of the dependent type nodes (which only occur in C++
1005 // templates), produce an error.
1006#define TYPE(Class, Base)
1007#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1008#include "clang/AST/TypeNodes.def"
1009 assert(false && "Cannot serialize dependent type nodes");
1010 break;
1011 }
1012
1013 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001014 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001015
1016 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001017 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001018}
1019
1020/// \brief Write a block containing all of the types.
1021void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001022 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001023 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001024
Douglas Gregore43f0972009-04-26 03:49:13 +00001025 // Emit all of the types that need to be emitted (so far).
1026 while (!TypesToEmit.empty()) {
1027 const Type *T = TypesToEmit.front();
1028 TypesToEmit.pop();
1029 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1030 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001031 }
1032
1033 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001034 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001035}
1036
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001037//===----------------------------------------------------------------------===//
1038// Declaration Serialization
1039//===----------------------------------------------------------------------===//
1040
Douglas Gregorc34897d2009-04-09 22:27:44 +00001041/// \brief Write the block containing all of the declaration IDs
1042/// lexically declared within the given DeclContext.
1043///
1044/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1045/// bistream, or 0 if no block was written.
1046uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1047 DeclContext *DC) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001048 if (DC->decls_empty(Context))
Douglas Gregorc34897d2009-04-09 22:27:44 +00001049 return 0;
1050
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001051 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001052 RecordData Record;
1053 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
1054 DEnd = DC->decls_end(Context);
1055 D != DEnd; ++D)
1056 AddDeclRef(*D, Record);
1057
Douglas Gregoraf136d92009-04-22 22:34:57 +00001058 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001059 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001060 return Offset;
1061}
1062
1063/// \brief Write the block containing all of the declaration IDs
1064/// visible from the given DeclContext.
1065///
1066/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1067/// bistream, or 0 if no block was written.
1068uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1069 DeclContext *DC) {
1070 if (DC->getPrimaryContext() != DC)
1071 return 0;
1072
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001073 // Since there is no name lookup into functions or methods, and we
1074 // perform name lookup for the translation unit via the
1075 // IdentifierInfo chains, don't bother to build a
1076 // visible-declarations table for these entities.
1077 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001078 return 0;
1079
Douglas Gregorc34897d2009-04-09 22:27:44 +00001080 // Force the DeclContext to build a its name-lookup table.
1081 DC->lookup(Context, DeclarationName());
1082
1083 // Serialize the contents of the mapping used for lookup. Note that,
1084 // although we have two very different code paths, the serialized
1085 // representation is the same for both cases: a declaration name,
1086 // followed by a size, followed by references to the visible
1087 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001088 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001089 RecordData Record;
1090 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001091 if (!Map)
1092 return 0;
1093
Douglas Gregorc34897d2009-04-09 22:27:44 +00001094 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1095 D != DEnd; ++D) {
1096 AddDeclarationName(D->first, Record);
1097 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1098 Record.push_back(Result.second - Result.first);
1099 for(; Result.first != Result.second; ++Result.first)
1100 AddDeclRef(*Result.first, Record);
1101 }
1102
1103 if (Record.size() == 0)
1104 return 0;
1105
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001106 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001107 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001108 return Offset;
1109}
1110
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001111//===----------------------------------------------------------------------===//
1112// Global Method Pool and Selector Serialization
1113//===----------------------------------------------------------------------===//
1114
Douglas Gregorff9a6092009-04-20 20:36:09 +00001115namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001116// Trait used for the on-disk hash table used in the method pool.
1117class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1118 PCHWriter &Writer;
1119
1120public:
1121 typedef Selector key_type;
1122 typedef key_type key_type_ref;
1123
1124 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1125 typedef const data_type& data_type_ref;
1126
1127 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1128
1129 static unsigned ComputeHash(Selector Sel) {
1130 unsigned N = Sel.getNumArgs();
1131 if (N == 0)
1132 ++N;
1133 unsigned R = 5381;
1134 for (unsigned I = 0; I != N; ++I)
1135 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1136 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1137 return R;
1138 }
1139
1140 std::pair<unsigned,unsigned>
1141 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1142 data_type_ref Methods) {
1143 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1144 clang::io::Emit16(Out, KeyLen);
1145 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1146 for (const ObjCMethodList *Method = &Methods.first; Method;
1147 Method = Method->Next)
1148 if (Method->Method)
1149 DataLen += 4;
1150 for (const ObjCMethodList *Method = &Methods.second; Method;
1151 Method = Method->Next)
1152 if (Method->Method)
1153 DataLen += 4;
1154 clang::io::Emit16(Out, DataLen);
1155 return std::make_pair(KeyLen, DataLen);
1156 }
1157
Douglas Gregor2d711832009-04-25 17:48:32 +00001158 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1159 uint64_t Start = Out.tell();
1160 assert((Start >> 32) == 0 && "Selector key offset too large");
1161 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001162 unsigned N = Sel.getNumArgs();
1163 clang::io::Emit16(Out, N);
1164 if (N == 0)
1165 N = 1;
1166 for (unsigned I = 0; I != N; ++I)
1167 clang::io::Emit32(Out,
1168 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1169 }
1170
1171 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001172 data_type_ref Methods, unsigned DataLen) {
1173 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001174 unsigned NumInstanceMethods = 0;
1175 for (const ObjCMethodList *Method = &Methods.first; Method;
1176 Method = Method->Next)
1177 if (Method->Method)
1178 ++NumInstanceMethods;
1179
1180 unsigned NumFactoryMethods = 0;
1181 for (const ObjCMethodList *Method = &Methods.second; Method;
1182 Method = Method->Next)
1183 if (Method->Method)
1184 ++NumFactoryMethods;
1185
1186 clang::io::Emit16(Out, NumInstanceMethods);
1187 clang::io::Emit16(Out, NumFactoryMethods);
1188 for (const ObjCMethodList *Method = &Methods.first; Method;
1189 Method = Method->Next)
1190 if (Method->Method)
1191 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001192 for (const ObjCMethodList *Method = &Methods.second; Method;
1193 Method = Method->Next)
1194 if (Method->Method)
1195 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001196
1197 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001198 }
1199};
1200} // end anonymous namespace
1201
1202/// \brief Write the method pool into the PCH file.
1203///
1204/// The method pool contains both instance and factory methods, stored
1205/// in an on-disk hash table indexed by the selector.
1206void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1207 using namespace llvm;
1208
1209 // Create and write out the blob that contains the instance and
1210 // factor method pools.
1211 bool Empty = true;
1212 {
1213 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1214
1215 // Create the on-disk hash table representation. Start by
1216 // iterating through the instance method pool.
1217 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001218 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001219 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1220 Instance = SemaRef.InstanceMethodPool.begin(),
1221 InstanceEnd = SemaRef.InstanceMethodPool.end();
1222 Instance != InstanceEnd; ++Instance) {
1223 // Check whether there is a factory method with the same
1224 // selector.
1225 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1226 = SemaRef.FactoryMethodPool.find(Instance->first);
1227
1228 if (Factory == SemaRef.FactoryMethodPool.end())
1229 Generator.insert(Instance->first,
1230 std::make_pair(Instance->second,
1231 ObjCMethodList()));
1232 else
1233 Generator.insert(Instance->first,
1234 std::make_pair(Instance->second, Factory->second));
1235
Douglas Gregor2d711832009-04-25 17:48:32 +00001236 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001237 Empty = false;
1238 }
1239
1240 // Now iterate through the factory method pool, to pick up any
1241 // selectors that weren't already in the instance method pool.
1242 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1243 Factory = SemaRef.FactoryMethodPool.begin(),
1244 FactoryEnd = SemaRef.FactoryMethodPool.end();
1245 Factory != FactoryEnd; ++Factory) {
1246 // Check whether there is an instance method with the same
1247 // selector. If so, there is no work to do here.
1248 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1249 = SemaRef.InstanceMethodPool.find(Factory->first);
1250
Douglas Gregor2d711832009-04-25 17:48:32 +00001251 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001252 Generator.insert(Factory->first,
1253 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001254 ++NumSelectorsInMethodPool;
1255 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001256
1257 Empty = false;
1258 }
1259
Douglas Gregor2d711832009-04-25 17:48:32 +00001260 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001261 return;
1262
1263 // Create the on-disk hash table in a buffer.
1264 llvm::SmallVector<char, 4096> MethodPool;
1265 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001266 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001267 {
1268 PCHMethodPoolTrait Trait(*this);
1269 llvm::raw_svector_ostream Out(MethodPool);
1270 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001271 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001272 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001273
1274 // For every selector that we have seen but which was not
1275 // written into the hash table, write the selector itself and
1276 // record it's offset.
1277 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1278 if (SelectorOffsets[I] == 0)
1279 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001280 }
1281
1282 // Create a blob abbreviation
1283 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1284 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1285 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001286 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001287 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1288 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1289
Douglas Gregor2d711832009-04-25 17:48:32 +00001290 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001291 RecordData Record;
1292 Record.push_back(pch::METHOD_POOL);
1293 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001294 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001295 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1296 &MethodPool.front(),
1297 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001298
1299 // Create a blob abbreviation for the selector table offsets.
1300 Abbrev = new BitCodeAbbrev();
1301 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1304 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1305
1306 // Write the selector offsets table.
1307 Record.clear();
1308 Record.push_back(pch::SELECTOR_OFFSETS);
1309 Record.push_back(SelectorOffsets.size());
1310 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1311 (const char *)&SelectorOffsets.front(),
1312 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001313 }
1314}
1315
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001316//===----------------------------------------------------------------------===//
1317// Identifier Table Serialization
1318//===----------------------------------------------------------------------===//
1319
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001320namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001321class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1322 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001323 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001324
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001325 /// \brief Determines whether this is an "interesting" identifier
1326 /// that needs a full IdentifierInfo structure written into the hash
1327 /// table.
1328 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1329 return II->isPoisoned() ||
1330 II->isExtensionToken() ||
1331 II->hasMacroDefinition() ||
1332 II->getObjCOrBuiltinID() ||
1333 II->getFETokenInfo<void>();
1334 }
1335
Douglas Gregorff9a6092009-04-20 20:36:09 +00001336public:
1337 typedef const IdentifierInfo* key_type;
1338 typedef key_type key_type_ref;
1339
1340 typedef pch::IdentID data_type;
1341 typedef data_type data_type_ref;
1342
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001343 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1344 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001345
1346 static unsigned ComputeHash(const IdentifierInfo* II) {
1347 return clang::BernsteinHash(II->getName());
1348 }
1349
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001350 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001351 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1352 pch::IdentID ID) {
1353 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001354 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1355 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001356 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001357 if (II->hasMacroDefinition() &&
1358 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001359 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001360 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1361 DEnd = IdentifierResolver::end();
1362 D != DEnd; ++D)
1363 DataLen += sizeof(pch::DeclID);
1364 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001365 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001366 // We emit the key length after the data length so that every
1367 // string is preceded by a 16-bit length. This matches the PTH
1368 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001369 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001370 return std::make_pair(KeyLen, DataLen);
1371 }
1372
1373 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1374 unsigned KeyLen) {
1375 // Record the location of the key data. This is used when generating
1376 // the mapping from persistent IDs to strings.
1377 Writer.SetIdentifierOffset(II, Out.tell());
1378 Out.write(II->getName(), KeyLen);
1379 }
1380
1381 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1382 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001383 if (!isInterestingIdentifier(II)) {
1384 clang::io::Emit32(Out, ID << 1);
1385 return;
1386 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001387
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001388 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001389 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001390 bool hasMacroDefinition =
1391 II->hasMacroDefinition() &&
1392 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001393 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001394 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001395 Bits = (Bits << 1) | II->isExtensionToken();
1396 Bits = (Bits << 1) | II->isPoisoned();
1397 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001398 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001399
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001400 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001401 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001402
Douglas Gregorc713da92009-04-21 22:25:48 +00001403 // Emit the declaration IDs in reverse order, because the
1404 // IdentifierResolver provides the declarations as they would be
1405 // visible (e.g., the function "stat" would come before the struct
1406 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1407 // adds declarations to the end of the list (so we need to see the
1408 // struct "status" before the function "status").
1409 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1410 IdentifierResolver::end());
1411 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1412 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001413 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001414 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001415 }
1416};
1417} // end anonymous namespace
1418
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001419/// \brief Write the identifier table into the PCH file.
1420///
1421/// The identifier table consists of a blob containing string data
1422/// (the actual identifiers themselves) and a separate "offsets" index
1423/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001424void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001425 using namespace llvm;
1426
1427 // Create and write out the blob that contains the identifier
1428 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001429 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001430 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1431
Douglas Gregor91137812009-04-28 20:33:11 +00001432 // Look for any identifiers that were named while processing the
1433 // headers, but are otherwise not needed. We add these to the hash
1434 // table to enable checking of the predefines buffer in the case
1435 // where the user adds new macro definitions when building the PCH
1436 // file.
1437 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1438 IDEnd = PP.getIdentifierTable().end();
1439 ID != IDEnd; ++ID)
1440 getIdentifierRef(ID->second);
1441
Douglas Gregorff9a6092009-04-20 20:36:09 +00001442 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001443 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001444 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1445 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1446 ID != IDEnd; ++ID) {
1447 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001448 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001449 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001450
Douglas Gregorff9a6092009-04-20 20:36:09 +00001451 // Create the on-disk hash table in a buffer.
1452 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001453 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001454 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001455 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001456 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001457 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001458 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001459 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001460 }
1461
1462 // Create a blob abbreviation
1463 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1464 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001465 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001466 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001467 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001468
1469 // Write the identifier table
1470 RecordData Record;
1471 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001472 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001473 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1474 &IdentifierTable.front(),
1475 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001476 }
1477
1478 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001479 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1480 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1481 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1483 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1484
1485 RecordData Record;
1486 Record.push_back(pch::IDENTIFIER_OFFSET);
1487 Record.push_back(IdentifierOffsets.size());
1488 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1489 (const char *)&IdentifierOffsets.front(),
1490 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001491}
1492
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001493//===----------------------------------------------------------------------===//
1494// General Serialization Routines
1495//===----------------------------------------------------------------------===//
1496
Douglas Gregor1c507882009-04-15 21:30:51 +00001497/// \brief Write a record containing the given attributes.
1498void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1499 RecordData Record;
1500 for (; Attr; Attr = Attr->getNext()) {
1501 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1502 Record.push_back(Attr->isInherited());
1503 switch (Attr->getKind()) {
1504 case Attr::Alias:
1505 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1506 break;
1507
1508 case Attr::Aligned:
1509 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1510 break;
1511
1512 case Attr::AlwaysInline:
1513 break;
1514
1515 case Attr::AnalyzerNoReturn:
1516 break;
1517
1518 case Attr::Annotate:
1519 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1520 break;
1521
1522 case Attr::AsmLabel:
1523 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1524 break;
1525
1526 case Attr::Blocks:
1527 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1528 break;
1529
1530 case Attr::Cleanup:
1531 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1532 break;
1533
1534 case Attr::Const:
1535 break;
1536
1537 case Attr::Constructor:
1538 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1539 break;
1540
1541 case Attr::DLLExport:
1542 case Attr::DLLImport:
1543 case Attr::Deprecated:
1544 break;
1545
1546 case Attr::Destructor:
1547 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1548 break;
1549
1550 case Attr::FastCall:
1551 break;
1552
1553 case Attr::Format: {
1554 const FormatAttr *Format = cast<FormatAttr>(Attr);
1555 AddString(Format->getType(), Record);
1556 Record.push_back(Format->getFormatIdx());
1557 Record.push_back(Format->getFirstArg());
1558 break;
1559 }
1560
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001561 case Attr::FormatArg: {
1562 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1563 Record.push_back(Format->getFormatIdx());
1564 break;
1565 }
1566
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001567 case Attr::Sentinel : {
1568 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1569 Record.push_back(Sentinel->getSentinel());
1570 Record.push_back(Sentinel->getNullPos());
1571 break;
1572 }
1573
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001574 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001575 case Attr::IBOutletKind:
1576 case Attr::NoReturn:
1577 case Attr::NoThrow:
1578 case Attr::Nodebug:
1579 case Attr::Noinline:
1580 break;
1581
1582 case Attr::NonNull: {
1583 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1584 Record.push_back(NonNull->size());
1585 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1586 break;
1587 }
1588
1589 case Attr::ObjCException:
1590 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001591 case Attr::CFReturnsRetained:
1592 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001593 case Attr::Overloadable:
1594 break;
1595
1596 case Attr::Packed:
1597 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1598 break;
1599
1600 case Attr::Pure:
1601 break;
1602
1603 case Attr::Regparm:
1604 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1605 break;
1606
1607 case Attr::Section:
1608 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1609 break;
1610
1611 case Attr::StdCall:
1612 case Attr::TransparentUnion:
1613 case Attr::Unavailable:
1614 case Attr::Unused:
1615 case Attr::Used:
1616 break;
1617
1618 case Attr::Visibility:
1619 // FIXME: stable encoding
1620 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1621 break;
1622
1623 case Attr::WarnUnusedResult:
1624 case Attr::Weak:
1625 case Attr::WeakImport:
1626 break;
1627 }
1628 }
1629
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001630 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001631}
1632
1633void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1634 Record.push_back(Str.size());
1635 Record.insert(Record.end(), Str.begin(), Str.end());
1636}
1637
Douglas Gregorff9a6092009-04-20 20:36:09 +00001638/// \brief Note that the identifier II occurs at the given offset
1639/// within the identifier table.
1640void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001641 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001642}
1643
Douglas Gregor2d711832009-04-25 17:48:32 +00001644/// \brief Note that the selector Sel occurs at the given offset
1645/// within the method pool/selector table.
1646void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1647 unsigned ID = SelectorIDs[Sel];
1648 assert(ID && "Unknown selector");
1649 SelectorOffsets[ID - 1] = Offset;
1650}
1651
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001652PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001653 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001654 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1655 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001656
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001657void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001658 using namespace llvm;
1659
Douglas Gregor87887da2009-04-20 15:53:59 +00001660 ASTContext &Context = SemaRef.Context;
1661 Preprocessor &PP = SemaRef.PP;
1662
Douglas Gregorc34897d2009-04-09 22:27:44 +00001663 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001664 Stream.Emit((unsigned)'C', 8);
1665 Stream.Emit((unsigned)'P', 8);
1666 Stream.Emit((unsigned)'C', 8);
1667 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001668
1669 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001670
1671 // The translation unit is the first declaration we'll emit.
1672 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1673 DeclsToEmit.push(Context.getTranslationUnitDecl());
1674
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001675 // Make sure that we emit IdentifierInfos (and any attached
1676 // declarations) for builtins.
1677 {
1678 IdentifierTable &Table = PP.getIdentifierTable();
1679 llvm::SmallVector<const char *, 32> BuiltinNames;
1680 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1681 Context.getLangOptions().NoBuiltin);
1682 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1683 getIdentifierRef(&Table.get(BuiltinNames[I]));
1684 }
1685
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001686 // Build a record containing all of the tentative definitions in
1687 // this header file. Generally, this record will be empty.
1688 RecordData TentativeDefinitions;
1689 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1690 TD = SemaRef.TentativeDefinitions.begin(),
1691 TDEnd = SemaRef.TentativeDefinitions.end();
1692 TD != TDEnd; ++TD)
1693 AddDeclRef(TD->second, TentativeDefinitions);
1694
Douglas Gregor062d9482009-04-22 22:18:58 +00001695 // Build a record containing all of the locally-scoped external
1696 // declarations in this header file. Generally, this record will be
1697 // empty.
1698 RecordData LocallyScopedExternalDecls;
1699 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1700 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1701 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1702 TD != TDEnd; ++TD)
1703 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1704
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001705 // Build a record containing all of the ext_vector declarations.
1706 RecordData ExtVectorDecls;
1707 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1708 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1709
1710 // Build a record containing all of the Objective-C category
1711 // implementations.
1712 RecordData ObjCCategoryImpls;
1713 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1714 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1715
Douglas Gregorc34897d2009-04-09 22:27:44 +00001716 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001717 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001718 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001719 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001720 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001721 if (StatCalls)
1722 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001723 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001724 WritePreprocessor(PP);
Douglas Gregore43f0972009-04-26 03:49:13 +00001725
1726 // Keep writing types and declarations until all types and
1727 // declarations have been written.
1728 do {
1729 if (!DeclsToEmit.empty())
1730 WriteDeclsBlock(Context);
1731 if (!TypesToEmit.empty())
1732 WriteTypesBlock(Context);
1733 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1734
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001735 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001736 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001737
1738 // Write the type offsets array
1739 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1740 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1741 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1743 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1744 Record.clear();
1745 Record.push_back(pch::TYPE_OFFSET);
1746 Record.push_back(TypeOffsets.size());
1747 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1748 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001749 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001750
1751 // Write the declaration offsets array
1752 Abbrev = new BitCodeAbbrev();
1753 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1754 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1755 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1756 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1757 Record.clear();
1758 Record.push_back(pch::DECL_OFFSET);
1759 Record.push_back(DeclOffsets.size());
1760 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1761 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001762 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001763
1764 // Write the record of special types.
1765 Record.clear();
1766 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001767 AddTypeRef(Context.getObjCIdType(), Record);
1768 AddTypeRef(Context.getObjCSelType(), Record);
1769 AddTypeRef(Context.getObjCProtoType(), Record);
1770 AddTypeRef(Context.getObjCClassType(), Record);
1771 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1772 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001773 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1774
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001775 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001776 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001777 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001778
1779 // Write the record containing tentative definitions.
1780 if (!TentativeDefinitions.empty())
1781 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001782
1783 // Write the record containing locally-scoped external definitions.
1784 if (!LocallyScopedExternalDecls.empty())
1785 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1786 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001787
1788 // Write the record containing ext_vector type names.
1789 if (!ExtVectorDecls.empty())
1790 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1791
1792 // Write the record containing Objective-C category implementations.
1793 if (!ObjCCategoryImpls.empty())
1794 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001795
1796 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001797 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001798 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001799 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001800 Record.push_back(NumLexicalDeclContexts);
1801 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001802 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001803 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001804}
1805
1806void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1807 Record.push_back(Loc.getRawEncoding());
1808}
1809
1810void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1811 Record.push_back(Value.getBitWidth());
1812 unsigned N = Value.getNumWords();
1813 const uint64_t* Words = Value.getRawData();
1814 for (unsigned I = 0; I != N; ++I)
1815 Record.push_back(Words[I]);
1816}
1817
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001818void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1819 Record.push_back(Value.isUnsigned());
1820 AddAPInt(Value, Record);
1821}
1822
Douglas Gregore2f37202009-04-14 21:55:33 +00001823void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1824 AddAPInt(Value.bitcastToAPInt(), Record);
1825}
1826
Douglas Gregorc34897d2009-04-09 22:27:44 +00001827void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001828 Record.push_back(getIdentifierRef(II));
1829}
1830
1831pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1832 if (II == 0)
1833 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001834
1835 pch::IdentID &ID = IdentifierIDs[II];
1836 if (ID == 0)
1837 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001838 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001839}
1840
Steve Naroff9e84d782009-04-23 10:39:46 +00001841void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1842 if (SelRef.getAsOpaquePtr() == 0) {
1843 Record.push_back(0);
1844 return;
1845 }
1846
1847 pch::SelectorID &SID = SelectorIDs[SelRef];
1848 if (SID == 0) {
1849 SID = SelectorIDs.size();
1850 SelVector.push_back(SelRef);
1851 }
1852 Record.push_back(SID);
1853}
1854
Douglas Gregorc34897d2009-04-09 22:27:44 +00001855void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1856 if (T.isNull()) {
1857 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1858 return;
1859 }
1860
1861 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001862 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001863 switch (BT->getKind()) {
1864 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1865 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1866 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1867 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1868 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1869 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1870 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1871 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001872 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001873 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1874 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1875 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1876 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1877 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1878 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1879 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001880 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001881 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1882 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1883 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001884 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001885 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1886 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1887 }
1888
1889 Record.push_back((ID << 3) | T.getCVRQualifiers());
1890 return;
1891 }
1892
Douglas Gregorac8f2802009-04-10 17:25:41 +00001893 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001894 if (ID == 0) {
1895 // We haven't seen this type before. Assign it a new ID and put it
1896 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001897 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001898 TypesToEmit.push(T.getTypePtr());
1899 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001900
1901 // Encode the type qualifiers in the type reference.
1902 Record.push_back((ID << 3) | T.getCVRQualifiers());
1903}
1904
1905void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1906 if (D == 0) {
1907 Record.push_back(0);
1908 return;
1909 }
1910
Douglas Gregorac8f2802009-04-10 17:25:41 +00001911 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001912 if (ID == 0) {
1913 // We haven't seen this declaration before. Give it a new ID and
1914 // enqueue it in the list of declarations to emit.
1915 ID = DeclIDs.size();
1916 DeclsToEmit.push(const_cast<Decl *>(D));
1917 }
1918
1919 Record.push_back(ID);
1920}
1921
Douglas Gregorff9a6092009-04-20 20:36:09 +00001922pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1923 if (D == 0)
1924 return 0;
1925
1926 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1927 return DeclIDs[D];
1928}
1929
Douglas Gregorc34897d2009-04-09 22:27:44 +00001930void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001931 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001932 Record.push_back(Name.getNameKind());
1933 switch (Name.getNameKind()) {
1934 case DeclarationName::Identifier:
1935 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1936 break;
1937
1938 case DeclarationName::ObjCZeroArgSelector:
1939 case DeclarationName::ObjCOneArgSelector:
1940 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001941 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001942 break;
1943
1944 case DeclarationName::CXXConstructorName:
1945 case DeclarationName::CXXDestructorName:
1946 case DeclarationName::CXXConversionFunctionName:
1947 AddTypeRef(Name.getCXXNameType(), Record);
1948 break;
1949
1950 case DeclarationName::CXXOperatorName:
1951 Record.push_back(Name.getCXXOverloadedOperator());
1952 break;
1953
1954 case DeclarationName::CXXUsingDirective:
1955 // No extra data to emit
1956 break;
1957 }
1958}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001959