blob: 3bfc9e89d10a344e9f50f0b85a185722423164bb [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregor87887da2009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Douglas Gregorff9a6092009-04-20 20:36:09 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregorc34897d2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner1b094952009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregorff9a6092009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorb7064742009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregore2f37202009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregoreccf0d12009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner64b65f82009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattnerd83ede52009-04-27 06:16:06 +000043
Douglas Gregorc34897d2009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
53 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor6cc5d192009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
67void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
68 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
69 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
70 Record.push_back(T->getAddressSpace());
71 Code = pch::TYPE_EXT_QUAL;
72}
73
74void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
75 assert(false && "Built-in types are never serialized");
76}
77
78void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
79 Record.push_back(T->getWidth());
80 Record.push_back(T->isSigned());
81 Code = pch::TYPE_FIXED_WIDTH_INT;
82}
83
84void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
85 Writer.AddTypeRef(T->getElementType(), Record);
86 Code = pch::TYPE_COMPLEX;
87}
88
89void PCHTypeWriter::VisitPointerType(const PointerType *T) {
90 Writer.AddTypeRef(T->getPointeeType(), Record);
91 Code = pch::TYPE_POINTER;
92}
93
94void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_BLOCK_POINTER;
97}
98
99void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_LVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Code = pch::TYPE_RVALUE_REFERENCE;
107}
108
109void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
110 Writer.AddTypeRef(T->getPointeeType(), Record);
111 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
112 Code = pch::TYPE_MEMBER_POINTER;
113}
114
115void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
116 Writer.AddTypeRef(T->getElementType(), Record);
117 Record.push_back(T->getSizeModifier()); // FIXME: stable values
118 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
119}
120
121void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
122 VisitArrayType(T);
123 Writer.AddAPInt(T->getSize(), Record);
124 Code = pch::TYPE_CONSTANT_ARRAY;
125}
126
127void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
128 VisitArrayType(T);
129 Code = pch::TYPE_INCOMPLETE_ARRAY;
130}
131
132void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
133 VisitArrayType(T);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000134 Writer.AddStmt(T->getSizeExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000135 Code = pch::TYPE_VARIABLE_ARRAY;
136}
137
138void PCHTypeWriter::VisitVectorType(const VectorType *T) {
139 Writer.AddTypeRef(T->getElementType(), Record);
140 Record.push_back(T->getNumElements());
141 Code = pch::TYPE_VECTOR;
142}
143
144void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
145 VisitVectorType(T);
146 Code = pch::TYPE_EXT_VECTOR;
147}
148
149void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
150 Writer.AddTypeRef(T->getResultType(), Record);
151}
152
153void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
154 VisitFunctionType(T);
155 Code = pch::TYPE_FUNCTION_NO_PROTO;
156}
157
158void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
159 VisitFunctionType(T);
160 Record.push_back(T->getNumArgs());
161 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
162 Writer.AddTypeRef(T->getArgType(I), Record);
163 Record.push_back(T->isVariadic());
164 Record.push_back(T->getTypeQuals());
Sebastian Redl2767d882009-05-27 22:11:52 +0000165 Record.push_back(T->hasExceptionSpec());
166 Record.push_back(T->hasAnyExceptionSpec());
167 Record.push_back(T->getNumExceptions());
168 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
169 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000170 Code = pch::TYPE_FUNCTION_PROTO;
171}
172
173void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
174 Writer.AddDeclRef(T->getDecl(), Record);
175 Code = pch::TYPE_TYPEDEF;
176}
177
178void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000179 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000180 Code = pch::TYPE_TYPEOF_EXPR;
181}
182
183void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
184 Writer.AddTypeRef(T->getUnderlyingType(), Record);
185 Code = pch::TYPE_TYPEOF;
186}
187
Anders Carlsson93ab5332009-06-24 19:06:50 +0000188void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
189 Writer.AddStmt(T->getUnderlyingExpr());
190 Code = pch::TYPE_DECLTYPE;
191}
192
Douglas Gregorc34897d2009-04-09 22:27:44 +0000193void PCHTypeWriter::VisitTagType(const TagType *T) {
194 Writer.AddDeclRef(T->getDecl(), Record);
195 assert(!T->isBeingDefined() &&
196 "Cannot serialize in the middle of a type definition");
197}
198
199void PCHTypeWriter::VisitRecordType(const RecordType *T) {
200 VisitTagType(T);
201 Code = pch::TYPE_RECORD;
202}
203
204void PCHTypeWriter::VisitEnumType(const EnumType *T) {
205 VisitTagType(T);
206 Code = pch::TYPE_ENUM;
207}
208
209void
210PCHTypeWriter::VisitTemplateSpecializationType(
211 const TemplateSpecializationType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000212 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000213 assert(false && "Cannot serialize template specialization types");
214}
215
216void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000217 // FIXME: Serialize this type (C++ only)
Douglas Gregorc34897d2009-04-09 22:27:44 +0000218 assert(false && "Cannot serialize qualified name types");
219}
220
221void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
222 Writer.AddDeclRef(T->getDecl(), Record);
223 Code = pch::TYPE_OBJC_INTERFACE;
224}
225
226void
227PCHTypeWriter::VisitObjCQualifiedInterfaceType(
228 const ObjCQualifiedInterfaceType *T) {
229 VisitObjCInterfaceType(T);
230 Record.push_back(T->getNumProtocols());
Steve Naroff83418522009-05-27 16:21:00 +0000231 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
232 E = T->qual_end(); I != E; ++I)
233 Writer.AddDeclRef(*I, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000234 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
235}
236
Steve Naroffc75c1a82009-06-17 22:40:22 +0000237void
238PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
239 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000240 Record.push_back(T->getNumProtocols());
Steve Naroffc75c1a82009-06-17 22:40:22 +0000241 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff83418522009-05-27 16:21:00 +0000242 E = T->qual_end(); I != E; ++I)
243 Writer.AddDeclRef(*I, Record);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000244 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000245}
246
Chris Lattner80f83c62009-04-22 05:57:30 +0000247//===----------------------------------------------------------------------===//
Douglas Gregorc34897d2009-04-09 22:27:44 +0000248// PCHWriter Implementation
249//===----------------------------------------------------------------------===//
250
Chris Lattner920673a2009-04-26 22:26:21 +0000251static void EmitBlockID(unsigned ID, const char *Name,
252 llvm::BitstreamWriter &Stream,
253 PCHWriter::RecordData &Record) {
254 Record.clear();
255 Record.push_back(ID);
256 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
257
258 // Emit the block name if present.
259 if (Name == 0 || Name[0] == 0) return;
260 Record.clear();
261 while (*Name)
262 Record.push_back(*Name++);
263 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
264}
265
266static void EmitRecordID(unsigned ID, const char *Name,
267 llvm::BitstreamWriter &Stream,
268 PCHWriter::RecordData &Record) {
269 Record.clear();
270 Record.push_back(ID);
271 while (*Name)
272 Record.push_back(*Name++);
273 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000274}
275
276static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
277 PCHWriter::RecordData &Record) {
278#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
279 RECORD(STMT_STOP);
280 RECORD(STMT_NULL_PTR);
281 RECORD(STMT_NULL);
282 RECORD(STMT_COMPOUND);
283 RECORD(STMT_CASE);
284 RECORD(STMT_DEFAULT);
285 RECORD(STMT_LABEL);
286 RECORD(STMT_IF);
287 RECORD(STMT_SWITCH);
288 RECORD(STMT_WHILE);
289 RECORD(STMT_DO);
290 RECORD(STMT_FOR);
291 RECORD(STMT_GOTO);
292 RECORD(STMT_INDIRECT_GOTO);
293 RECORD(STMT_CONTINUE);
294 RECORD(STMT_BREAK);
295 RECORD(STMT_RETURN);
296 RECORD(STMT_DECL);
297 RECORD(STMT_ASM);
298 RECORD(EXPR_PREDEFINED);
299 RECORD(EXPR_DECL_REF);
300 RECORD(EXPR_INTEGER_LITERAL);
301 RECORD(EXPR_FLOATING_LITERAL);
302 RECORD(EXPR_IMAGINARY_LITERAL);
303 RECORD(EXPR_STRING_LITERAL);
304 RECORD(EXPR_CHARACTER_LITERAL);
305 RECORD(EXPR_PAREN);
306 RECORD(EXPR_UNARY_OPERATOR);
307 RECORD(EXPR_SIZEOF_ALIGN_OF);
308 RECORD(EXPR_ARRAY_SUBSCRIPT);
309 RECORD(EXPR_CALL);
310 RECORD(EXPR_MEMBER);
311 RECORD(EXPR_BINARY_OPERATOR);
312 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
313 RECORD(EXPR_CONDITIONAL_OPERATOR);
314 RECORD(EXPR_IMPLICIT_CAST);
315 RECORD(EXPR_CSTYLE_CAST);
316 RECORD(EXPR_COMPOUND_LITERAL);
317 RECORD(EXPR_EXT_VECTOR_ELEMENT);
318 RECORD(EXPR_INIT_LIST);
319 RECORD(EXPR_DESIGNATED_INIT);
320 RECORD(EXPR_IMPLICIT_VALUE_INIT);
321 RECORD(EXPR_VA_ARG);
322 RECORD(EXPR_ADDR_LABEL);
323 RECORD(EXPR_STMT);
324 RECORD(EXPR_TYPES_COMPATIBLE);
325 RECORD(EXPR_CHOOSE);
326 RECORD(EXPR_GNU_NULL);
327 RECORD(EXPR_SHUFFLE_VECTOR);
328 RECORD(EXPR_BLOCK);
329 RECORD(EXPR_BLOCK_DECL_REF);
330 RECORD(EXPR_OBJC_STRING_LITERAL);
331 RECORD(EXPR_OBJC_ENCODE);
332 RECORD(EXPR_OBJC_SELECTOR_EXPR);
333 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
334 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
335 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
336 RECORD(EXPR_OBJC_KVC_REF_EXPR);
337 RECORD(EXPR_OBJC_MESSAGE_EXPR);
338 RECORD(EXPR_OBJC_SUPER_EXPR);
339 RECORD(STMT_OBJC_FOR_COLLECTION);
340 RECORD(STMT_OBJC_CATCH);
341 RECORD(STMT_OBJC_FINALLY);
342 RECORD(STMT_OBJC_AT_TRY);
343 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
344 RECORD(STMT_OBJC_AT_THROW);
345#undef RECORD
Chris Lattner920673a2009-04-26 22:26:21 +0000346}
347
348void PCHWriter::WriteBlockInfoBlock() {
349 RecordData Record;
350 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
351
Chris Lattner880f3f72009-04-27 00:40:25 +0000352#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner920673a2009-04-26 22:26:21 +0000353#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
354
355 // PCH Top-Level Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000356 BLOCK(PCH_BLOCK);
Zhongxing Xu29b61a52009-06-03 09:23:28 +0000357 RECORD(ORIGINAL_FILE_NAME);
Chris Lattner920673a2009-04-26 22:26:21 +0000358 RECORD(TYPE_OFFSET);
359 RECORD(DECL_OFFSET);
360 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorb7064742009-04-27 22:23:34 +0000361 RECORD(METADATA);
Chris Lattner920673a2009-04-26 22:26:21 +0000362 RECORD(IDENTIFIER_OFFSET);
363 RECORD(IDENTIFIER_TABLE);
364 RECORD(EXTERNAL_DEFINITIONS);
365 RECORD(SPECIAL_TYPES);
366 RECORD(STATISTICS);
367 RECORD(TENTATIVE_DEFINITIONS);
368 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
369 RECORD(SELECTOR_OFFSETS);
370 RECORD(METHOD_POOL);
371 RECORD(PP_COUNTER_VALUE);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000372 RECORD(SOURCE_LOCATION_OFFSETS);
373 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000374 RECORD(STAT_CACHE);
Douglas Gregorb36b20d2009-04-27 20:06:05 +0000375 RECORD(EXT_VECTOR_DECLS);
376 RECORD(OBJC_CATEGORY_IMPLEMENTATIONS);
Douglas Gregora252b232009-07-02 17:08:52 +0000377 RECORD(COMMENT_RANGES);
378
Chris Lattner920673a2009-04-26 22:26:21 +0000379 // SourceManager Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000380 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000381 RECORD(SM_SLOC_FILE_ENTRY);
382 RECORD(SM_SLOC_BUFFER_ENTRY);
383 RECORD(SM_SLOC_BUFFER_BLOB);
384 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
385 RECORD(SM_LINE_TABLE);
386 RECORD(SM_HEADER_FILE_INFO);
387
388 // Preprocessor Block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000389 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000390 RECORD(PP_MACRO_OBJECT_LIKE);
391 RECORD(PP_MACRO_FUNCTION_LIKE);
392 RECORD(PP_TOKEN);
393
394 // Types block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000395 BLOCK(TYPES_BLOCK);
Chris Lattner920673a2009-04-26 22:26:21 +0000396 RECORD(TYPE_EXT_QUAL);
397 RECORD(TYPE_FIXED_WIDTH_INT);
398 RECORD(TYPE_COMPLEX);
399 RECORD(TYPE_POINTER);
400 RECORD(TYPE_BLOCK_POINTER);
401 RECORD(TYPE_LVALUE_REFERENCE);
402 RECORD(TYPE_RVALUE_REFERENCE);
403 RECORD(TYPE_MEMBER_POINTER);
404 RECORD(TYPE_CONSTANT_ARRAY);
405 RECORD(TYPE_INCOMPLETE_ARRAY);
406 RECORD(TYPE_VARIABLE_ARRAY);
407 RECORD(TYPE_VECTOR);
408 RECORD(TYPE_EXT_VECTOR);
409 RECORD(TYPE_FUNCTION_PROTO);
410 RECORD(TYPE_FUNCTION_NO_PROTO);
411 RECORD(TYPE_TYPEDEF);
412 RECORD(TYPE_TYPEOF_EXPR);
413 RECORD(TYPE_TYPEOF);
414 RECORD(TYPE_RECORD);
415 RECORD(TYPE_ENUM);
416 RECORD(TYPE_OBJC_INTERFACE);
417 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000418 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000419 // Statements and Exprs can occur in the Types block.
420 AddStmtsExprs(Stream, Record);
421
Chris Lattner920673a2009-04-26 22:26:21 +0000422 // Decls block.
Chris Lattner880f3f72009-04-27 00:40:25 +0000423 BLOCK(DECLS_BLOCK);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000424 RECORD(DECL_ATTR);
425 RECORD(DECL_TRANSLATION_UNIT);
426 RECORD(DECL_TYPEDEF);
427 RECORD(DECL_ENUM);
428 RECORD(DECL_RECORD);
429 RECORD(DECL_ENUM_CONSTANT);
430 RECORD(DECL_FUNCTION);
431 RECORD(DECL_OBJC_METHOD);
432 RECORD(DECL_OBJC_INTERFACE);
433 RECORD(DECL_OBJC_PROTOCOL);
434 RECORD(DECL_OBJC_IVAR);
435 RECORD(DECL_OBJC_AT_DEFS_FIELD);
436 RECORD(DECL_OBJC_CLASS);
437 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
438 RECORD(DECL_OBJC_CATEGORY);
439 RECORD(DECL_OBJC_CATEGORY_IMPL);
440 RECORD(DECL_OBJC_IMPLEMENTATION);
441 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
442 RECORD(DECL_OBJC_PROPERTY);
443 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner920673a2009-04-26 22:26:21 +0000444 RECORD(DECL_FIELD);
445 RECORD(DECL_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000446 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner920673a2009-04-26 22:26:21 +0000447 RECORD(DECL_PARM_VAR);
Chris Lattner8a0e3162009-04-26 22:32:16 +0000448 RECORD(DECL_ORIGINAL_PARM_VAR);
449 RECORD(DECL_FILE_SCOPE_ASM);
450 RECORD(DECL_BLOCK);
451 RECORD(DECL_CONTEXT_LEXICAL);
452 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerd16afaa2009-04-27 00:49:53 +0000453 // Statements and Exprs can occur in the Decls block.
454 AddStmtsExprs(Stream, Record);
Chris Lattner920673a2009-04-26 22:26:21 +0000455#undef RECORD
456#undef BLOCK
457 Stream.ExitBlock();
458}
459
460
Douglas Gregorb7064742009-04-27 22:23:34 +0000461/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000462void PCHWriter::WriteMetadata(ASTContext &Context) {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000463 using namespace llvm;
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000464
465 // Original file name
466 SourceManager &SM = Context.getSourceManager();
467 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
468 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
469 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
470 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
471 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
472
473 llvm::sys::Path MainFilePath(MainFile->getName());
474 std::string MainFileName;
475
476 if (!MainFilePath.isAbsolute()) {
477 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
478 P.appendComponent(MainFilePath.toString());
479 MainFileName = P.toString();
480 } else {
481 MainFileName = MainFilePath.toString();
482 }
483
484 RecordData Record;
485 Record.push_back(pch::ORIGINAL_FILE_NAME);
486 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileName.c_str(),
487 MainFileName.size());
488 }
489
490 // Metadata
491 const TargetInfo &Target = Context.Target;
492 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
493 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
494 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
495 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
496 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
497 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
498 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
499 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000500
501 RecordData Record;
Douglas Gregorb7064742009-04-27 22:23:34 +0000502 Record.push_back(pch::METADATA);
503 Record.push_back(pch::VERSION_MAJOR);
504 Record.push_back(pch::VERSION_MINOR);
505 Record.push_back(CLANG_VERSION_MAJOR);
506 Record.push_back(CLANG_VERSION_MINOR);
Douglas Gregorb5887f32009-04-10 21:16:55 +0000507 const char *Triple = Target.getTargetTriple();
Douglas Gregoreccf0d12009-05-12 01:31:05 +0000508 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple, strlen(Triple));
Douglas Gregorb5887f32009-04-10 21:16:55 +0000509}
510
511/// \brief Write the LangOptions structure.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000512void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
513 RecordData Record;
514 Record.push_back(LangOpts.Trigraphs);
515 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
516 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
517 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
518 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
519 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
520 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
521 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
522 Record.push_back(LangOpts.C99); // C99 Support
523 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
524 Record.push_back(LangOpts.CPlusPlus); // C++ Support
525 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor179cfb12009-04-10 20:39:37 +0000526 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
527
528 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
529 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
530 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
531
532 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor179cfb12009-04-10 20:39:37 +0000533 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
534 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begeman909e06e2009-06-25 23:01:11 +0000535 Record.push_back(LangOpts.AltiVec);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000536 Record.push_back(LangOpts.Exceptions); // Support exception handling.
537
538 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
539 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
540 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
541
Chris Lattnercd4da472009-04-27 07:35:58 +0000542 // Whether static initializers are protected by locks.
543 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000544 Record.push_back(LangOpts.Blocks); // block extension to C
545 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
546 // they are unused.
547 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
548 // (modulo the platform support).
549
550 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
551 // signed integer arithmetic overflows.
552
553 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
554 // may be ripped out at any time.
555
556 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
557 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
558 // defined.
559 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
560 // opposed to __DYNAMIC__).
561 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
562
563 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
564 // used (instead of C99 semantics).
565 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssonf2310142009-05-13 19:49:53 +0000566 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
567 // be enabled.
Eli Friedmand9389be2009-06-05 07:05:05 +0000568 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
569 // unsigned type
Douglas Gregor179cfb12009-04-10 20:39:37 +0000570 Record.push_back(LangOpts.getGCMode());
571 Record.push_back(LangOpts.getVisibilityMode());
572 Record.push_back(LangOpts.InstantiationDepth);
Nate Begeman909e06e2009-06-25 23:01:11 +0000573 Record.push_back(LangOpts.OpenCL);
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000574 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor179cfb12009-04-10 20:39:37 +0000575}
576
Douglas Gregorab1cef72009-04-10 03:52:48 +0000577//===----------------------------------------------------------------------===//
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000578// stat cache Serialization
579//===----------------------------------------------------------------------===//
580
581namespace {
582// Trait used for the on-disk hash table of stat cache results.
583class VISIBILITY_HIDDEN PCHStatCacheTrait {
584public:
585 typedef const char * key_type;
586 typedef key_type key_type_ref;
587
588 typedef std::pair<int, struct stat> data_type;
589 typedef const data_type& data_type_ref;
590
591 static unsigned ComputeHash(const char *path) {
592 return BernsteinHash(path);
593 }
594
595 std::pair<unsigned,unsigned>
596 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
597 data_type_ref Data) {
598 unsigned StrLen = strlen(path);
599 clang::io::Emit16(Out, StrLen);
600 unsigned DataLen = 1; // result value
601 if (Data.first == 0)
602 DataLen += 4 + 4 + 2 + 8 + 8;
603 clang::io::Emit8(Out, DataLen);
604 return std::make_pair(StrLen + 1, DataLen);
605 }
606
607 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
608 Out.write(path, KeyLen);
609 }
610
611 void EmitData(llvm::raw_ostream& Out, key_type_ref,
612 data_type_ref Data, unsigned DataLen) {
613 using namespace clang::io;
614 uint64_t Start = Out.tell(); (void)Start;
615
616 // Result of stat()
617 Emit8(Out, Data.first? 1 : 0);
618
619 if (Data.first == 0) {
620 Emit32(Out, (uint32_t) Data.second.st_ino);
621 Emit32(Out, (uint32_t) Data.second.st_dev);
622 Emit16(Out, (uint16_t) Data.second.st_mode);
623 Emit64(Out, (uint64_t) Data.second.st_mtime);
624 Emit64(Out, (uint64_t) Data.second.st_size);
625 }
626
627 assert(Out.tell() - Start == DataLen && "Wrong data length");
628 }
629};
630} // end anonymous namespace
631
632/// \brief Write the stat() system call cache to the PCH file.
633void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
634 // Build the on-disk hash table containing information about every
635 // stat() call.
636 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
637 unsigned NumStatEntries = 0;
638 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
639 StatEnd = StatCalls.end();
640 Stat != StatEnd; ++Stat, ++NumStatEntries)
641 Generator.insert(Stat->first(), Stat->second);
642
643 // Create the on-disk hash table in a buffer.
644 llvm::SmallVector<char, 4096> StatCacheData;
645 uint32_t BucketOffset;
646 {
647 llvm::raw_svector_ostream Out(StatCacheData);
648 // Make sure that no bucket is at offset 0
649 clang::io::Emit32(Out, 0);
650 BucketOffset = Generator.Emit(Out);
651 }
652
653 // Create a blob abbreviation
654 using namespace llvm;
655 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
656 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
657 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
658 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
659 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
660 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
661
662 // Write the stat cache
663 RecordData Record;
664 Record.push_back(pch::STAT_CACHE);
665 Record.push_back(BucketOffset);
666 Record.push_back(NumStatEntries);
667 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record,
668 &StatCacheData.front(),
669 StatCacheData.size());
670}
671
672//===----------------------------------------------------------------------===//
Douglas Gregorab1cef72009-04-10 03:52:48 +0000673// Source Manager Serialization
674//===----------------------------------------------------------------------===//
675
676/// \brief Create an abbreviation for the SLocEntry that refers to a
677/// file.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000678static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000679 using namespace llvm;
680 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
681 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
682 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorab1cef72009-04-10 03:52:48 +0000686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000687 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000688}
689
690/// \brief Create an abbreviation for the SLocEntry that refers to a
691/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000692static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000693 using namespace llvm;
694 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
695 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000701 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000702}
703
704/// \brief Create an abbreviation for the SLocEntry that refers to a
705/// buffer's blob.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000706static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000707 using namespace llvm;
708 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
709 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
710 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000711 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000712}
713
714/// \brief Create an abbreviation for the SLocEntry that refers to an
715/// buffer.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000716static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000717 using namespace llvm;
718 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
719 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
721 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor364e5802009-04-15 18:05:10 +0000724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000725 return Stream.EmitAbbrev(Abbrev);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000726}
727
728/// \brief Writes the block containing the serialized form of the
729/// source manager.
730///
731/// TODO: We should probably use an on-disk hash table (stored in a
732/// blob), indexed based on the file name, so that we only create
733/// entries for files that we actually need. In the common case (no
734/// errors), we probably won't have to create file entries for any of
735/// the files in the AST.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000736void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
737 const Preprocessor &PP) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000738 RecordData Record;
739
Chris Lattner84b04f12009-04-10 17:16:57 +0000740 // Enter the source manager block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000741 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000742
743 // Abbreviations for the various kinds of source-location entries.
Chris Lattnereb559a62009-04-27 19:03:22 +0000744 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
745 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
746 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
747 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000748
Douglas Gregor635f97f2009-04-13 16:31:14 +0000749 // Write the line table.
750 if (SourceMgr.hasLineTable()) {
751 LineTableInfo &LineTable = SourceMgr.getLineTable();
752
753 // Emit the file names
754 Record.push_back(LineTable.getNumFilenames());
755 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
756 // Emit the file name
757 const char *Filename = LineTable.getFilename(I);
758 unsigned FilenameLen = Filename? strlen(Filename) : 0;
759 Record.push_back(FilenameLen);
760 if (FilenameLen)
761 Record.insert(Record.end(), Filename, Filename + FilenameLen);
762 }
763
764 // Emit the line entries
765 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
766 L != LEnd; ++L) {
767 // Emit the file ID
768 Record.push_back(L->first);
769
770 // Emit the line entries
771 Record.push_back(L->second.size());
772 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
773 LEEnd = L->second.end();
774 LE != LEEnd; ++LE) {
775 Record.push_back(LE->FileOffset);
776 Record.push_back(LE->LineNo);
777 Record.push_back(LE->FilenameID);
778 Record.push_back((unsigned)LE->FileKind);
779 Record.push_back(LE->IncludeOffset);
780 }
Douglas Gregor635f97f2009-04-13 16:31:14 +0000781 }
Zhongxing Xu01838482009-05-22 08:38:27 +0000782 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor635f97f2009-04-13 16:31:14 +0000783 }
784
Douglas Gregor32e231c2009-04-27 06:38:32 +0000785 // Write out entries for all of the header files we know about.
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000786 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000787 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000788 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
789 E = HS.header_file_end();
790 I != E; ++I) {
791 Record.push_back(I->isImport);
792 Record.push_back(I->DirInfo);
793 Record.push_back(I->NumIncludes);
Douglas Gregor32e231c2009-04-27 06:38:32 +0000794 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000795 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
796 Record.clear();
797 }
798
Douglas Gregor32e231c2009-04-27 06:38:32 +0000799 // Write out the source location entry table. We skip the first
800 // entry, which is always the same dummy entry.
Chris Lattner93307da2009-04-27 19:01:47 +0000801 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000802 RecordData PreloadSLocs;
803 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
804 for (SourceManager::sloc_entry_iterator
805 SLoc = SourceMgr.sloc_entry_begin() + 1,
806 SLocEnd = SourceMgr.sloc_entry_end();
807 SLoc != SLocEnd; ++SLoc) {
808 // Record the offset of this source-location entry.
809 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
810
811 // Figure out which record code to use.
812 unsigned Code;
813 if (SLoc->isFile()) {
814 if (SLoc->getFile().getContentCache()->Entry)
815 Code = pch::SM_SLOC_FILE_ENTRY;
816 else
817 Code = pch::SM_SLOC_BUFFER_ENTRY;
818 } else
819 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
820 Record.clear();
821 Record.push_back(Code);
822
823 Record.push_back(SLoc->getOffset());
824 if (SLoc->isFile()) {
825 const SrcMgr::FileInfo &File = SLoc->getFile();
826 Record.push_back(File.getIncludeLoc().getRawEncoding());
827 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
828 Record.push_back(File.hasLineDirectives());
829
830 const SrcMgr::ContentCache *Content = File.getContentCache();
831 if (Content->Entry) {
832 // The source location entry is a file. The blob associated
833 // with this entry is the file name.
834 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
835 Content->Entry->getName(),
836 strlen(Content->Entry->getName()));
837
838 // FIXME: For now, preload all file source locations, so that
839 // we get the appropriate File entries in the reader. This is
840 // a temporary measure.
841 PreloadSLocs.push_back(SLocEntryOffsets.size());
842 } else {
843 // The source location entry is a buffer. The blob associated
844 // with this entry contains the contents of the buffer.
845
846 // We add one to the size so that we capture the trailing NULL
847 // that is required by llvm::MemoryBuffer::getMemBuffer (on
848 // the reader side).
849 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
850 const char *Name = Buffer->getBufferIdentifier();
851 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
852 Record.clear();
853 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
854 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
855 Buffer->getBufferStart(),
856 Buffer->getBufferSize() + 1);
857
858 if (strcmp(Name, "<built-in>") == 0)
859 PreloadSLocs.push_back(SLocEntryOffsets.size());
860 }
861 } else {
862 // The source location entry is an instantiation.
863 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
864 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
865 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
866 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
867
868 // Compute the token length for this macro expansion.
869 unsigned NextOffset = SourceMgr.getNextOffset();
870 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
871 if (++NextSLoc != SLocEnd)
872 NextOffset = NextSLoc->getOffset();
873 Record.push_back(NextOffset - SLoc->getOffset() - 1);
874 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
875 }
876 }
877
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000878 Stream.ExitBlock();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000879
880 if (SLocEntryOffsets.empty())
881 return;
882
883 // Write the source-location offsets table into the PCH block. This
884 // table is used for lazily loading source-location information.
885 using namespace llvm;
886 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
887 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
888 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
891 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
892
893 Record.clear();
894 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
895 Record.push_back(SLocEntryOffsets.size());
896 Record.push_back(SourceMgr.getNextOffset());
897 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
898 (const char *)&SLocEntryOffsets.front(),
Chris Lattner93307da2009-04-27 19:01:47 +0000899 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor32e231c2009-04-27 06:38:32 +0000900
901 // Write the source location entry preloads array, telling the PCH
902 // reader which source locations entries it should load eagerly.
903 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000904}
905
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000906//===----------------------------------------------------------------------===//
907// Preprocessor Serialization
908//===----------------------------------------------------------------------===//
909
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000910/// \brief Writes the block containing the serialized form of the
911/// preprocessor.
912///
Chris Lattner850eabd2009-04-10 18:08:30 +0000913void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner1b094952009-04-10 18:00:12 +0000914 RecordData Record;
Chris Lattner84b04f12009-04-10 17:16:57 +0000915
Chris Lattner4b21c202009-04-13 01:29:17 +0000916 // If the preprocessor __COUNTER__ value has been bumped, remember it.
917 if (PP.getCounterValue() != 0) {
918 Record.push_back(PP.getCounterValue());
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000919 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner4b21c202009-04-13 01:29:17 +0000920 Record.clear();
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000921 }
922
923 // Enter the preprocessor block.
924 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattner4b21c202009-04-13 01:29:17 +0000925
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000926 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
927 // FIXME: use diagnostics subsystem for localization etc.
928 if (PP.SawDateOrTime())
929 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
930
Chris Lattner1b094952009-04-10 18:00:12 +0000931 // Loop over all the macro definitions that are live at the end of the file,
932 // emitting each to the PP section.
Chris Lattner1b094952009-04-10 18:00:12 +0000933 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
934 I != E; ++I) {
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000935 // FIXME: This emits macros in hash table order, we should do it in a stable
936 // order so that output is reproducible.
Chris Lattner1b094952009-04-10 18:00:12 +0000937 MacroInfo *MI = I->second;
938
939 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
940 // been redefined by the header (in which case they are not isBuiltinMacro).
941 if (MI->isBuiltinMacro())
942 continue;
943
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000944 // FIXME: Remove this identifier reference?
Chris Lattner29241862009-04-11 21:15:38 +0000945 AddIdentifierRef(I->first, Record);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000946 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner1b094952009-04-10 18:00:12 +0000947 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
948 Record.push_back(MI->isUsed());
949
950 unsigned Code;
951 if (MI->isObjectLike()) {
952 Code = pch::PP_MACRO_OBJECT_LIKE;
953 } else {
954 Code = pch::PP_MACRO_FUNCTION_LIKE;
955
956 Record.push_back(MI->isC99Varargs());
957 Record.push_back(MI->isGNUVarargs());
958 Record.push_back(MI->getNumArgs());
959 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
960 I != E; ++I)
Chris Lattner29241862009-04-11 21:15:38 +0000961 AddIdentifierRef(*I, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000962 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000963 Stream.EmitRecord(Code, Record);
Chris Lattner1b094952009-04-10 18:00:12 +0000964 Record.clear();
965
Chris Lattner850eabd2009-04-10 18:08:30 +0000966 // Emit the tokens array.
967 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
968 // Note that we know that the preprocessor does not have any annotation
969 // tokens in it because they are created by the parser, and thus can't be
970 // in a macro definition.
971 const Token &Tok = MI->getReplacementToken(TokNo);
972
973 Record.push_back(Tok.getLocation().getRawEncoding());
974 Record.push_back(Tok.getLength());
975
Chris Lattner850eabd2009-04-10 18:08:30 +0000976 // FIXME: When reading literal tokens, reconstruct the literal pointer if
977 // it is needed.
Chris Lattner29241862009-04-11 21:15:38 +0000978 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000979
980 // FIXME: Should translate token kind to a stable encoding.
981 Record.push_back(Tok.getKind());
982 // FIXME: Should translate token flags to a stable encoding.
983 Record.push_back(Tok.getFlags());
984
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000985 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner850eabd2009-04-10 18:08:30 +0000986 Record.clear();
987 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000988 ++NumMacros;
Chris Lattner1b094952009-04-10 18:00:12 +0000989 }
Douglas Gregorc72f6c82009-04-16 22:23:12 +0000990 Stream.ExitBlock();
Chris Lattnerffc05ed2009-04-10 17:15:23 +0000991}
992
Douglas Gregora252b232009-07-02 17:08:52 +0000993void PCHWriter::WriteComments(ASTContext &Context) {
994 using namespace llvm;
995
996 if (Context.Comments.empty())
997 return;
998
999 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1000 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1001 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1002 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1003
1004 RecordData Record;
1005 Record.push_back(pch::COMMENT_RANGES);
1006 Stream.EmitRecordWithBlob(CommentCode, Record,
1007 (const char*)&Context.Comments[0],
1008 Context.Comments.size() * sizeof(SourceRange));
1009}
1010
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001011//===----------------------------------------------------------------------===//
1012// Type Serialization
1013//===----------------------------------------------------------------------===//
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001014
Douglas Gregorc34897d2009-04-09 22:27:44 +00001015/// \brief Write the representation of a type to the PCH stream.
1016void PCHWriter::WriteType(const Type *T) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001017 pch::TypeID &ID = TypeIDs[T];
Chris Lattner84b04f12009-04-10 17:16:57 +00001018 if (ID == 0) // we haven't seen this type before.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001019 ID = NextTypeID++;
1020
1021 // Record the offset for this type.
1022 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001023 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001024 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1025 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001026 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001027 }
1028
1029 RecordData Record;
1030
1031 // Emit the type's representation.
1032 PCHTypeWriter W(*this, Record);
1033 switch (T->getTypeClass()) {
1034 // For all of the concrete, non-dependent types, call the
1035 // appropriate visitor function.
1036#define TYPE(Class, Base) \
1037 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1038#define ABSTRACT_TYPE(Class, Base)
1039#define DEPENDENT_TYPE(Class, Base)
1040#include "clang/AST/TypeNodes.def"
1041
1042 // For all of the dependent type nodes (which only occur in C++
1043 // templates), produce an error.
1044#define TYPE(Class, Base)
1045#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1046#include "clang/AST/TypeNodes.def"
1047 assert(false && "Cannot serialize dependent type nodes");
1048 break;
1049 }
1050
1051 // Emit the serialized record.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001052 Stream.EmitRecord(W.Code, Record);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001053
1054 // Flush any expressions that were written as part of this type.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001055 FlushStmts();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001056}
1057
1058/// \brief Write a block containing all of the types.
1059void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner84b04f12009-04-10 17:16:57 +00001060 // Enter the types block.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001061 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001062
Douglas Gregore43f0972009-04-26 03:49:13 +00001063 // Emit all of the types that need to be emitted (so far).
1064 while (!TypesToEmit.empty()) {
1065 const Type *T = TypesToEmit.front();
1066 TypesToEmit.pop();
1067 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
1068 WriteType(T);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001069 }
1070
1071 // Exit the types block
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001072 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001073}
1074
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001075//===----------------------------------------------------------------------===//
1076// Declaration Serialization
1077//===----------------------------------------------------------------------===//
1078
Douglas Gregorc34897d2009-04-09 22:27:44 +00001079/// \brief Write the block containing all of the declaration IDs
1080/// lexically declared within the given DeclContext.
1081///
1082/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1083/// bistream, or 0 if no block was written.
1084uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1085 DeclContext *DC) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001086 if (DC->decls_empty())
Douglas Gregorc34897d2009-04-09 22:27:44 +00001087 return 0;
1088
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001089 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001090 RecordData Record;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001091 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1092 D != DEnd; ++D)
Douglas Gregorc34897d2009-04-09 22:27:44 +00001093 AddDeclRef(*D, Record);
1094
Douglas Gregoraf136d92009-04-22 22:34:57 +00001095 ++NumLexicalDeclContexts;
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001096 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001097 return Offset;
1098}
1099
1100/// \brief Write the block containing all of the declaration IDs
1101/// visible from the given DeclContext.
1102///
1103/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1104/// bistream, or 0 if no block was written.
1105uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1106 DeclContext *DC) {
1107 if (DC->getPrimaryContext() != DC)
1108 return 0;
1109
Douglas Gregor35ca85e2009-04-21 22:32:33 +00001110 // Since there is no name lookup into functions or methods, and we
1111 // perform name lookup for the translation unit via the
1112 // IdentifierInfo chains, don't bother to build a
1113 // visible-declarations table for these entities.
1114 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor5afd9802009-04-18 15:49:20 +00001115 return 0;
1116
Douglas Gregorc34897d2009-04-09 22:27:44 +00001117 // Force the DeclContext to build a its name-lookup table.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001118 DC->lookup(DeclarationName());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001119
1120 // Serialize the contents of the mapping used for lookup. Note that,
1121 // although we have two very different code paths, the serialized
1122 // representation is the same for both cases: a declaration name,
1123 // followed by a size, followed by references to the visible
1124 // declarations that have that name.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001125 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001126 RecordData Record;
1127 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor982365e2009-04-13 21:20:57 +00001128 if (!Map)
1129 return 0;
1130
Douglas Gregorc34897d2009-04-09 22:27:44 +00001131 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1132 D != DEnd; ++D) {
1133 AddDeclarationName(D->first, Record);
1134 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1135 Record.push_back(Result.second - Result.first);
1136 for(; Result.first != Result.second; ++Result.first)
1137 AddDeclRef(*Result.first, Record);
1138 }
1139
1140 if (Record.size() == 0)
1141 return 0;
1142
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001143 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001144 ++NumVisibleDeclContexts;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001145 return Offset;
1146}
1147
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001148//===----------------------------------------------------------------------===//
1149// Global Method Pool and Selector Serialization
1150//===----------------------------------------------------------------------===//
1151
Douglas Gregorff9a6092009-04-20 20:36:09 +00001152namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001153// Trait used for the on-disk hash table used in the method pool.
1154class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1155 PCHWriter &Writer;
1156
1157public:
1158 typedef Selector key_type;
1159 typedef key_type key_type_ref;
1160
1161 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1162 typedef const data_type& data_type_ref;
1163
1164 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1165
1166 static unsigned ComputeHash(Selector Sel) {
1167 unsigned N = Sel.getNumArgs();
1168 if (N == 0)
1169 ++N;
1170 unsigned R = 5381;
1171 for (unsigned I = 0; I != N; ++I)
1172 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1173 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1174 return R;
1175 }
1176
1177 std::pair<unsigned,unsigned>
1178 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1179 data_type_ref Methods) {
1180 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1181 clang::io::Emit16(Out, KeyLen);
1182 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1183 for (const ObjCMethodList *Method = &Methods.first; Method;
1184 Method = Method->Next)
1185 if (Method->Method)
1186 DataLen += 4;
1187 for (const ObjCMethodList *Method = &Methods.second; Method;
1188 Method = Method->Next)
1189 if (Method->Method)
1190 DataLen += 4;
1191 clang::io::Emit16(Out, DataLen);
1192 return std::make_pair(KeyLen, DataLen);
1193 }
1194
Douglas Gregor2d711832009-04-25 17:48:32 +00001195 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1196 uint64_t Start = Out.tell();
1197 assert((Start >> 32) == 0 && "Selector key offset too large");
1198 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001199 unsigned N = Sel.getNumArgs();
1200 clang::io::Emit16(Out, N);
1201 if (N == 0)
1202 N = 1;
1203 for (unsigned I = 0; I != N; ++I)
1204 clang::io::Emit32(Out,
1205 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1206 }
1207
1208 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor9c266982009-04-24 21:49:02 +00001209 data_type_ref Methods, unsigned DataLen) {
1210 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001211 unsigned NumInstanceMethods = 0;
1212 for (const ObjCMethodList *Method = &Methods.first; Method;
1213 Method = Method->Next)
1214 if (Method->Method)
1215 ++NumInstanceMethods;
1216
1217 unsigned NumFactoryMethods = 0;
1218 for (const ObjCMethodList *Method = &Methods.second; Method;
1219 Method = Method->Next)
1220 if (Method->Method)
1221 ++NumFactoryMethods;
1222
1223 clang::io::Emit16(Out, NumInstanceMethods);
1224 clang::io::Emit16(Out, NumFactoryMethods);
1225 for (const ObjCMethodList *Method = &Methods.first; Method;
1226 Method = Method->Next)
1227 if (Method->Method)
1228 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001229 for (const ObjCMethodList *Method = &Methods.second; Method;
1230 Method = Method->Next)
1231 if (Method->Method)
1232 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor9c266982009-04-24 21:49:02 +00001233
1234 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001235 }
1236};
1237} // end anonymous namespace
1238
1239/// \brief Write the method pool into the PCH file.
1240///
1241/// The method pool contains both instance and factory methods, stored
1242/// in an on-disk hash table indexed by the selector.
1243void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1244 using namespace llvm;
1245
1246 // Create and write out the blob that contains the instance and
1247 // factor method pools.
1248 bool Empty = true;
1249 {
1250 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1251
1252 // Create the on-disk hash table representation. Start by
1253 // iterating through the instance method pool.
1254 PCHMethodPoolTrait::key_type Key;
Douglas Gregor2d711832009-04-25 17:48:32 +00001255 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001256 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1257 Instance = SemaRef.InstanceMethodPool.begin(),
1258 InstanceEnd = SemaRef.InstanceMethodPool.end();
1259 Instance != InstanceEnd; ++Instance) {
1260 // Check whether there is a factory method with the same
1261 // selector.
1262 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1263 = SemaRef.FactoryMethodPool.find(Instance->first);
1264
1265 if (Factory == SemaRef.FactoryMethodPool.end())
1266 Generator.insert(Instance->first,
1267 std::make_pair(Instance->second,
1268 ObjCMethodList()));
1269 else
1270 Generator.insert(Instance->first,
1271 std::make_pair(Instance->second, Factory->second));
1272
Douglas Gregor2d711832009-04-25 17:48:32 +00001273 ++NumSelectorsInMethodPool;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001274 Empty = false;
1275 }
1276
1277 // Now iterate through the factory method pool, to pick up any
1278 // selectors that weren't already in the instance method pool.
1279 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1280 Factory = SemaRef.FactoryMethodPool.begin(),
1281 FactoryEnd = SemaRef.FactoryMethodPool.end();
1282 Factory != FactoryEnd; ++Factory) {
1283 // Check whether there is an instance method with the same
1284 // selector. If so, there is no work to do here.
1285 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1286 = SemaRef.InstanceMethodPool.find(Factory->first);
1287
Douglas Gregor2d711832009-04-25 17:48:32 +00001288 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001289 Generator.insert(Factory->first,
1290 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor2d711832009-04-25 17:48:32 +00001291 ++NumSelectorsInMethodPool;
1292 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001293
1294 Empty = false;
1295 }
1296
Douglas Gregor2d711832009-04-25 17:48:32 +00001297 if (Empty && SelectorOffsets.empty())
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001298 return;
1299
1300 // Create the on-disk hash table in a buffer.
1301 llvm::SmallVector<char, 4096> MethodPool;
1302 uint32_t BucketOffset;
Douglas Gregor2d711832009-04-25 17:48:32 +00001303 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001304 {
1305 PCHMethodPoolTrait Trait(*this);
1306 llvm::raw_svector_ostream Out(MethodPool);
1307 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001308 clang::io::Emit32(Out, 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001309 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor2d711832009-04-25 17:48:32 +00001310
1311 // For every selector that we have seen but which was not
1312 // written into the hash table, write the selector itself and
1313 // record it's offset.
1314 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1315 if (SelectorOffsets[I] == 0)
1316 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001317 }
1318
1319 // Create a blob abbreviation
1320 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1321 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1322 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor2d711832009-04-25 17:48:32 +00001323 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001324 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1325 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1326
Douglas Gregor2d711832009-04-25 17:48:32 +00001327 // Write the method pool
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001328 RecordData Record;
1329 Record.push_back(pch::METHOD_POOL);
1330 Record.push_back(BucketOffset);
Douglas Gregor2d711832009-04-25 17:48:32 +00001331 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001332 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1333 &MethodPool.front(),
1334 MethodPool.size());
Douglas Gregor2d711832009-04-25 17:48:32 +00001335
1336 // Create a blob abbreviation for the selector table offsets.
1337 Abbrev = new BitCodeAbbrev();
1338 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1339 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1340 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1341 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1342
1343 // Write the selector offsets table.
1344 Record.clear();
1345 Record.push_back(pch::SELECTOR_OFFSETS);
1346 Record.push_back(SelectorOffsets.size());
1347 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1348 (const char *)&SelectorOffsets.front(),
1349 SelectorOffsets.size() * 4);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001350 }
1351}
1352
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001353//===----------------------------------------------------------------------===//
1354// Identifier Table Serialization
1355//===----------------------------------------------------------------------===//
1356
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001357namespace {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001358class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1359 PCHWriter &Writer;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001360 Preprocessor &PP;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001361
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001362 /// \brief Determines whether this is an "interesting" identifier
1363 /// that needs a full IdentifierInfo structure written into the hash
1364 /// table.
1365 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1366 return II->isPoisoned() ||
1367 II->isExtensionToken() ||
1368 II->hasMacroDefinition() ||
1369 II->getObjCOrBuiltinID() ||
1370 II->getFETokenInfo<void>();
1371 }
1372
Douglas Gregorff9a6092009-04-20 20:36:09 +00001373public:
1374 typedef const IdentifierInfo* key_type;
1375 typedef key_type key_type_ref;
1376
1377 typedef pch::IdentID data_type;
1378 typedef data_type data_type_ref;
1379
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001380 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1381 : Writer(Writer), PP(PP) { }
Douglas Gregorff9a6092009-04-20 20:36:09 +00001382
1383 static unsigned ComputeHash(const IdentifierInfo* II) {
1384 return clang::BernsteinHash(II->getName());
1385 }
1386
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001387 std::pair<unsigned,unsigned>
Douglas Gregorff9a6092009-04-20 20:36:09 +00001388 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1389 pch::IdentID ID) {
1390 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001391 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1392 if (isInterestingIdentifier(II)) {
Douglas Gregor67d91172009-04-28 21:32:13 +00001393 DataLen += 2; // 2 bytes for builtin ID, flags
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001394 if (II->hasMacroDefinition() &&
1395 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor67d91172009-04-28 21:32:13 +00001396 DataLen += 4;
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001397 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1398 DEnd = IdentifierResolver::end();
1399 D != DEnd; ++D)
1400 DataLen += sizeof(pch::DeclID);
1401 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001402 clang::io::Emit16(Out, DataLen);
Douglas Gregor68619772009-04-28 20:01:51 +00001403 // We emit the key length after the data length so that every
1404 // string is preceded by a 16-bit length. This matches the PTH
1405 // format for storing identifiers.
Douglas Gregor85c4a872009-04-25 21:04:17 +00001406 clang::io::Emit16(Out, KeyLen);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001407 return std::make_pair(KeyLen, DataLen);
1408 }
1409
1410 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1411 unsigned KeyLen) {
1412 // Record the location of the key data. This is used when generating
1413 // the mapping from persistent IDs to strings.
1414 Writer.SetIdentifierOffset(II, Out.tell());
1415 Out.write(II->getName(), KeyLen);
1416 }
1417
1418 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1419 pch::IdentID ID, unsigned) {
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001420 if (!isInterestingIdentifier(II)) {
1421 clang::io::Emit32(Out, ID << 1);
1422 return;
1423 }
Douglas Gregor67d91172009-04-28 21:32:13 +00001424
Douglas Gregor2c09dad2009-04-28 21:18:29 +00001425 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001426 uint32_t Bits = 0;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001427 bool hasMacroDefinition =
1428 II->hasMacroDefinition() &&
1429 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor67d91172009-04-28 21:32:13 +00001430 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001431 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001432 Bits = (Bits << 1) | II->isExtensionToken();
1433 Bits = (Bits << 1) | II->isPoisoned();
1434 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor67d91172009-04-28 21:32:13 +00001435 clang::io::Emit16(Out, Bits);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001436
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001437 if (hasMacroDefinition)
Douglas Gregor67d91172009-04-28 21:32:13 +00001438 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001439
Douglas Gregorc713da92009-04-21 22:25:48 +00001440 // Emit the declaration IDs in reverse order, because the
1441 // IdentifierResolver provides the declarations as they would be
1442 // visible (e.g., the function "stat" would come before the struct
1443 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1444 // adds declarations to the end of the list (so we need to see the
1445 // struct "status" before the function "status").
1446 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1447 IdentifierResolver::end());
1448 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1449 DEnd = Decls.rend();
Douglas Gregorff9a6092009-04-20 20:36:09 +00001450 D != DEnd; ++D)
Douglas Gregorc713da92009-04-21 22:25:48 +00001451 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001452 }
1453};
1454} // end anonymous namespace
1455
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001456/// \brief Write the identifier table into the PCH file.
1457///
1458/// The identifier table consists of a blob containing string data
1459/// (the actual identifiers themselves) and a separate "offsets" index
1460/// that maps identifier IDs to locations within the blob.
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001461void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001462 using namespace llvm;
1463
1464 // Create and write out the blob that contains the identifier
1465 // strings.
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001466 {
Douglas Gregorff9a6092009-04-20 20:36:09 +00001467 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1468
Douglas Gregor91137812009-04-28 20:33:11 +00001469 // Look for any identifiers that were named while processing the
1470 // headers, but are otherwise not needed. We add these to the hash
1471 // table to enable checking of the predefines buffer in the case
1472 // where the user adds new macro definitions when building the PCH
1473 // file.
1474 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1475 IDEnd = PP.getIdentifierTable().end();
1476 ID != IDEnd; ++ID)
1477 getIdentifierRef(ID->second);
1478
Douglas Gregorff9a6092009-04-20 20:36:09 +00001479 // Create the on-disk hash table representation.
Douglas Gregor91137812009-04-28 20:33:11 +00001480 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001481 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1482 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1483 ID != IDEnd; ++ID) {
1484 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor68619772009-04-28 20:01:51 +00001485 Generator.insert(ID->first, ID->second);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001486 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001487
Douglas Gregorff9a6092009-04-20 20:36:09 +00001488 // Create the on-disk hash table in a buffer.
1489 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregorc713da92009-04-21 22:25:48 +00001490 uint32_t BucketOffset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001491 {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001492 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001493 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001494 // Make sure that no bucket is at offset 0
Douglas Gregor9c266982009-04-24 21:49:02 +00001495 clang::io::Emit32(Out, 0);
Douglas Gregorc713da92009-04-21 22:25:48 +00001496 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001497 }
1498
1499 // Create a blob abbreviation
1500 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1501 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregorc713da92009-04-21 22:25:48 +00001502 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorff9a6092009-04-20 20:36:09 +00001503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001504 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001505
1506 // Write the identifier table
1507 RecordData Record;
1508 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregorc713da92009-04-21 22:25:48 +00001509 Record.push_back(BucketOffset);
Douglas Gregorff9a6092009-04-20 20:36:09 +00001510 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1511 &IdentifierTable.front(),
1512 IdentifierTable.size());
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001513 }
1514
1515 // Write the offsets table for identifier IDs.
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001516 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1517 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1519 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1520 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1521
1522 RecordData Record;
1523 Record.push_back(pch::IDENTIFIER_OFFSET);
1524 Record.push_back(IdentifierOffsets.size());
1525 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1526 (const char *)&IdentifierOffsets.front(),
1527 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001528}
1529
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001530//===----------------------------------------------------------------------===//
1531// General Serialization Routines
1532//===----------------------------------------------------------------------===//
1533
Douglas Gregor1c507882009-04-15 21:30:51 +00001534/// \brief Write a record containing the given attributes.
1535void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1536 RecordData Record;
1537 for (; Attr; Attr = Attr->getNext()) {
1538 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1539 Record.push_back(Attr->isInherited());
1540 switch (Attr->getKind()) {
1541 case Attr::Alias:
1542 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1543 break;
1544
1545 case Attr::Aligned:
1546 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1547 break;
1548
1549 case Attr::AlwaysInline:
1550 break;
1551
1552 case Attr::AnalyzerNoReturn:
1553 break;
1554
1555 case Attr::Annotate:
1556 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1557 break;
1558
1559 case Attr::AsmLabel:
1560 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1561 break;
1562
1563 case Attr::Blocks:
1564 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1565 break;
1566
1567 case Attr::Cleanup:
1568 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1569 break;
1570
1571 case Attr::Const:
1572 break;
1573
1574 case Attr::Constructor:
1575 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1576 break;
1577
1578 case Attr::DLLExport:
1579 case Attr::DLLImport:
1580 case Attr::Deprecated:
1581 break;
1582
1583 case Attr::Destructor:
1584 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1585 break;
1586
1587 case Attr::FastCall:
1588 break;
1589
1590 case Attr::Format: {
1591 const FormatAttr *Format = cast<FormatAttr>(Attr);
1592 AddString(Format->getType(), Record);
1593 Record.push_back(Format->getFormatIdx());
1594 Record.push_back(Format->getFirstArg());
1595 break;
1596 }
1597
Fariborz Jahanian306d7252009-05-20 17:41:43 +00001598 case Attr::FormatArg: {
1599 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1600 Record.push_back(Format->getFormatIdx());
1601 break;
1602 }
1603
Fariborz Jahanian180f3412009-05-13 18:09:35 +00001604 case Attr::Sentinel : {
1605 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1606 Record.push_back(Sentinel->getSentinel());
1607 Record.push_back(Sentinel->getNullPos());
1608 break;
1609 }
1610
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001611 case Attr::GNUInline:
Douglas Gregor1c507882009-04-15 21:30:51 +00001612 case Attr::IBOutletKind:
1613 case Attr::NoReturn:
1614 case Attr::NoThrow:
1615 case Attr::Nodebug:
1616 case Attr::Noinline:
1617 break;
1618
1619 case Attr::NonNull: {
1620 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1621 Record.push_back(NonNull->size());
1622 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1623 break;
1624 }
1625
1626 case Attr::ObjCException:
1627 case Attr::ObjCNSObject:
Ted Kremenek13ddd1a2009-05-09 02:44:38 +00001628 case Attr::CFReturnsRetained:
1629 case Attr::NSReturnsRetained:
Douglas Gregor1c507882009-04-15 21:30:51 +00001630 case Attr::Overloadable:
1631 break;
1632
1633 case Attr::Packed:
1634 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1635 break;
1636
1637 case Attr::Pure:
1638 break;
1639
1640 case Attr::Regparm:
1641 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1642 break;
Nate Begeman60702162009-06-26 06:32:41 +00001643
1644 case Attr::ReqdWorkGroupSize:
1645 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1646 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1647 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1648 break;
Douglas Gregor1c507882009-04-15 21:30:51 +00001649
1650 case Attr::Section:
1651 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1652 break;
1653
1654 case Attr::StdCall:
1655 case Attr::TransparentUnion:
1656 case Attr::Unavailable:
1657 case Attr::Unused:
1658 case Attr::Used:
1659 break;
1660
1661 case Attr::Visibility:
1662 // FIXME: stable encoding
1663 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1664 break;
1665
1666 case Attr::WarnUnusedResult:
1667 case Attr::Weak:
1668 case Attr::WeakImport:
1669 break;
1670 }
1671 }
1672
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001673 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001674}
1675
1676void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1677 Record.push_back(Str.size());
1678 Record.insert(Record.end(), Str.begin(), Str.end());
1679}
1680
Douglas Gregorff9a6092009-04-20 20:36:09 +00001681/// \brief Note that the identifier II occurs at the given offset
1682/// within the identifier table.
1683void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001684 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregorff9a6092009-04-20 20:36:09 +00001685}
1686
Douglas Gregor2d711832009-04-25 17:48:32 +00001687/// \brief Note that the selector Sel occurs at the given offset
1688/// within the method pool/selector table.
1689void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1690 unsigned ID = SelectorIDs[Sel];
1691 assert(ID && "Unknown selector");
1692 SelectorOffsets[ID - 1] = Offset;
1693}
1694
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001695PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001696 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregoraf136d92009-04-22 22:34:57 +00001697 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1698 NumVisibleDeclContexts(0) { }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001699
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001700void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls) {
Douglas Gregor24a224c2009-04-25 18:35:21 +00001701 using namespace llvm;
1702
Douglas Gregor87887da2009-04-20 15:53:59 +00001703 ASTContext &Context = SemaRef.Context;
1704 Preprocessor &PP = SemaRef.PP;
1705
Douglas Gregorc34897d2009-04-09 22:27:44 +00001706 // Emit the file header.
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001707 Stream.Emit((unsigned)'C', 8);
1708 Stream.Emit((unsigned)'P', 8);
1709 Stream.Emit((unsigned)'C', 8);
1710 Stream.Emit((unsigned)'H', 8);
Chris Lattner920673a2009-04-26 22:26:21 +00001711
1712 WriteBlockInfoBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001713
1714 // The translation unit is the first declaration we'll emit.
1715 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1716 DeclsToEmit.push(Context.getTranslationUnitDecl());
1717
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001718 // Make sure that we emit IdentifierInfos (and any attached
1719 // declarations) for builtins.
1720 {
1721 IdentifierTable &Table = PP.getIdentifierTable();
1722 llvm::SmallVector<const char *, 32> BuiltinNames;
1723 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1724 Context.getLangOptions().NoBuiltin);
1725 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1726 getIdentifierRef(&Table.get(BuiltinNames[I]));
1727 }
1728
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001729 // Build a record containing all of the tentative definitions in
1730 // this header file. Generally, this record will be empty.
1731 RecordData TentativeDefinitions;
1732 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1733 TD = SemaRef.TentativeDefinitions.begin(),
1734 TDEnd = SemaRef.TentativeDefinitions.end();
1735 TD != TDEnd; ++TD)
1736 AddDeclRef(TD->second, TentativeDefinitions);
1737
Douglas Gregor062d9482009-04-22 22:18:58 +00001738 // Build a record containing all of the locally-scoped external
1739 // declarations in this header file. Generally, this record will be
1740 // empty.
1741 RecordData LocallyScopedExternalDecls;
1742 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1743 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1744 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1745 TD != TDEnd; ++TD)
1746 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1747
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001748 // Build a record containing all of the ext_vector declarations.
1749 RecordData ExtVectorDecls;
1750 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1751 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1752
1753 // Build a record containing all of the Objective-C category
1754 // implementations.
1755 RecordData ObjCCategoryImpls;
1756 for (unsigned I = 0, N = SemaRef.ObjCCategoryImpls.size(); I != N; ++I)
1757 AddDeclRef(SemaRef.ObjCCategoryImpls[I], ObjCCategoryImpls);
1758
Douglas Gregorc34897d2009-04-09 22:27:44 +00001759 // Write the remaining PCH contents.
Douglas Gregore01ad442009-04-18 05:55:16 +00001760 RecordData Record;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001761 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001762 WriteMetadata(Context);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001763 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001764 if (StatCalls)
1765 WriteStatCache(*StatCalls);
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001766 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattnerffc05ed2009-04-10 17:15:23 +00001767 WritePreprocessor(PP);
Douglas Gregora252b232009-07-02 17:08:52 +00001768 WriteComments(Context);
1769
Douglas Gregore43f0972009-04-26 03:49:13 +00001770 // Keep writing types and declarations until all types and
1771 // declarations have been written.
1772 do {
1773 if (!DeclsToEmit.empty())
1774 WriteDeclsBlock(Context);
1775 if (!TypesToEmit.empty())
1776 WriteTypesBlock(Context);
1777 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1778
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001779 WriteMethodPool(SemaRef);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001780 WriteIdentifierTable(PP);
Douglas Gregor24a224c2009-04-25 18:35:21 +00001781
1782 // Write the type offsets array
1783 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1784 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1787 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1788 Record.clear();
1789 Record.push_back(pch::TYPE_OFFSET);
1790 Record.push_back(TypeOffsets.size());
1791 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1792 (const char *)&TypeOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001793 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001794
1795 // Write the declaration offsets array
1796 Abbrev = new BitCodeAbbrev();
1797 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1800 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1801 Record.clear();
1802 Record.push_back(pch::DECL_OFFSET);
1803 Record.push_back(DeclOffsets.size());
1804 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1805 (const char *)&DeclOffsets.front(),
Chris Lattnerea332f32009-04-27 18:24:17 +00001806 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregore01ad442009-04-18 05:55:16 +00001807
1808 // Write the record of special types.
1809 Record.clear();
1810 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00001811 AddTypeRef(Context.getObjCIdType(), Record);
1812 AddTypeRef(Context.getObjCSelType(), Record);
1813 AddTypeRef(Context.getObjCProtoType(), Record);
1814 AddTypeRef(Context.getObjCClassType(), Record);
1815 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1816 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregore01ad442009-04-18 05:55:16 +00001817 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1818
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001819 // Write the record containing external, unnamed definitions.
Douglas Gregor631f6c62009-04-14 00:24:19 +00001820 if (!ExternalDefinitions.empty())
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001821 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001822
1823 // Write the record containing tentative definitions.
1824 if (!TentativeDefinitions.empty())
1825 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor062d9482009-04-22 22:18:58 +00001826
1827 // Write the record containing locally-scoped external definitions.
1828 if (!LocallyScopedExternalDecls.empty())
1829 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1830 LocallyScopedExternalDecls);
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001831
1832 // Write the record containing ext_vector type names.
1833 if (!ExtVectorDecls.empty())
1834 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
1835
1836 // Write the record containing Objective-C category implementations.
1837 if (!ObjCCategoryImpls.empty())
1838 Stream.EmitRecord(pch::OBJC_CATEGORY_IMPLEMENTATIONS, ObjCCategoryImpls);
Douglas Gregor456e0952009-04-17 22:13:46 +00001839
1840 // Some simple statistics
Douglas Gregore01ad442009-04-18 05:55:16 +00001841 Record.clear();
Douglas Gregor456e0952009-04-17 22:13:46 +00001842 Record.push_back(NumStatements);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001843 Record.push_back(NumMacros);
Douglas Gregoraf136d92009-04-22 22:34:57 +00001844 Record.push_back(NumLexicalDeclContexts);
1845 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor456e0952009-04-17 22:13:46 +00001846 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc72f6c82009-04-16 22:23:12 +00001847 Stream.ExitBlock();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001848}
1849
1850void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1851 Record.push_back(Loc.getRawEncoding());
1852}
1853
1854void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1855 Record.push_back(Value.getBitWidth());
1856 unsigned N = Value.getNumWords();
1857 const uint64_t* Words = Value.getRawData();
1858 for (unsigned I = 0; I != N; ++I)
1859 Record.push_back(Words[I]);
1860}
1861
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001862void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1863 Record.push_back(Value.isUnsigned());
1864 AddAPInt(Value, Record);
1865}
1866
Douglas Gregore2f37202009-04-14 21:55:33 +00001867void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1868 AddAPInt(Value.bitcastToAPInt(), Record);
1869}
1870
Douglas Gregorc34897d2009-04-09 22:27:44 +00001871void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001872 Record.push_back(getIdentifierRef(II));
1873}
1874
1875pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1876 if (II == 0)
1877 return 0;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001878
1879 pch::IdentID &ID = IdentifierIDs[II];
1880 if (ID == 0)
1881 ID = IdentifierIDs.size();
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001882 return ID;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001883}
1884
Steve Naroff9e84d782009-04-23 10:39:46 +00001885void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1886 if (SelRef.getAsOpaquePtr() == 0) {
1887 Record.push_back(0);
1888 return;
1889 }
1890
1891 pch::SelectorID &SID = SelectorIDs[SelRef];
1892 if (SID == 0) {
1893 SID = SelectorIDs.size();
1894 SelVector.push_back(SelRef);
1895 }
1896 Record.push_back(SID);
1897}
1898
Douglas Gregorc34897d2009-04-09 22:27:44 +00001899void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1900 if (T.isNull()) {
1901 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1902 return;
1903 }
1904
1905 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001906 pch::TypeID ID = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001907 switch (BT->getKind()) {
1908 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1909 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1910 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1911 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1912 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1913 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1914 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1915 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001916 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001917 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1918 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1919 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1920 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1921 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1922 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1923 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001924 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001925 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1926 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1927 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001928 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001929 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1930 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Anders Carlsson4a8498c2009-06-26 18:41:36 +00001931 case BuiltinType::UndeducedAuto:
1932 assert(0 && "Should not see undeduced auto here");
1933 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001934 }
1935
1936 Record.push_back((ID << 3) | T.getCVRQualifiers());
1937 return;
1938 }
1939
Douglas Gregorac8f2802009-04-10 17:25:41 +00001940 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregore43f0972009-04-26 03:49:13 +00001941 if (ID == 0) {
1942 // We haven't seen this type before. Assign it a new ID and put it
1943 // into the queu of types to emit.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001944 ID = NextTypeID++;
Douglas Gregore43f0972009-04-26 03:49:13 +00001945 TypesToEmit.push(T.getTypePtr());
1946 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001947
1948 // Encode the type qualifiers in the type reference.
1949 Record.push_back((ID << 3) | T.getCVRQualifiers());
1950}
1951
1952void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1953 if (D == 0) {
1954 Record.push_back(0);
1955 return;
1956 }
1957
Douglas Gregorac8f2802009-04-10 17:25:41 +00001958 pch::DeclID &ID = DeclIDs[D];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001959 if (ID == 0) {
1960 // We haven't seen this declaration before. Give it a new ID and
1961 // enqueue it in the list of declarations to emit.
1962 ID = DeclIDs.size();
1963 DeclsToEmit.push(const_cast<Decl *>(D));
1964 }
1965
1966 Record.push_back(ID);
1967}
1968
Douglas Gregorff9a6092009-04-20 20:36:09 +00001969pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1970 if (D == 0)
1971 return 0;
1972
1973 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1974 return DeclIDs[D];
1975}
1976
Douglas Gregorc34897d2009-04-09 22:27:44 +00001977void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnercd4da472009-04-27 07:35:58 +00001978 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregorc34897d2009-04-09 22:27:44 +00001979 Record.push_back(Name.getNameKind());
1980 switch (Name.getNameKind()) {
1981 case DeclarationName::Identifier:
1982 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1983 break;
1984
1985 case DeclarationName::ObjCZeroArgSelector:
1986 case DeclarationName::ObjCOneArgSelector:
1987 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff9e84d782009-04-23 10:39:46 +00001988 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001989 break;
1990
1991 case DeclarationName::CXXConstructorName:
1992 case DeclarationName::CXXDestructorName:
1993 case DeclarationName::CXXConversionFunctionName:
1994 AddTypeRef(Name.getCXXNameType(), Record);
1995 break;
1996
1997 case DeclarationName::CXXOperatorName:
1998 Record.push_back(Name.getCXXOverloadedOperator());
1999 break;
2000
2001 case DeclarationName::CXXUsingDirective:
2002 // No extra data to emit
2003 break;
2004 }
2005}
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002006