blob: 8ef846f767221866dcacf735854d99aee12b9d9c [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000022#include "clang/Lex/MacroInfo.h"
23#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000030#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000031#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamWriter.h"
34#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000035#include "llvm/Support/MemoryBuffer.h"
Douglas Gregorb64c1932009-05-12 01:31:05 +000036#include "llvm/System/Path.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000037#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038using namespace clang;
39
40//===----------------------------------------------------------------------===//
41// Type serialization
42//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000043
Douglas Gregor2cf26342009-04-09 22:27:44 +000044namespace {
45 class VISIBILITY_HIDDEN PCHTypeWriter {
46 PCHWriter &Writer;
47 PCHWriter::RecordData &Record;
48
49 public:
50 /// \brief Type code that corresponds to the record generated.
51 pch::TypeCode Code;
52
Mike Stump1eb44332009-09-09 15:08:12 +000053 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor4fed3f42009-04-27 18:38:38 +000054 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000055
56 void VisitArrayType(const ArrayType *T);
57 void VisitFunctionType(const FunctionType *T);
58 void VisitTagType(const TagType *T);
59
60#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
61#define ABSTRACT_TYPE(Class, Base)
62#define DEPENDENT_TYPE(Class, Base)
63#include "clang/AST/TypeNodes.def"
64 };
65}
66
Douglas Gregor2cf26342009-04-09 22:27:44 +000067void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
68 assert(false && "Built-in types are never serialized");
69}
70
71void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
72 Record.push_back(T->getWidth());
73 Record.push_back(T->isSigned());
74 Code = pch::TYPE_FIXED_WIDTH_INT;
75}
76
77void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
78 Writer.AddTypeRef(T->getElementType(), Record);
79 Code = pch::TYPE_COMPLEX;
80}
81
82void PCHTypeWriter::VisitPointerType(const PointerType *T) {
83 Writer.AddTypeRef(T->getPointeeType(), Record);
84 Code = pch::TYPE_POINTER;
85}
86
87void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +000088 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +000089 Code = pch::TYPE_BLOCK_POINTER;
90}
91
92void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_LVALUE_REFERENCE;
95}
96
97void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Code = pch::TYPE_RVALUE_REFERENCE;
100}
101
102void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000105 Code = pch::TYPE_MEMBER_POINTER;
106}
107
108void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
109 Writer.AddTypeRef(T->getElementType(), Record);
110 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall0953e762009-09-24 19:53:00 +0000111 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregor2cf26342009-04-09 22:27:44 +0000112}
113
114void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
115 VisitArrayType(T);
116 Writer.AddAPInt(T->getSize(), Record);
117 Code = pch::TYPE_CONSTANT_ARRAY;
118}
119
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000120void PCHTypeWriter
121::VisitConstantArrayWithExprType(const ConstantArrayWithExprType *T) {
122 VisitArrayType(T);
123 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
124 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
125 Writer.AddAPInt(T->getSize(), Record);
126 Writer.AddStmt(T->getSizeExpr());
127 Code = pch::TYPE_CONSTANT_ARRAY_WITH_EXPR;
128}
129
130void PCHTypeWriter
131::VisitConstantArrayWithoutExprType(const ConstantArrayWithoutExprType *T) {
132 VisitArrayType(T);
133 Writer.AddAPInt(T->getSize(), Record);
134 Code = pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR;
135}
136
Douglas Gregor2cf26342009-04-09 22:27:44 +0000137void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
138 VisitArrayType(T);
139 Code = pch::TYPE_INCOMPLETE_ARRAY;
140}
141
142void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
143 VisitArrayType(T);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000144 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
145 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000146 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000147 Code = pch::TYPE_VARIABLE_ARRAY;
148}
149
150void PCHTypeWriter::VisitVectorType(const VectorType *T) {
151 Writer.AddTypeRef(T->getElementType(), Record);
152 Record.push_back(T->getNumElements());
153 Code = pch::TYPE_VECTOR;
154}
155
156void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
157 VisitVectorType(T);
158 Code = pch::TYPE_EXT_VECTOR;
159}
160
161void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
162 Writer.AddTypeRef(T->getResultType(), Record);
163}
164
165void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
166 VisitFunctionType(T);
167 Code = pch::TYPE_FUNCTION_NO_PROTO;
168}
169
170void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
171 VisitFunctionType(T);
172 Record.push_back(T->getNumArgs());
173 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
174 Writer.AddTypeRef(T->getArgType(I), Record);
175 Record.push_back(T->isVariadic());
176 Record.push_back(T->getTypeQuals());
Sebastian Redl465226e2009-05-27 22:11:52 +0000177 Record.push_back(T->hasExceptionSpec());
178 Record.push_back(T->hasAnyExceptionSpec());
179 Record.push_back(T->getNumExceptions());
180 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
181 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000182 Code = pch::TYPE_FUNCTION_PROTO;
183}
184
185void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
186 Writer.AddDeclRef(T->getDecl(), Record);
187 Code = pch::TYPE_TYPEDEF;
188}
189
190void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000191 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000192 Code = pch::TYPE_TYPEOF_EXPR;
193}
194
195void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
196 Writer.AddTypeRef(T->getUnderlyingType(), Record);
197 Code = pch::TYPE_TYPEOF;
198}
199
Anders Carlsson395b4752009-06-24 19:06:50 +0000200void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
201 Writer.AddStmt(T->getUnderlyingExpr());
202 Code = pch::TYPE_DECLTYPE;
203}
204
Douglas Gregor2cf26342009-04-09 22:27:44 +0000205void PCHTypeWriter::VisitTagType(const TagType *T) {
206 Writer.AddDeclRef(T->getDecl(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +0000207 assert(!T->isBeingDefined() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +0000208 "Cannot serialize in the middle of a type definition");
209}
210
211void PCHTypeWriter::VisitRecordType(const RecordType *T) {
212 VisitTagType(T);
213 Code = pch::TYPE_RECORD;
214}
215
216void PCHTypeWriter::VisitEnumType(const EnumType *T) {
217 VisitTagType(T);
218 Code = pch::TYPE_ENUM;
219}
220
John McCall7da24312009-09-05 00:15:47 +0000221void PCHTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
222 Writer.AddTypeRef(T->getUnderlyingType(), Record);
223 Record.push_back(T->getTagKind());
224 Code = pch::TYPE_ELABORATED;
225}
226
Mike Stump1eb44332009-09-09 15:08:12 +0000227void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000228PCHTypeWriter::VisitTemplateSpecializationType(
229 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000230 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000231 assert(false && "Cannot serialize template specialization types");
232}
233
234void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000235 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000236 assert(false && "Cannot serialize qualified name types");
237}
238
239void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
240 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000241 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000242 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
243 E = T->qual_end(); I != E; ++I)
244 Writer.AddDeclRef(*I, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +0000245 Code = pch::TYPE_OBJC_INTERFACE;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000246}
247
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000248void
249PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000250 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000251 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000252 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000253 E = T->qual_end(); I != E; ++I)
254 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000255 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000256}
257
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000258//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000259// PCHWriter Implementation
260//===----------------------------------------------------------------------===//
261
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000262static void EmitBlockID(unsigned ID, const char *Name,
263 llvm::BitstreamWriter &Stream,
264 PCHWriter::RecordData &Record) {
265 Record.clear();
266 Record.push_back(ID);
267 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
268
269 // Emit the block name if present.
270 if (Name == 0 || Name[0] == 0) return;
271 Record.clear();
272 while (*Name)
273 Record.push_back(*Name++);
274 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
275}
276
277static void EmitRecordID(unsigned ID, const char *Name,
278 llvm::BitstreamWriter &Stream,
279 PCHWriter::RecordData &Record) {
280 Record.clear();
281 Record.push_back(ID);
282 while (*Name)
283 Record.push_back(*Name++);
284 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000285}
286
287static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
288 PCHWriter::RecordData &Record) {
289#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
290 RECORD(STMT_STOP);
291 RECORD(STMT_NULL_PTR);
292 RECORD(STMT_NULL);
293 RECORD(STMT_COMPOUND);
294 RECORD(STMT_CASE);
295 RECORD(STMT_DEFAULT);
296 RECORD(STMT_LABEL);
297 RECORD(STMT_IF);
298 RECORD(STMT_SWITCH);
299 RECORD(STMT_WHILE);
300 RECORD(STMT_DO);
301 RECORD(STMT_FOR);
302 RECORD(STMT_GOTO);
303 RECORD(STMT_INDIRECT_GOTO);
304 RECORD(STMT_CONTINUE);
305 RECORD(STMT_BREAK);
306 RECORD(STMT_RETURN);
307 RECORD(STMT_DECL);
308 RECORD(STMT_ASM);
309 RECORD(EXPR_PREDEFINED);
310 RECORD(EXPR_DECL_REF);
311 RECORD(EXPR_INTEGER_LITERAL);
312 RECORD(EXPR_FLOATING_LITERAL);
313 RECORD(EXPR_IMAGINARY_LITERAL);
314 RECORD(EXPR_STRING_LITERAL);
315 RECORD(EXPR_CHARACTER_LITERAL);
316 RECORD(EXPR_PAREN);
317 RECORD(EXPR_UNARY_OPERATOR);
318 RECORD(EXPR_SIZEOF_ALIGN_OF);
319 RECORD(EXPR_ARRAY_SUBSCRIPT);
320 RECORD(EXPR_CALL);
321 RECORD(EXPR_MEMBER);
322 RECORD(EXPR_BINARY_OPERATOR);
323 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
324 RECORD(EXPR_CONDITIONAL_OPERATOR);
325 RECORD(EXPR_IMPLICIT_CAST);
326 RECORD(EXPR_CSTYLE_CAST);
327 RECORD(EXPR_COMPOUND_LITERAL);
328 RECORD(EXPR_EXT_VECTOR_ELEMENT);
329 RECORD(EXPR_INIT_LIST);
330 RECORD(EXPR_DESIGNATED_INIT);
331 RECORD(EXPR_IMPLICIT_VALUE_INIT);
332 RECORD(EXPR_VA_ARG);
333 RECORD(EXPR_ADDR_LABEL);
334 RECORD(EXPR_STMT);
335 RECORD(EXPR_TYPES_COMPATIBLE);
336 RECORD(EXPR_CHOOSE);
337 RECORD(EXPR_GNU_NULL);
338 RECORD(EXPR_SHUFFLE_VECTOR);
339 RECORD(EXPR_BLOCK);
340 RECORD(EXPR_BLOCK_DECL_REF);
341 RECORD(EXPR_OBJC_STRING_LITERAL);
342 RECORD(EXPR_OBJC_ENCODE);
343 RECORD(EXPR_OBJC_SELECTOR_EXPR);
344 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
345 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
346 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
347 RECORD(EXPR_OBJC_KVC_REF_EXPR);
348 RECORD(EXPR_OBJC_MESSAGE_EXPR);
349 RECORD(EXPR_OBJC_SUPER_EXPR);
350 RECORD(STMT_OBJC_FOR_COLLECTION);
351 RECORD(STMT_OBJC_CATCH);
352 RECORD(STMT_OBJC_FINALLY);
353 RECORD(STMT_OBJC_AT_TRY);
354 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
355 RECORD(STMT_OBJC_AT_THROW);
356#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000357}
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000359void PCHWriter::WriteBlockInfoBlock() {
360 RecordData Record;
361 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner2f4efd12009-04-27 00:40:25 +0000363#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000364#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000366 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000367 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000368 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000369 RECORD(TYPE_OFFSET);
370 RECORD(DECL_OFFSET);
371 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000372 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000373 RECORD(IDENTIFIER_OFFSET);
374 RECORD(IDENTIFIER_TABLE);
375 RECORD(EXTERNAL_DEFINITIONS);
376 RECORD(SPECIAL_TYPES);
377 RECORD(STATISTICS);
378 RECORD(TENTATIVE_DEFINITIONS);
379 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
380 RECORD(SELECTOR_OFFSETS);
381 RECORD(METHOD_POOL);
382 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000383 RECORD(SOURCE_LOCATION_OFFSETS);
384 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000385 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000386 RECORD(EXT_VECTOR_DECLS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000387 RECORD(COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000389 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000390 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000391 RECORD(SM_SLOC_FILE_ENTRY);
392 RECORD(SM_SLOC_BUFFER_ENTRY);
393 RECORD(SM_SLOC_BUFFER_BLOB);
394 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
395 RECORD(SM_LINE_TABLE);
396 RECORD(SM_HEADER_FILE_INFO);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000398 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000399 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000400 RECORD(PP_MACRO_OBJECT_LIKE);
401 RECORD(PP_MACRO_FUNCTION_LIKE);
402 RECORD(PP_TOKEN);
403
404 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000405 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000406 RECORD(TYPE_EXT_QUAL);
407 RECORD(TYPE_FIXED_WIDTH_INT);
408 RECORD(TYPE_COMPLEX);
409 RECORD(TYPE_POINTER);
410 RECORD(TYPE_BLOCK_POINTER);
411 RECORD(TYPE_LVALUE_REFERENCE);
412 RECORD(TYPE_RVALUE_REFERENCE);
413 RECORD(TYPE_MEMBER_POINTER);
414 RECORD(TYPE_CONSTANT_ARRAY);
415 RECORD(TYPE_INCOMPLETE_ARRAY);
416 RECORD(TYPE_VARIABLE_ARRAY);
417 RECORD(TYPE_VECTOR);
418 RECORD(TYPE_EXT_VECTOR);
419 RECORD(TYPE_FUNCTION_PROTO);
420 RECORD(TYPE_FUNCTION_NO_PROTO);
421 RECORD(TYPE_TYPEDEF);
422 RECORD(TYPE_TYPEOF_EXPR);
423 RECORD(TYPE_TYPEOF);
424 RECORD(TYPE_RECORD);
425 RECORD(TYPE_ENUM);
426 RECORD(TYPE_OBJC_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000427 RECORD(TYPE_OBJC_OBJECT_POINTER);
Chris Lattner0558df22009-04-27 00:49:53 +0000428 // Statements and Exprs can occur in the Types block.
429 AddStmtsExprs(Stream, Record);
430
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000431 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000432 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000433 RECORD(DECL_ATTR);
434 RECORD(DECL_TRANSLATION_UNIT);
435 RECORD(DECL_TYPEDEF);
436 RECORD(DECL_ENUM);
437 RECORD(DECL_RECORD);
438 RECORD(DECL_ENUM_CONSTANT);
439 RECORD(DECL_FUNCTION);
440 RECORD(DECL_OBJC_METHOD);
441 RECORD(DECL_OBJC_INTERFACE);
442 RECORD(DECL_OBJC_PROTOCOL);
443 RECORD(DECL_OBJC_IVAR);
444 RECORD(DECL_OBJC_AT_DEFS_FIELD);
445 RECORD(DECL_OBJC_CLASS);
446 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
447 RECORD(DECL_OBJC_CATEGORY);
448 RECORD(DECL_OBJC_CATEGORY_IMPL);
449 RECORD(DECL_OBJC_IMPLEMENTATION);
450 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
451 RECORD(DECL_OBJC_PROPERTY);
452 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000453 RECORD(DECL_FIELD);
454 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000455 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000456 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000457 RECORD(DECL_ORIGINAL_PARM_VAR);
458 RECORD(DECL_FILE_SCOPE_ASM);
459 RECORD(DECL_BLOCK);
460 RECORD(DECL_CONTEXT_LEXICAL);
461 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000462 // Statements and Exprs can occur in the Decls block.
463 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000464#undef RECORD
465#undef BLOCK
466 Stream.ExitBlock();
467}
468
Douglas Gregore650c8c2009-07-07 00:12:59 +0000469/// \brief Adjusts the given filename to only write out the portion of the
470/// filename that is not part of the system root directory.
Mike Stump1eb44332009-09-09 15:08:12 +0000471///
Douglas Gregore650c8c2009-07-07 00:12:59 +0000472/// \param Filename the file name to adjust.
473///
474/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
475/// the returned filename will be adjusted by this system root.
476///
477/// \returns either the original filename (if it needs no adjustment) or the
478/// adjusted filename (which points into the @p Filename parameter).
Mike Stump1eb44332009-09-09 15:08:12 +0000479static const char *
Douglas Gregore650c8c2009-07-07 00:12:59 +0000480adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
481 assert(Filename && "No file name to adjust?");
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregore650c8c2009-07-07 00:12:59 +0000483 if (!isysroot)
484 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregore650c8c2009-07-07 00:12:59 +0000486 // Verify that the filename and the system root have the same prefix.
487 unsigned Pos = 0;
488 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
489 if (Filename[Pos] != isysroot[Pos])
490 return Filename; // Prefixes don't match.
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregore650c8c2009-07-07 00:12:59 +0000492 // We hit the end of the filename before we hit the end of the system root.
493 if (!Filename[Pos])
494 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregore650c8c2009-07-07 00:12:59 +0000496 // If the file name has a '/' at the current position, skip over the '/'.
497 // We distinguish sysroot-based includes from absolute includes by the
498 // absence of '/' at the beginning of sysroot-based includes.
499 if (Filename[Pos] == '/')
500 ++Pos;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Douglas Gregore650c8c2009-07-07 00:12:59 +0000502 return Filename + Pos;
503}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000504
Douglas Gregorab41e632009-04-27 22:23:34 +0000505/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000506void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000507 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000508
Douglas Gregore650c8c2009-07-07 00:12:59 +0000509 // Metadata
510 const TargetInfo &Target = Context.Target;
511 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
512 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
513 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
514 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
515 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
516 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
517 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
518 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
519 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregore650c8c2009-07-07 00:12:59 +0000521 RecordData Record;
522 Record.push_back(pch::METADATA);
523 Record.push_back(pch::VERSION_MAJOR);
524 Record.push_back(pch::VERSION_MINOR);
525 Record.push_back(CLANG_VERSION_MAJOR);
526 Record.push_back(CLANG_VERSION_MINOR);
527 Record.push_back(isysroot != 0);
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000528 const std::string &TripleStr = Target.getTriple().getTriple();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000529 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregorb64c1932009-05-12 01:31:05 +0000531 // Original file name
532 SourceManager &SM = Context.getSourceManager();
533 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
534 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
535 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
536 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
537 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
538
539 llvm::sys::Path MainFilePath(MainFile->getName());
540 std::string MainFileName;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Douglas Gregorb64c1932009-05-12 01:31:05 +0000542 if (!MainFilePath.isAbsolute()) {
543 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000544 P.appendComponent(MainFilePath.str());
545 MainFileName = P.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000546 } else {
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000547 MainFileName = MainFilePath.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000548 }
549
Douglas Gregore650c8c2009-07-07 00:12:59 +0000550 const char *MainFileNameStr = MainFileName.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +0000551 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000552 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000553 RecordData Record;
554 Record.push_back(pch::ORIGINAL_FILE_NAME);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000555 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000556 }
Douglas Gregor2bec0412009-04-10 21:16:55 +0000557}
558
559/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000560void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
561 RecordData Record;
562 Record.push_back(LangOpts.Trigraphs);
563 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
564 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
565 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
566 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
567 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
568 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
569 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
570 Record.push_back(LangOpts.C99); // C99 Support
571 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
572 Record.push_back(LangOpts.CPlusPlus); // C++ Support
573 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000574 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000576 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
577 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
578 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000580 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000581 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
582 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000583 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000584 Record.push_back(LangOpts.Exceptions); // Support exception handling.
585
586 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
587 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
588 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
589
Chris Lattnerea5ce472009-04-27 07:35:58 +0000590 // Whether static initializers are protected by locks.
591 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +0000592 Record.push_back(LangOpts.POSIXThreads);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000593 Record.push_back(LangOpts.Blocks); // block extension to C
594 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
595 // they are unused.
596 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
597 // (modulo the platform support).
598
599 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
600 // signed integer arithmetic overflows.
601
602 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
603 // may be ripped out at any time.
604
605 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
Mike Stump1eb44332009-09-09 15:08:12 +0000606 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000607 // defined.
608 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
609 // opposed to __DYNAMIC__).
610 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
611
612 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
613 // used (instead of C99 semantics).
614 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000615 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
616 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000617 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
618 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000619 Record.push_back(LangOpts.getGCMode());
620 Record.push_back(LangOpts.getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000621 Record.push_back(LangOpts.getStackProtectorMode());
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000622 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000623 Record.push_back(LangOpts.OpenCL);
Anders Carlsson92f58222009-08-22 22:30:33 +0000624 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000625 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000626}
627
Douglas Gregor14f79002009-04-10 03:52:48 +0000628//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000629// stat cache Serialization
630//===----------------------------------------------------------------------===//
631
632namespace {
633// Trait used for the on-disk hash table of stat cache results.
634class VISIBILITY_HIDDEN PCHStatCacheTrait {
635public:
636 typedef const char * key_type;
637 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000639 typedef std::pair<int, struct stat> data_type;
640 typedef const data_type& data_type_ref;
641
642 static unsigned ComputeHash(const char *path) {
643 return BernsteinHash(path);
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
646 std::pair<unsigned,unsigned>
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000647 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
648 data_type_ref Data) {
649 unsigned StrLen = strlen(path);
650 clang::io::Emit16(Out, StrLen);
651 unsigned DataLen = 1; // result value
652 if (Data.first == 0)
653 DataLen += 4 + 4 + 2 + 8 + 8;
654 clang::io::Emit8(Out, DataLen);
655 return std::make_pair(StrLen + 1, DataLen);
656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000658 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
659 Out.write(path, KeyLen);
660 }
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000662 void EmitData(llvm::raw_ostream& Out, key_type_ref,
663 data_type_ref Data, unsigned DataLen) {
664 using namespace clang::io;
665 uint64_t Start = Out.tell(); (void)Start;
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000667 // Result of stat()
668 Emit8(Out, Data.first? 1 : 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000670 if (Data.first == 0) {
671 Emit32(Out, (uint32_t) Data.second.st_ino);
672 Emit32(Out, (uint32_t) Data.second.st_dev);
673 Emit16(Out, (uint16_t) Data.second.st_mode);
674 Emit64(Out, (uint64_t) Data.second.st_mtime);
675 Emit64(Out, (uint64_t) Data.second.st_size);
676 }
677
678 assert(Out.tell() - Start == DataLen && "Wrong data length");
679 }
680};
681} // end anonymous namespace
682
683/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000684void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
685 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000686 // Build the on-disk hash table containing information about every
687 // stat() call.
688 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
689 unsigned NumStatEntries = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000690 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000691 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000692 Stat != StatEnd; ++Stat, ++NumStatEntries) {
693 const char *Filename = Stat->first();
694 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
695 Generator.insert(Filename, Stat->second);
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000698 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000699 llvm::SmallString<4096> StatCacheData;
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000700 uint32_t BucketOffset;
701 {
702 llvm::raw_svector_ostream Out(StatCacheData);
703 // Make sure that no bucket is at offset 0
704 clang::io::Emit32(Out, 0);
705 BucketOffset = Generator.Emit(Out);
706 }
707
708 // Create a blob abbreviation
709 using namespace llvm;
710 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
711 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
712 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
713 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
715 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
716
717 // Write the stat cache
718 RecordData Record;
719 Record.push_back(pch::STAT_CACHE);
720 Record.push_back(BucketOffset);
721 Record.push_back(NumStatEntries);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000722 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000723}
724
725//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000726// Source Manager Serialization
727//===----------------------------------------------------------------------===//
728
729/// \brief Create an abbreviation for the SLocEntry that refers to a
730/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000731static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000732 using namespace llvm;
733 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
734 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
737 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000739 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000740 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000741}
742
743/// \brief Create an abbreviation for the SLocEntry that refers to a
744/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000745static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000746 using namespace llvm;
747 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
748 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
750 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
751 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
752 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
753 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000754 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000755}
756
757/// \brief Create an abbreviation for the SLocEntry that refers to a
758/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000759static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000760 using namespace llvm;
761 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
762 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000764 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000765}
766
767/// \brief Create an abbreviation for the SLocEntry that refers to an
768/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000769static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000770 using namespace llvm;
771 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
772 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
774 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
776 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000778 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000779}
780
781/// \brief Writes the block containing the serialized form of the
782/// source manager.
783///
784/// TODO: We should probably use an on-disk hash table (stored in a
785/// blob), indexed based on the file name, so that we only create
786/// entries for files that we actually need. In the common case (no
787/// errors), we probably won't have to create file entries for any of
788/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000789void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000790 const Preprocessor &PP,
791 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000792 RecordData Record;
793
Chris Lattnerf04ad692009-04-10 17:16:57 +0000794 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000795 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000796
797 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000798 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
799 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
800 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
801 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000802
Douglas Gregorbd945002009-04-13 16:31:14 +0000803 // Write the line table.
804 if (SourceMgr.hasLineTable()) {
805 LineTableInfo &LineTable = SourceMgr.getLineTable();
806
807 // Emit the file names
808 Record.push_back(LineTable.getNumFilenames());
809 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
810 // Emit the file name
811 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000812 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000813 unsigned FilenameLen = Filename? strlen(Filename) : 0;
814 Record.push_back(FilenameLen);
815 if (FilenameLen)
816 Record.insert(Record.end(), Filename, Filename + FilenameLen);
817 }
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Douglas Gregorbd945002009-04-13 16:31:14 +0000819 // Emit the line entries
820 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
821 L != LEnd; ++L) {
822 // Emit the file ID
823 Record.push_back(L->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Douglas Gregorbd945002009-04-13 16:31:14 +0000825 // Emit the line entries
826 Record.push_back(L->second.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000827 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
Douglas Gregorbd945002009-04-13 16:31:14 +0000828 LEEnd = L->second.end();
829 LE != LEEnd; ++LE) {
830 Record.push_back(LE->FileOffset);
831 Record.push_back(LE->LineNo);
832 Record.push_back(LE->FilenameID);
833 Record.push_back((unsigned)LE->FileKind);
834 Record.push_back(LE->IncludeOffset);
835 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000836 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000837 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000838 }
839
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000840 // Write out entries for all of the header files we know about.
Mike Stump1eb44332009-09-09 15:08:12 +0000841 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000842 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000843 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000844 E = HS.header_file_end();
845 I != E; ++I) {
846 Record.push_back(I->isImport);
847 Record.push_back(I->DirInfo);
848 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000849 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000850 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
851 Record.clear();
852 }
853
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000854 // Write out the source location entry table. We skip the first
855 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000856 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000857 RecordData PreloadSLocs;
858 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000859 for (SourceManager::sloc_entry_iterator
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000860 SLoc = SourceMgr.sloc_entry_begin() + 1,
861 SLocEnd = SourceMgr.sloc_entry_end();
862 SLoc != SLocEnd; ++SLoc) {
863 // Record the offset of this source-location entry.
864 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
865
866 // Figure out which record code to use.
867 unsigned Code;
868 if (SLoc->isFile()) {
869 if (SLoc->getFile().getContentCache()->Entry)
870 Code = pch::SM_SLOC_FILE_ENTRY;
871 else
872 Code = pch::SM_SLOC_BUFFER_ENTRY;
873 } else
874 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
875 Record.clear();
876 Record.push_back(Code);
877
878 Record.push_back(SLoc->getOffset());
879 if (SLoc->isFile()) {
880 const SrcMgr::FileInfo &File = SLoc->getFile();
881 Record.push_back(File.getIncludeLoc().getRawEncoding());
882 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
883 Record.push_back(File.hasLineDirectives());
884
885 const SrcMgr::ContentCache *Content = File.getContentCache();
886 if (Content->Entry) {
887 // The source location entry is a file. The blob associated
888 // with this entry is the file name.
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregore650c8c2009-07-07 00:12:59 +0000890 // Turn the file name into an absolute path, if it isn't already.
891 const char *Filename = Content->Entry->getName();
892 llvm::sys::Path FilePath(Filename, strlen(Filename));
893 std::string FilenameStr;
894 if (!FilePath.isAbsolute()) {
895 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000896 P.appendComponent(FilePath.str());
897 FilenameStr = P.str();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000898 Filename = FilenameStr.c_str();
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Douglas Gregore650c8c2009-07-07 00:12:59 +0000901 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000902 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000903
904 // FIXME: For now, preload all file source locations, so that
905 // we get the appropriate File entries in the reader. This is
906 // a temporary measure.
907 PreloadSLocs.push_back(SLocEntryOffsets.size());
908 } else {
909 // The source location entry is a buffer. The blob associated
910 // with this entry contains the contents of the buffer.
911
912 // We add one to the size so that we capture the trailing NULL
913 // that is required by llvm::MemoryBuffer::getMemBuffer (on
914 // the reader side).
915 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
916 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000917 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
918 llvm::StringRef(Name, strlen(Name) + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000919 Record.clear();
920 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
921 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Daniel Dunbarec312a12009-08-24 09:31:37 +0000922 llvm::StringRef(Buffer->getBufferStart(),
923 Buffer->getBufferSize() + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000924
925 if (strcmp(Name, "<built-in>") == 0)
926 PreloadSLocs.push_back(SLocEntryOffsets.size());
927 }
928 } else {
929 // The source location entry is an instantiation.
930 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
931 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
932 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
933 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
934
935 // Compute the token length for this macro expansion.
936 unsigned NextOffset = SourceMgr.getNextOffset();
937 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
938 if (++NextSLoc != SLocEnd)
939 NextOffset = NextSLoc->getOffset();
940 Record.push_back(NextOffset - SLoc->getOffset() - 1);
941 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
942 }
943 }
944
Douglas Gregorc9490c02009-04-16 22:23:12 +0000945 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000946
947 if (SLocEntryOffsets.empty())
948 return;
949
950 // Write the source-location offsets table into the PCH block. This
951 // table is used for lazily loading source-location information.
952 using namespace llvm;
953 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
954 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
955 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
956 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
957 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
958 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000960 Record.clear();
961 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
962 Record.push_back(SLocEntryOffsets.size());
963 Record.push_back(SourceMgr.getNextOffset());
964 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +0000965 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000966 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000967
968 // Write the source location entry preloads array, telling the PCH
969 // reader which source locations entries it should load eagerly.
970 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000971}
972
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000973//===----------------------------------------------------------------------===//
974// Preprocessor Serialization
975//===----------------------------------------------------------------------===//
976
Chris Lattner0b1fb982009-04-10 17:15:23 +0000977/// \brief Writes the block containing the serialized form of the
978/// preprocessor.
979///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000980void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000981 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000982
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000983 // If the preprocessor __COUNTER__ value has been bumped, remember it.
984 if (PP.getCounterValue() != 0) {
985 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000986 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000987 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000988 }
989
990 // Enter the preprocessor block.
991 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000993 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
994 // FIXME: use diagnostics subsystem for localization etc.
995 if (PP.SawDateOrTime())
996 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000998 // Loop over all the macro definitions that are live at the end of the file,
999 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001000 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1001 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001002 // FIXME: This emits macros in hash table order, we should do it in a stable
1003 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001004 MacroInfo *MI = I->second;
1005
1006 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1007 // been redefined by the header (in which case they are not isBuiltinMacro).
1008 if (MI->isBuiltinMacro())
1009 continue;
1010
Douglas Gregor37e26842009-04-21 23:56:24 +00001011 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001012 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001013 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001014 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1015 Record.push_back(MI->isUsed());
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001017 unsigned Code;
1018 if (MI->isObjectLike()) {
1019 Code = pch::PP_MACRO_OBJECT_LIKE;
1020 } else {
1021 Code = pch::PP_MACRO_FUNCTION_LIKE;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001023 Record.push_back(MI->isC99Varargs());
1024 Record.push_back(MI->isGNUVarargs());
1025 Record.push_back(MI->getNumArgs());
1026 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1027 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001028 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001029 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001030 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001031 Record.clear();
1032
Chris Lattnerdf961c22009-04-10 18:08:30 +00001033 // Emit the tokens array.
1034 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1035 // Note that we know that the preprocessor does not have any annotation
1036 // tokens in it because they are created by the parser, and thus can't be
1037 // in a macro definition.
1038 const Token &Tok = MI->getReplacementToken(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattnerdf961c22009-04-10 18:08:30 +00001040 Record.push_back(Tok.getLocation().getRawEncoding());
1041 Record.push_back(Tok.getLength());
1042
Chris Lattnerdf961c22009-04-10 18:08:30 +00001043 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1044 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001045 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Chris Lattnerdf961c22009-04-10 18:08:30 +00001047 // FIXME: Should translate token kind to a stable encoding.
1048 Record.push_back(Tok.getKind());
1049 // FIXME: Should translate token flags to a stable encoding.
1050 Record.push_back(Tok.getFlags());
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Douglas Gregorc9490c02009-04-16 22:23:12 +00001052 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001053 Record.clear();
1054 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001055 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001056 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001057 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001058}
1059
Douglas Gregor2e222532009-07-02 17:08:52 +00001060void PCHWriter::WriteComments(ASTContext &Context) {
1061 using namespace llvm;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Douglas Gregor2e222532009-07-02 17:08:52 +00001063 if (Context.Comments.empty())
1064 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor2e222532009-07-02 17:08:52 +00001066 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1067 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1068 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1069 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregor2e222532009-07-02 17:08:52 +00001071 RecordData Record;
1072 Record.push_back(pch::COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +00001073 Stream.EmitRecordWithBlob(CommentCode, Record,
Douglas Gregor2e222532009-07-02 17:08:52 +00001074 (const char*)&Context.Comments[0],
1075 Context.Comments.size() * sizeof(SourceRange));
1076}
1077
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001078//===----------------------------------------------------------------------===//
1079// Type Serialization
1080//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001081
Douglas Gregor2cf26342009-04-09 22:27:44 +00001082/// \brief Write the representation of a type to the PCH stream.
John McCall0953e762009-09-24 19:53:00 +00001083void PCHWriter::WriteType(QualType T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001084 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001085 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001086 ID = NextTypeID++;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Douglas Gregor2cf26342009-04-09 22:27:44 +00001088 // Record the offset for this type.
1089 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001090 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001091 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1092 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001093 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001094 }
1095
1096 RecordData Record;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregor2cf26342009-04-09 22:27:44 +00001098 // Emit the type's representation.
1099 PCHTypeWriter W(*this, Record);
John McCall0953e762009-09-24 19:53:00 +00001100
1101 if (T.hasNonFastQualifiers()) {
1102 Qualifiers Qs = T.getQualifiers();
1103 AddTypeRef(T.getUnqualifiedType(), Record);
1104 Record.push_back(Qs.getAsOpaqueValue());
1105 W.Code = pch::TYPE_EXT_QUAL;
1106 } else {
1107 switch (T->getTypeClass()) {
1108 // For all of the concrete, non-dependent types, call the
1109 // appropriate visitor function.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001110#define TYPE(Class, Base) \
John McCall0953e762009-09-24 19:53:00 +00001111 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001112#define ABSTRACT_TYPE(Class, Base)
1113#define DEPENDENT_TYPE(Class, Base)
1114#include "clang/AST/TypeNodes.def"
1115
John McCall0953e762009-09-24 19:53:00 +00001116 // For all of the dependent type nodes (which only occur in C++
1117 // templates), produce an error.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001118#define TYPE(Class, Base)
1119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1120#include "clang/AST/TypeNodes.def"
John McCall0953e762009-09-24 19:53:00 +00001121 assert(false && "Cannot serialize dependent type nodes");
1122 break;
1123 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001124 }
1125
1126 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001127 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001128
1129 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001130 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001131}
1132
1133/// \brief Write a block containing all of the types.
1134void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001135 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001136 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001137
Douglas Gregor366809a2009-04-26 03:49:13 +00001138 // Emit all of the types that need to be emitted (so far).
1139 while (!TypesToEmit.empty()) {
John McCall0953e762009-09-24 19:53:00 +00001140 QualType T = TypesToEmit.front();
Douglas Gregor366809a2009-04-26 03:49:13 +00001141 TypesToEmit.pop();
Douglas Gregor366809a2009-04-26 03:49:13 +00001142 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001143 }
1144
1145 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001146 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001147}
1148
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001149//===----------------------------------------------------------------------===//
1150// Declaration Serialization
1151//===----------------------------------------------------------------------===//
1152
Douglas Gregor2cf26342009-04-09 22:27:44 +00001153/// \brief Write the block containing all of the declaration IDs
1154/// lexically declared within the given DeclContext.
1155///
1156/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1157/// bistream, or 0 if no block was written.
Mike Stump1eb44332009-09-09 15:08:12 +00001158uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001160 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001161 return 0;
1162
Douglas Gregorc9490c02009-04-16 22:23:12 +00001163 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001164 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001165 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1166 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001167 AddDeclRef(*D, Record);
1168
Douglas Gregor25123082009-04-22 22:34:57 +00001169 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001170 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001171 return Offset;
1172}
1173
1174/// \brief Write the block containing all of the declaration IDs
1175/// visible from the given DeclContext.
1176///
1177/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1178/// bistream, or 0 if no block was written.
1179uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1180 DeclContext *DC) {
1181 if (DC->getPrimaryContext() != DC)
1182 return 0;
1183
Douglas Gregoraff22df2009-04-21 22:32:33 +00001184 // Since there is no name lookup into functions or methods, and we
1185 // perform name lookup for the translation unit via the
1186 // IdentifierInfo chains, don't bother to build a
1187 // visible-declarations table for these entities.
1188 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001189 return 0;
1190
Douglas Gregor2cf26342009-04-09 22:27:44 +00001191 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001192 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001193
1194 // Serialize the contents of the mapping used for lookup. Note that,
1195 // although we have two very different code paths, the serialized
1196 // representation is the same for both cases: a declaration name,
1197 // followed by a size, followed by references to the visible
1198 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001199 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001200 RecordData Record;
1201 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001202 if (!Map)
1203 return 0;
1204
Douglas Gregor2cf26342009-04-09 22:27:44 +00001205 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1206 D != DEnd; ++D) {
1207 AddDeclarationName(D->first, Record);
1208 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1209 Record.push_back(Result.second - Result.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001210 for (; Result.first != Result.second; ++Result.first)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001211 AddDeclRef(*Result.first, Record);
1212 }
1213
1214 if (Record.size() == 0)
1215 return 0;
1216
Douglas Gregorc9490c02009-04-16 22:23:12 +00001217 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001218 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001219 return Offset;
1220}
1221
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001222//===----------------------------------------------------------------------===//
1223// Global Method Pool and Selector Serialization
1224//===----------------------------------------------------------------------===//
1225
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001226namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001227// Trait used for the on-disk hash table used in the method pool.
1228class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1229 PCHWriter &Writer;
1230
1231public:
1232 typedef Selector key_type;
1233 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001235 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1236 typedef const data_type& data_type_ref;
1237
1238 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001240 static unsigned ComputeHash(Selector Sel) {
1241 unsigned N = Sel.getNumArgs();
1242 if (N == 0)
1243 ++N;
1244 unsigned R = 5381;
1245 for (unsigned I = 0; I != N; ++I)
1246 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1247 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1248 return R;
1249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
1251 std::pair<unsigned,unsigned>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001252 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1253 data_type_ref Methods) {
1254 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1255 clang::io::Emit16(Out, KeyLen);
1256 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
Mike Stump1eb44332009-09-09 15:08:12 +00001257 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001258 Method = Method->Next)
1259 if (Method->Method)
1260 DataLen += 4;
Mike Stump1eb44332009-09-09 15:08:12 +00001261 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001262 Method = Method->Next)
1263 if (Method->Method)
1264 DataLen += 4;
1265 clang::io::Emit16(Out, DataLen);
1266 return std::make_pair(KeyLen, DataLen);
1267 }
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregor83941df2009-04-25 17:48:32 +00001269 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump1eb44332009-09-09 15:08:12 +00001270 uint64_t Start = Out.tell();
Douglas Gregor83941df2009-04-25 17:48:32 +00001271 assert((Start >> 32) == 0 && "Selector key offset too large");
1272 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001273 unsigned N = Sel.getNumArgs();
1274 clang::io::Emit16(Out, N);
1275 if (N == 0)
1276 N = 1;
1277 for (unsigned I = 0; I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001278 clang::io::Emit32(Out,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001279 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1280 }
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001282 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001283 data_type_ref Methods, unsigned DataLen) {
1284 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001285 unsigned NumInstanceMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001286 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001287 Method = Method->Next)
1288 if (Method->Method)
1289 ++NumInstanceMethods;
1290
1291 unsigned NumFactoryMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001292 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001293 Method = Method->Next)
1294 if (Method->Method)
1295 ++NumFactoryMethods;
1296
1297 clang::io::Emit16(Out, NumInstanceMethods);
1298 clang::io::Emit16(Out, NumFactoryMethods);
Mike Stump1eb44332009-09-09 15:08:12 +00001299 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001300 Method = Method->Next)
1301 if (Method->Method)
1302 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Mike Stump1eb44332009-09-09 15:08:12 +00001303 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001304 Method = Method->Next)
1305 if (Method->Method)
1306 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001307
1308 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001309 }
1310};
1311} // end anonymous namespace
1312
1313/// \brief Write the method pool into the PCH file.
1314///
1315/// The method pool contains both instance and factory methods, stored
1316/// in an on-disk hash table indexed by the selector.
1317void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1318 using namespace llvm;
1319
1320 // Create and write out the blob that contains the instance and
1321 // factor method pools.
1322 bool Empty = true;
1323 {
1324 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001326 // Create the on-disk hash table representation. Start by
1327 // iterating through the instance method pool.
1328 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001329 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001330 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001331 Instance = SemaRef.InstanceMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001332 InstanceEnd = SemaRef.InstanceMethodPool.end();
1333 Instance != InstanceEnd; ++Instance) {
1334 // Check whether there is a factory method with the same
1335 // selector.
1336 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1337 = SemaRef.FactoryMethodPool.find(Instance->first);
1338
1339 if (Factory == SemaRef.FactoryMethodPool.end())
1340 Generator.insert(Instance->first,
Mike Stump1eb44332009-09-09 15:08:12 +00001341 std::make_pair(Instance->second,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001342 ObjCMethodList()));
1343 else
1344 Generator.insert(Instance->first,
1345 std::make_pair(Instance->second, Factory->second));
1346
Douglas Gregor83941df2009-04-25 17:48:32 +00001347 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001348 Empty = false;
1349 }
1350
1351 // Now iterate through the factory method pool, to pick up any
1352 // selectors that weren't already in the instance method pool.
1353 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001354 Factory = SemaRef.FactoryMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001355 FactoryEnd = SemaRef.FactoryMethodPool.end();
1356 Factory != FactoryEnd; ++Factory) {
1357 // Check whether there is an instance method with the same
1358 // selector. If so, there is no work to do here.
1359 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1360 = SemaRef.InstanceMethodPool.find(Factory->first);
1361
Douglas Gregor83941df2009-04-25 17:48:32 +00001362 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001363 Generator.insert(Factory->first,
1364 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001365 ++NumSelectorsInMethodPool;
1366 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001367
1368 Empty = false;
1369 }
1370
Douglas Gregor83941df2009-04-25 17:48:32 +00001371 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001372 return;
1373
1374 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001375 llvm::SmallString<4096> MethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001376 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001377 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001378 {
1379 PCHMethodPoolTrait Trait(*this);
1380 llvm::raw_svector_ostream Out(MethodPool);
1381 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001382 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001383 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001384
1385 // For every selector that we have seen but which was not
1386 // written into the hash table, write the selector itself and
1387 // record it's offset.
1388 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1389 if (SelectorOffsets[I] == 0)
1390 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001391 }
1392
1393 // Create a blob abbreviation
1394 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1395 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1396 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001397 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001398 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1399 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1400
Douglas Gregor83941df2009-04-25 17:48:32 +00001401 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001402 RecordData Record;
1403 Record.push_back(pch::METHOD_POOL);
1404 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001405 Record.push_back(NumSelectorsInMethodPool);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001406 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor83941df2009-04-25 17:48:32 +00001407
1408 // Create a blob abbreviation for the selector table offsets.
1409 Abbrev = new BitCodeAbbrev();
1410 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1411 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1413 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1414
1415 // Write the selector offsets table.
1416 Record.clear();
1417 Record.push_back(pch::SELECTOR_OFFSETS);
1418 Record.push_back(SelectorOffsets.size());
1419 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1420 (const char *)&SelectorOffsets.front(),
1421 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001422 }
1423}
1424
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001425//===----------------------------------------------------------------------===//
1426// Identifier Table Serialization
1427//===----------------------------------------------------------------------===//
1428
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001429namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001430class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1431 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001432 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001433
Douglas Gregora92193e2009-04-28 21:18:29 +00001434 /// \brief Determines whether this is an "interesting" identifier
1435 /// that needs a full IdentifierInfo structure written into the hash
1436 /// table.
1437 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1438 return II->isPoisoned() ||
1439 II->isExtensionToken() ||
1440 II->hasMacroDefinition() ||
1441 II->getObjCOrBuiltinID() ||
1442 II->getFETokenInfo<void>();
1443 }
1444
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001445public:
1446 typedef const IdentifierInfo* key_type;
1447 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001449 typedef pch::IdentID data_type;
1450 typedef data_type data_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
1452 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
Douglas Gregor37e26842009-04-21 23:56:24 +00001453 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001454
1455 static unsigned ComputeHash(const IdentifierInfo* II) {
1456 return clang::BernsteinHash(II->getName());
1457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
1459 std::pair<unsigned,unsigned>
1460 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001461 pch::IdentID ID) {
1462 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001463 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1464 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001465 DataLen += 2; // 2 bytes for builtin ID, flags
Mike Stump1eb44332009-09-09 15:08:12 +00001466 if (II->hasMacroDefinition() &&
Douglas Gregora92193e2009-04-28 21:18:29 +00001467 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001468 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001469 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1470 DEnd = IdentifierResolver::end();
1471 D != DEnd; ++D)
1472 DataLen += sizeof(pch::DeclID);
1473 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001474 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001475 // We emit the key length after the data length so that every
1476 // string is preceded by a 16-bit length. This matches the PTH
1477 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001478 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001479 return std::make_pair(KeyLen, DataLen);
1480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
1482 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001483 unsigned KeyLen) {
1484 // Record the location of the key data. This is used when generating
1485 // the mapping from persistent IDs to strings.
1486 Writer.SetIdentifierOffset(II, Out.tell());
1487 Out.write(II->getName(), KeyLen);
1488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
1490 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001491 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001492 if (!isInterestingIdentifier(II)) {
1493 clang::io::Emit32(Out, ID << 1);
1494 return;
1495 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001496
Douglas Gregora92193e2009-04-28 21:18:29 +00001497 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001498 uint32_t Bits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001499 bool hasMacroDefinition =
1500 II->hasMacroDefinition() &&
Douglas Gregor37e26842009-04-21 23:56:24 +00001501 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001502 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001503 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001504 Bits = (Bits << 1) | II->isExtensionToken();
1505 Bits = (Bits << 1) | II->isPoisoned();
1506 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001507 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001508
Douglas Gregor37e26842009-04-21 23:56:24 +00001509 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001510 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001511
Douglas Gregor668c1a42009-04-21 22:25:48 +00001512 // Emit the declaration IDs in reverse order, because the
1513 // IdentifierResolver provides the declarations as they would be
1514 // visible (e.g., the function "stat" would come before the struct
1515 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1516 // adds declarations to the end of the list (so we need to see the
1517 // struct "status" before the function "status").
Mike Stump1eb44332009-09-09 15:08:12 +00001518 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
Douglas Gregor668c1a42009-04-21 22:25:48 +00001519 IdentifierResolver::end());
1520 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1521 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001522 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001523 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001524 }
1525};
1526} // end anonymous namespace
1527
Douglas Gregorafaf3082009-04-11 00:14:32 +00001528/// \brief Write the identifier table into the PCH file.
1529///
1530/// The identifier table consists of a blob containing string data
1531/// (the actual identifiers themselves) and a separate "offsets" index
1532/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001533void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001534 using namespace llvm;
1535
1536 // Create and write out the blob that contains the identifier
1537 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001538 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001539 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Douglas Gregor92b059e2009-04-28 20:33:11 +00001541 // Look for any identifiers that were named while processing the
1542 // headers, but are otherwise not needed. We add these to the hash
1543 // table to enable checking of the predefines buffer in the case
1544 // where the user adds new macro definitions when building the PCH
1545 // file.
1546 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1547 IDEnd = PP.getIdentifierTable().end();
1548 ID != IDEnd; ++ID)
1549 getIdentifierRef(ID->second);
1550
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001551 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001552 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001553 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1554 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1555 ID != IDEnd; ++ID) {
1556 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001557 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001558 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001559
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001560 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001561 llvm::SmallString<4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001562 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001563 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001564 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001565 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001566 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001567 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001568 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001569 }
1570
1571 // Create a blob abbreviation
1572 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1573 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001576 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001577
1578 // Write the identifier table
1579 RecordData Record;
1580 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001581 Record.push_back(BucketOffset);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001582 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001583 }
1584
1585 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001586 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1587 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1588 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1589 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1590 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1591
1592 RecordData Record;
1593 Record.push_back(pch::IDENTIFIER_OFFSET);
1594 Record.push_back(IdentifierOffsets.size());
1595 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1596 (const char *)&IdentifierOffsets.front(),
1597 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001598}
1599
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001600//===----------------------------------------------------------------------===//
1601// General Serialization Routines
1602//===----------------------------------------------------------------------===//
1603
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001604/// \brief Write a record containing the given attributes.
1605void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1606 RecordData Record;
1607 for (; Attr; Attr = Attr->getNext()) {
1608 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1609 Record.push_back(Attr->isInherited());
1610 switch (Attr->getKind()) {
1611 case Attr::Alias:
1612 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1613 break;
1614
1615 case Attr::Aligned:
1616 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1617 break;
1618
1619 case Attr::AlwaysInline:
1620 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001622 case Attr::AnalyzerNoReturn:
1623 break;
1624
1625 case Attr::Annotate:
1626 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1627 break;
1628
1629 case Attr::AsmLabel:
1630 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1631 break;
1632
1633 case Attr::Blocks:
1634 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1635 break;
1636
1637 case Attr::Cleanup:
1638 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1639 break;
1640
1641 case Attr::Const:
1642 break;
1643
1644 case Attr::Constructor:
1645 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1646 break;
1647
1648 case Attr::DLLExport:
1649 case Attr::DLLImport:
1650 case Attr::Deprecated:
1651 break;
1652
1653 case Attr::Destructor:
1654 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1655 break;
1656
1657 case Attr::FastCall:
1658 break;
1659
1660 case Attr::Format: {
1661 const FormatAttr *Format = cast<FormatAttr>(Attr);
1662 AddString(Format->getType(), Record);
1663 Record.push_back(Format->getFormatIdx());
1664 Record.push_back(Format->getFirstArg());
1665 break;
1666 }
1667
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001668 case Attr::FormatArg: {
1669 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1670 Record.push_back(Format->getFormatIdx());
1671 break;
1672 }
1673
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001674 case Attr::Sentinel : {
1675 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1676 Record.push_back(Sentinel->getSentinel());
1677 Record.push_back(Sentinel->getNullPos());
1678 break;
1679 }
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Chris Lattnercf2a7212009-04-20 19:12:28 +00001681 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001682 case Attr::IBOutletKind:
Ryan Flynn76168e22009-08-09 20:07:29 +00001683 case Attr::Malloc:
Mike Stump1feade82009-08-26 22:31:08 +00001684 case Attr::NoDebug:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001685 case Attr::NoReturn:
1686 case Attr::NoThrow:
Mike Stump1feade82009-08-26 22:31:08 +00001687 case Attr::NoInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001688 break;
1689
1690 case Attr::NonNull: {
1691 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1692 Record.push_back(NonNull->size());
1693 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1694 break;
1695 }
1696
1697 case Attr::ObjCException:
1698 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001699 case Attr::CFReturnsRetained:
1700 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001701 case Attr::Overloadable:
1702 break;
1703
Anders Carlssona860e752009-08-08 18:23:56 +00001704 case Attr::PragmaPack:
1705 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001706 break;
1707
Anders Carlssona860e752009-08-08 18:23:56 +00001708 case Attr::Packed:
1709 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001711 case Attr::Pure:
1712 break;
1713
1714 case Attr::Regparm:
1715 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1716 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Nate Begeman6f3d8382009-06-26 06:32:41 +00001718 case Attr::ReqdWorkGroupSize:
1719 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1720 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1721 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1722 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001723
1724 case Attr::Section:
1725 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1726 break;
1727
1728 case Attr::StdCall:
1729 case Attr::TransparentUnion:
1730 case Attr::Unavailable:
1731 case Attr::Unused:
1732 case Attr::Used:
1733 break;
1734
1735 case Attr::Visibility:
1736 // FIXME: stable encoding
Mike Stump1eb44332009-09-09 15:08:12 +00001737 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001738 break;
1739
1740 case Attr::WarnUnusedResult:
1741 case Attr::Weak:
1742 case Attr::WeakImport:
1743 break;
1744 }
1745 }
1746
Douglas Gregorc9490c02009-04-16 22:23:12 +00001747 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001748}
1749
1750void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1751 Record.push_back(Str.size());
1752 Record.insert(Record.end(), Str.begin(), Str.end());
1753}
1754
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001755/// \brief Note that the identifier II occurs at the given offset
1756/// within the identifier table.
1757void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001758 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001759}
1760
Douglas Gregor83941df2009-04-25 17:48:32 +00001761/// \brief Note that the selector Sel occurs at the given offset
1762/// within the method pool/selector table.
1763void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1764 unsigned ID = SelectorIDs[Sel];
1765 assert(ID && "Unknown selector");
1766 SelectorOffsets[ID - 1] = Offset;
1767}
1768
Mike Stump1eb44332009-09-09 15:08:12 +00001769PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1770 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001771 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1772 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773
Douglas Gregore650c8c2009-07-07 00:12:59 +00001774void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1775 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001776 using namespace llvm;
1777
Douglas Gregore7785042009-04-20 15:53:59 +00001778 ASTContext &Context = SemaRef.Context;
1779 Preprocessor &PP = SemaRef.PP;
1780
Douglas Gregor2cf26342009-04-09 22:27:44 +00001781 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001782 Stream.Emit((unsigned)'C', 8);
1783 Stream.Emit((unsigned)'P', 8);
1784 Stream.Emit((unsigned)'C', 8);
1785 Stream.Emit((unsigned)'H', 8);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001787 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001788
1789 // The translation unit is the first declaration we'll emit.
1790 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1791 DeclsToEmit.push(Context.getTranslationUnitDecl());
1792
Douglas Gregor2deaea32009-04-22 18:49:13 +00001793 // Make sure that we emit IdentifierInfos (and any attached
1794 // declarations) for builtins.
1795 {
1796 IdentifierTable &Table = PP.getIdentifierTable();
1797 llvm::SmallVector<const char *, 32> BuiltinNames;
1798 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1799 Context.getLangOptions().NoBuiltin);
1800 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1801 getIdentifierRef(&Table.get(BuiltinNames[I]));
1802 }
1803
Chris Lattner63d65f82009-09-08 18:19:27 +00001804 // Build a record containing all of the tentative definitions in this file, in
1805 // TentativeDefinitionList order. Generally, this record will be empty for
1806 // headers.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001807 RecordData TentativeDefinitions;
Chris Lattner63d65f82009-09-08 18:19:27 +00001808 for (unsigned i = 0, e = SemaRef.TentativeDefinitionList.size(); i != e; ++i){
1809 VarDecl *VD =
1810 SemaRef.TentativeDefinitions.lookup(SemaRef.TentativeDefinitionList[i]);
1811 if (VD) AddDeclRef(VD, TentativeDefinitions);
1812 }
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001813
Douglas Gregor14c22f22009-04-22 22:18:58 +00001814 // Build a record containing all of the locally-scoped external
1815 // declarations in this header file. Generally, this record will be
1816 // empty.
1817 RecordData LocallyScopedExternalDecls;
Chris Lattner63d65f82009-09-08 18:19:27 +00001818 // FIXME: This is filling in the PCH file in densemap order which is
1819 // nondeterminstic!
Mike Stump1eb44332009-09-09 15:08:12 +00001820 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Douglas Gregor14c22f22009-04-22 22:18:58 +00001821 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1822 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1823 TD != TDEnd; ++TD)
1824 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1825
Douglas Gregorb81c1702009-04-27 20:06:05 +00001826 // Build a record containing all of the ext_vector declarations.
1827 RecordData ExtVectorDecls;
1828 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1829 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1830
Douglas Gregor2cf26342009-04-09 22:27:44 +00001831 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001832 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001833 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001834 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001835 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001836 if (StatCalls && !isysroot)
1837 WriteStatCache(*StatCalls, isysroot);
1838 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001839 WritePreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +00001840 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001841 // Write the record of special types.
1842 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001844 AddTypeRef(Context.getBuiltinVaListType(), Record);
1845 AddTypeRef(Context.getObjCIdType(), Record);
1846 AddTypeRef(Context.getObjCSelType(), Record);
1847 AddTypeRef(Context.getObjCProtoType(), Record);
1848 AddTypeRef(Context.getObjCClassType(), Record);
1849 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1850 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1851 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001852 AddTypeRef(Context.getjmp_bufType(), Record);
1853 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregord1571ac2009-08-21 00:27:50 +00001854 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1855 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001856 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregor366809a2009-04-26 03:49:13 +00001858 // Keep writing types and declarations until all types and
1859 // declarations have been written.
1860 do {
1861 if (!DeclsToEmit.empty())
1862 WriteDeclsBlock(Context);
1863 if (!TypesToEmit.empty())
1864 WriteTypesBlock(Context);
1865 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1866
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001867 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001868 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001869
1870 // Write the type offsets array
1871 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1872 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1875 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1876 Record.clear();
1877 Record.push_back(pch::TYPE_OFFSET);
1878 Record.push_back(TypeOffsets.size());
1879 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001880 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001881 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001883 // Write the declaration offsets array
1884 Abbrev = new BitCodeAbbrev();
1885 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1888 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1889 Record.clear();
1890 Record.push_back(pch::DECL_OFFSET);
1891 Record.push_back(DeclOffsets.size());
1892 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001893 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001894 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001895
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001896 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001897 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001898 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001899
1900 // Write the record containing tentative definitions.
1901 if (!TentativeDefinitions.empty())
1902 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001903
1904 // Write the record containing locally-scoped external definitions.
1905 if (!LocallyScopedExternalDecls.empty())
Mike Stump1eb44332009-09-09 15:08:12 +00001906 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
Douglas Gregor14c22f22009-04-22 22:18:58 +00001907 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001908
1909 // Write the record containing ext_vector type names.
1910 if (!ExtVectorDecls.empty())
1911 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregor3e1af842009-04-17 22:13:46 +00001913 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001914 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001915 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001916 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001917 Record.push_back(NumLexicalDeclContexts);
1918 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001919 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001920 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001921}
1922
1923void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1924 Record.push_back(Loc.getRawEncoding());
1925}
1926
1927void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1928 Record.push_back(Value.getBitWidth());
1929 unsigned N = Value.getNumWords();
1930 const uint64_t* Words = Value.getRawData();
1931 for (unsigned I = 0; I != N; ++I)
1932 Record.push_back(Words[I]);
1933}
1934
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001935void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1936 Record.push_back(Value.isUnsigned());
1937 AddAPInt(Value, Record);
1938}
1939
Douglas Gregor17fc2232009-04-14 21:55:33 +00001940void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1941 AddAPInt(Value.bitcastToAPInt(), Record);
1942}
1943
Douglas Gregor2cf26342009-04-09 22:27:44 +00001944void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001945 Record.push_back(getIdentifierRef(II));
1946}
1947
1948pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1949 if (II == 0)
1950 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001951
1952 pch::IdentID &ID = IdentifierIDs[II];
1953 if (ID == 0)
1954 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001955 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001956}
1957
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001958void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1959 if (SelRef.getAsOpaquePtr() == 0) {
1960 Record.push_back(0);
1961 return;
1962 }
1963
1964 pch::SelectorID &SID = SelectorIDs[SelRef];
1965 if (SID == 0) {
1966 SID = SelectorIDs.size();
1967 SelVector.push_back(SelRef);
1968 }
1969 Record.push_back(SID);
1970}
1971
Douglas Gregor2cf26342009-04-09 22:27:44 +00001972void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1973 if (T.isNull()) {
1974 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1975 return;
1976 }
1977
John McCall0953e762009-09-24 19:53:00 +00001978 unsigned FastQuals = T.getFastQualifiers();
1979 T.removeFastQualifiers();
1980
1981 if (T.hasNonFastQualifiers()) {
1982 pch::TypeID &ID = TypeIDs[T];
1983 if (ID == 0) {
1984 // We haven't seen these qualifiers applied to this type before.
1985 // Assign it a new ID. This is the only time we enqueue a
1986 // qualified type, and it has no CV qualifiers.
1987 ID = NextTypeID++;
1988 TypesToEmit.push(T);
1989 }
1990
1991 // Encode the type qualifiers in the type reference.
1992 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
1993 return;
1994 }
1995
1996 assert(!T.hasQualifiers());
1997
Douglas Gregor2cf26342009-04-09 22:27:44 +00001998 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001999 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 switch (BT->getKind()) {
2001 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2002 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2003 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2004 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2005 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2006 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2007 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2008 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002009 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002010 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2011 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2012 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2013 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2014 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2015 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2016 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002017 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002018 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2019 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2020 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002021 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002022 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2023 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002024 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2025 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002026 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2027 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002028 case BuiltinType::UndeducedAuto:
2029 assert(0 && "Should not see undeduced auto here");
2030 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002031 }
2032
John McCall0953e762009-09-24 19:53:00 +00002033 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002034 return;
2035 }
2036
John McCall0953e762009-09-24 19:53:00 +00002037 pch::TypeID &ID = TypeIDs[T];
Douglas Gregor366809a2009-04-26 03:49:13 +00002038 if (ID == 0) {
2039 // We haven't seen this type before. Assign it a new ID and put it
John McCall0953e762009-09-24 19:53:00 +00002040 // into the queue of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002041 ID = NextTypeID++;
John McCall0953e762009-09-24 19:53:00 +00002042 TypesToEmit.push(T);
Douglas Gregor366809a2009-04-26 03:49:13 +00002043 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002044
2045 // Encode the type qualifiers in the type reference.
John McCall0953e762009-09-24 19:53:00 +00002046 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002047}
2048
2049void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2050 if (D == 0) {
2051 Record.push_back(0);
2052 return;
2053 }
2054
Douglas Gregor8038d512009-04-10 17:25:41 +00002055 pch::DeclID &ID = DeclIDs[D];
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if (ID == 0) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002057 // We haven't seen this declaration before. Give it a new ID and
2058 // enqueue it in the list of declarations to emit.
2059 ID = DeclIDs.size();
2060 DeclsToEmit.push(const_cast<Decl *>(D));
2061 }
2062
2063 Record.push_back(ID);
2064}
2065
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002066pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2067 if (D == 0)
2068 return 0;
2069
2070 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2071 return DeclIDs[D];
2072}
2073
Douglas Gregor2cf26342009-04-09 22:27:44 +00002074void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002075 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002076 Record.push_back(Name.getNameKind());
2077 switch (Name.getNameKind()) {
2078 case DeclarationName::Identifier:
2079 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2080 break;
2081
2082 case DeclarationName::ObjCZeroArgSelector:
2083 case DeclarationName::ObjCOneArgSelector:
2084 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002085 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002086 break;
2087
2088 case DeclarationName::CXXConstructorName:
2089 case DeclarationName::CXXDestructorName:
2090 case DeclarationName::CXXConversionFunctionName:
2091 AddTypeRef(Name.getCXXNameType(), Record);
2092 break;
2093
2094 case DeclarationName::CXXOperatorName:
2095 Record.push_back(Name.getCXXOverloadedOperator());
2096 break;
2097
2098 case DeclarationName::CXXUsingDirective:
2099 // No extra data to emit
2100 break;
2101 }
2102}
Douglas Gregor0b748912009-04-14 21:18:50 +00002103