blob: 08a1661e1d377f4dfac9fe5c62d34136e216be5b [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
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000258void PCHTypeWriter::VisitObjCProtocolListType(const ObjCProtocolListType *T) {
259 Writer.AddTypeRef(T->getBaseType(), Record);
260 Record.push_back(T->getNumProtocols());
261 for (ObjCProtocolListType::qual_iterator I = T->qual_begin(),
262 E = T->qual_end(); I != E; ++I)
263 Writer.AddDeclRef(*I, Record);
264 Code = pch::TYPE_OBJC_PROTOCOL_LIST;
265}
266
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000267//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000268// PCHWriter Implementation
269//===----------------------------------------------------------------------===//
270
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000271static void EmitBlockID(unsigned ID, const char *Name,
272 llvm::BitstreamWriter &Stream,
273 PCHWriter::RecordData &Record) {
274 Record.clear();
275 Record.push_back(ID);
276 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
277
278 // Emit the block name if present.
279 if (Name == 0 || Name[0] == 0) return;
280 Record.clear();
281 while (*Name)
282 Record.push_back(*Name++);
283 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
284}
285
286static void EmitRecordID(unsigned ID, const char *Name,
287 llvm::BitstreamWriter &Stream,
288 PCHWriter::RecordData &Record) {
289 Record.clear();
290 Record.push_back(ID);
291 while (*Name)
292 Record.push_back(*Name++);
293 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000294}
295
296static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
297 PCHWriter::RecordData &Record) {
298#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
299 RECORD(STMT_STOP);
300 RECORD(STMT_NULL_PTR);
301 RECORD(STMT_NULL);
302 RECORD(STMT_COMPOUND);
303 RECORD(STMT_CASE);
304 RECORD(STMT_DEFAULT);
305 RECORD(STMT_LABEL);
306 RECORD(STMT_IF);
307 RECORD(STMT_SWITCH);
308 RECORD(STMT_WHILE);
309 RECORD(STMT_DO);
310 RECORD(STMT_FOR);
311 RECORD(STMT_GOTO);
312 RECORD(STMT_INDIRECT_GOTO);
313 RECORD(STMT_CONTINUE);
314 RECORD(STMT_BREAK);
315 RECORD(STMT_RETURN);
316 RECORD(STMT_DECL);
317 RECORD(STMT_ASM);
318 RECORD(EXPR_PREDEFINED);
319 RECORD(EXPR_DECL_REF);
320 RECORD(EXPR_INTEGER_LITERAL);
321 RECORD(EXPR_FLOATING_LITERAL);
322 RECORD(EXPR_IMAGINARY_LITERAL);
323 RECORD(EXPR_STRING_LITERAL);
324 RECORD(EXPR_CHARACTER_LITERAL);
325 RECORD(EXPR_PAREN);
326 RECORD(EXPR_UNARY_OPERATOR);
327 RECORD(EXPR_SIZEOF_ALIGN_OF);
328 RECORD(EXPR_ARRAY_SUBSCRIPT);
329 RECORD(EXPR_CALL);
330 RECORD(EXPR_MEMBER);
331 RECORD(EXPR_BINARY_OPERATOR);
332 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
333 RECORD(EXPR_CONDITIONAL_OPERATOR);
334 RECORD(EXPR_IMPLICIT_CAST);
335 RECORD(EXPR_CSTYLE_CAST);
336 RECORD(EXPR_COMPOUND_LITERAL);
337 RECORD(EXPR_EXT_VECTOR_ELEMENT);
338 RECORD(EXPR_INIT_LIST);
339 RECORD(EXPR_DESIGNATED_INIT);
340 RECORD(EXPR_IMPLICIT_VALUE_INIT);
341 RECORD(EXPR_VA_ARG);
342 RECORD(EXPR_ADDR_LABEL);
343 RECORD(EXPR_STMT);
344 RECORD(EXPR_TYPES_COMPATIBLE);
345 RECORD(EXPR_CHOOSE);
346 RECORD(EXPR_GNU_NULL);
347 RECORD(EXPR_SHUFFLE_VECTOR);
348 RECORD(EXPR_BLOCK);
349 RECORD(EXPR_BLOCK_DECL_REF);
350 RECORD(EXPR_OBJC_STRING_LITERAL);
351 RECORD(EXPR_OBJC_ENCODE);
352 RECORD(EXPR_OBJC_SELECTOR_EXPR);
353 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
354 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
355 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
356 RECORD(EXPR_OBJC_KVC_REF_EXPR);
357 RECORD(EXPR_OBJC_MESSAGE_EXPR);
358 RECORD(EXPR_OBJC_SUPER_EXPR);
359 RECORD(STMT_OBJC_FOR_COLLECTION);
360 RECORD(STMT_OBJC_CATCH);
361 RECORD(STMT_OBJC_FINALLY);
362 RECORD(STMT_OBJC_AT_TRY);
363 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
364 RECORD(STMT_OBJC_AT_THROW);
365#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000366}
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000368void PCHWriter::WriteBlockInfoBlock() {
369 RecordData Record;
370 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner2f4efd12009-04-27 00:40:25 +0000372#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000373#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000375 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000376 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000377 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000378 RECORD(TYPE_OFFSET);
379 RECORD(DECL_OFFSET);
380 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000381 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000382 RECORD(IDENTIFIER_OFFSET);
383 RECORD(IDENTIFIER_TABLE);
384 RECORD(EXTERNAL_DEFINITIONS);
385 RECORD(SPECIAL_TYPES);
386 RECORD(STATISTICS);
387 RECORD(TENTATIVE_DEFINITIONS);
388 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
389 RECORD(SELECTOR_OFFSETS);
390 RECORD(METHOD_POOL);
391 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000392 RECORD(SOURCE_LOCATION_OFFSETS);
393 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000394 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000395 RECORD(EXT_VECTOR_DECLS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000396 RECORD(COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000398 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000399 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000400 RECORD(SM_SLOC_FILE_ENTRY);
401 RECORD(SM_SLOC_BUFFER_ENTRY);
402 RECORD(SM_SLOC_BUFFER_BLOB);
403 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
404 RECORD(SM_LINE_TABLE);
405 RECORD(SM_HEADER_FILE_INFO);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000407 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000408 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000409 RECORD(PP_MACRO_OBJECT_LIKE);
410 RECORD(PP_MACRO_FUNCTION_LIKE);
411 RECORD(PP_TOKEN);
412
413 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000414 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000415 RECORD(TYPE_EXT_QUAL);
416 RECORD(TYPE_FIXED_WIDTH_INT);
417 RECORD(TYPE_COMPLEX);
418 RECORD(TYPE_POINTER);
419 RECORD(TYPE_BLOCK_POINTER);
420 RECORD(TYPE_LVALUE_REFERENCE);
421 RECORD(TYPE_RVALUE_REFERENCE);
422 RECORD(TYPE_MEMBER_POINTER);
423 RECORD(TYPE_CONSTANT_ARRAY);
424 RECORD(TYPE_INCOMPLETE_ARRAY);
425 RECORD(TYPE_VARIABLE_ARRAY);
426 RECORD(TYPE_VECTOR);
427 RECORD(TYPE_EXT_VECTOR);
428 RECORD(TYPE_FUNCTION_PROTO);
429 RECORD(TYPE_FUNCTION_NO_PROTO);
430 RECORD(TYPE_TYPEDEF);
431 RECORD(TYPE_TYPEOF_EXPR);
432 RECORD(TYPE_TYPEOF);
433 RECORD(TYPE_RECORD);
434 RECORD(TYPE_ENUM);
435 RECORD(TYPE_OBJC_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000436 RECORD(TYPE_OBJC_OBJECT_POINTER);
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000437 RECORD(TYPE_OBJC_PROTOCOL_LIST);
Chris Lattner0558df22009-04-27 00:49:53 +0000438 // Statements and Exprs can occur in the Types block.
439 AddStmtsExprs(Stream, Record);
440
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000441 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000442 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000443 RECORD(DECL_ATTR);
444 RECORD(DECL_TRANSLATION_UNIT);
445 RECORD(DECL_TYPEDEF);
446 RECORD(DECL_ENUM);
447 RECORD(DECL_RECORD);
448 RECORD(DECL_ENUM_CONSTANT);
449 RECORD(DECL_FUNCTION);
450 RECORD(DECL_OBJC_METHOD);
451 RECORD(DECL_OBJC_INTERFACE);
452 RECORD(DECL_OBJC_PROTOCOL);
453 RECORD(DECL_OBJC_IVAR);
454 RECORD(DECL_OBJC_AT_DEFS_FIELD);
455 RECORD(DECL_OBJC_CLASS);
456 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
457 RECORD(DECL_OBJC_CATEGORY);
458 RECORD(DECL_OBJC_CATEGORY_IMPL);
459 RECORD(DECL_OBJC_IMPLEMENTATION);
460 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
461 RECORD(DECL_OBJC_PROPERTY);
462 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000463 RECORD(DECL_FIELD);
464 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000465 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000466 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000467 RECORD(DECL_ORIGINAL_PARM_VAR);
468 RECORD(DECL_FILE_SCOPE_ASM);
469 RECORD(DECL_BLOCK);
470 RECORD(DECL_CONTEXT_LEXICAL);
471 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000472 // Statements and Exprs can occur in the Decls block.
473 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000474#undef RECORD
475#undef BLOCK
476 Stream.ExitBlock();
477}
478
Douglas Gregore650c8c2009-07-07 00:12:59 +0000479/// \brief Adjusts the given filename to only write out the portion of the
480/// filename that is not part of the system root directory.
Mike Stump1eb44332009-09-09 15:08:12 +0000481///
Douglas Gregore650c8c2009-07-07 00:12:59 +0000482/// \param Filename the file name to adjust.
483///
484/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
485/// the returned filename will be adjusted by this system root.
486///
487/// \returns either the original filename (if it needs no adjustment) or the
488/// adjusted filename (which points into the @p Filename parameter).
Mike Stump1eb44332009-09-09 15:08:12 +0000489static const char *
Douglas Gregore650c8c2009-07-07 00:12:59 +0000490adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
491 assert(Filename && "No file name to adjust?");
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregore650c8c2009-07-07 00:12:59 +0000493 if (!isysroot)
494 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregore650c8c2009-07-07 00:12:59 +0000496 // Verify that the filename and the system root have the same prefix.
497 unsigned Pos = 0;
498 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
499 if (Filename[Pos] != isysroot[Pos])
500 return Filename; // Prefixes don't match.
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Douglas Gregore650c8c2009-07-07 00:12:59 +0000502 // We hit the end of the filename before we hit the end of the system root.
503 if (!Filename[Pos])
504 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Douglas Gregore650c8c2009-07-07 00:12:59 +0000506 // If the file name has a '/' at the current position, skip over the '/'.
507 // We distinguish sysroot-based includes from absolute includes by the
508 // absence of '/' at the beginning of sysroot-based includes.
509 if (Filename[Pos] == '/')
510 ++Pos;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregore650c8c2009-07-07 00:12:59 +0000512 return Filename + Pos;
513}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000514
Douglas Gregorab41e632009-04-27 22:23:34 +0000515/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000516void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000517 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000518
Douglas Gregore650c8c2009-07-07 00:12:59 +0000519 // Metadata
520 const TargetInfo &Target = Context.Target;
521 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
522 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
523 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
524 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
525 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
526 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
527 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
528 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
529 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregore650c8c2009-07-07 00:12:59 +0000531 RecordData Record;
532 Record.push_back(pch::METADATA);
533 Record.push_back(pch::VERSION_MAJOR);
534 Record.push_back(pch::VERSION_MINOR);
535 Record.push_back(CLANG_VERSION_MAJOR);
536 Record.push_back(CLANG_VERSION_MINOR);
537 Record.push_back(isysroot != 0);
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000538 const std::string &TripleStr = Target.getTriple().getTriple();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000539 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregorb64c1932009-05-12 01:31:05 +0000541 // Original file name
542 SourceManager &SM = Context.getSourceManager();
543 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
544 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
545 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
546 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
547 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
548
549 llvm::sys::Path MainFilePath(MainFile->getName());
550 std::string MainFileName;
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Douglas Gregorb64c1932009-05-12 01:31:05 +0000552 if (!MainFilePath.isAbsolute()) {
553 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000554 P.appendComponent(MainFilePath.str());
555 MainFileName = P.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000556 } else {
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000557 MainFileName = MainFilePath.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000558 }
559
Douglas Gregore650c8c2009-07-07 00:12:59 +0000560 const char *MainFileNameStr = MainFileName.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +0000561 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000562 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000563 RecordData Record;
564 Record.push_back(pch::ORIGINAL_FILE_NAME);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000565 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000566 }
Douglas Gregor2bec0412009-04-10 21:16:55 +0000567}
568
569/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000570void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
571 RecordData Record;
572 Record.push_back(LangOpts.Trigraphs);
573 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
574 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
575 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
576 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
577 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
578 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
579 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
580 Record.push_back(LangOpts.C99); // C99 Support
581 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
582 Record.push_back(LangOpts.CPlusPlus); // C++ Support
583 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000584 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000586 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
587 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
588 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000590 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000591 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
592 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000593 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000594 Record.push_back(LangOpts.Exceptions); // Support exception handling.
595
596 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
597 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
598 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
599
Chris Lattnerea5ce472009-04-27 07:35:58 +0000600 // Whether static initializers are protected by locks.
601 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +0000602 Record.push_back(LangOpts.POSIXThreads);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000603 Record.push_back(LangOpts.Blocks); // block extension to C
604 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
605 // they are unused.
606 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
607 // (modulo the platform support).
608
609 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
610 // signed integer arithmetic overflows.
611
612 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
613 // may be ripped out at any time.
614
615 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
Mike Stump1eb44332009-09-09 15:08:12 +0000616 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000617 // defined.
618 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
619 // opposed to __DYNAMIC__).
620 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
621
622 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
623 // used (instead of C99 semantics).
624 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000625 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
626 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000627 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
628 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000629 Record.push_back(LangOpts.getGCMode());
630 Record.push_back(LangOpts.getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000631 Record.push_back(LangOpts.getStackProtectorMode());
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000632 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000633 Record.push_back(LangOpts.OpenCL);
Anders Carlsson92f58222009-08-22 22:30:33 +0000634 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000635 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000636}
637
Douglas Gregor14f79002009-04-10 03:52:48 +0000638//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000639// stat cache Serialization
640//===----------------------------------------------------------------------===//
641
642namespace {
643// Trait used for the on-disk hash table of stat cache results.
644class VISIBILITY_HIDDEN PCHStatCacheTrait {
645public:
646 typedef const char * key_type;
647 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000649 typedef std::pair<int, struct stat> data_type;
650 typedef const data_type& data_type_ref;
651
652 static unsigned ComputeHash(const char *path) {
653 return BernsteinHash(path);
654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
656 std::pair<unsigned,unsigned>
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000657 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
658 data_type_ref Data) {
659 unsigned StrLen = strlen(path);
660 clang::io::Emit16(Out, StrLen);
661 unsigned DataLen = 1; // result value
662 if (Data.first == 0)
663 DataLen += 4 + 4 + 2 + 8 + 8;
664 clang::io::Emit8(Out, DataLen);
665 return std::make_pair(StrLen + 1, DataLen);
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000668 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
669 Out.write(path, KeyLen);
670 }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000672 void EmitData(llvm::raw_ostream& Out, key_type_ref,
673 data_type_ref Data, unsigned DataLen) {
674 using namespace clang::io;
675 uint64_t Start = Out.tell(); (void)Start;
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000677 // Result of stat()
678 Emit8(Out, Data.first? 1 : 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000680 if (Data.first == 0) {
681 Emit32(Out, (uint32_t) Data.second.st_ino);
682 Emit32(Out, (uint32_t) Data.second.st_dev);
683 Emit16(Out, (uint16_t) Data.second.st_mode);
684 Emit64(Out, (uint64_t) Data.second.st_mtime);
685 Emit64(Out, (uint64_t) Data.second.st_size);
686 }
687
688 assert(Out.tell() - Start == DataLen && "Wrong data length");
689 }
690};
691} // end anonymous namespace
692
693/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000694void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
695 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000696 // Build the on-disk hash table containing information about every
697 // stat() call.
698 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
699 unsigned NumStatEntries = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000700 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000701 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000702 Stat != StatEnd; ++Stat, ++NumStatEntries) {
703 const char *Filename = Stat->first();
704 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
705 Generator.insert(Filename, Stat->second);
706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000708 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000709 llvm::SmallString<4096> StatCacheData;
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000710 uint32_t BucketOffset;
711 {
712 llvm::raw_svector_ostream Out(StatCacheData);
713 // Make sure that no bucket is at offset 0
714 clang::io::Emit32(Out, 0);
715 BucketOffset = Generator.Emit(Out);
716 }
717
718 // Create a blob abbreviation
719 using namespace llvm;
720 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
721 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
722 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
725 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
726
727 // Write the stat cache
728 RecordData Record;
729 Record.push_back(pch::STAT_CACHE);
730 Record.push_back(BucketOffset);
731 Record.push_back(NumStatEntries);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000732 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000733}
734
735//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000736// Source Manager Serialization
737//===----------------------------------------------------------------------===//
738
739/// \brief Create an abbreviation for the SLocEntry that refers to a
740/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000741static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000742 using namespace llvm;
743 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
744 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
745 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000750 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000751}
752
753/// \brief Create an abbreviation for the SLocEntry that refers to a
754/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000755static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000756 using namespace llvm;
757 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
758 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
762 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
763 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name 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 a
768/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000769static unsigned CreateSLocBufferBlobAbbrev(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_BUFFER_BLOB));
773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000774 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000775}
776
777/// \brief Create an abbreviation for the SLocEntry that refers to an
778/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000779static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000780 using namespace llvm;
781 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
782 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
783 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000787 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000788 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000789}
790
791/// \brief Writes the block containing the serialized form of the
792/// source manager.
793///
794/// TODO: We should probably use an on-disk hash table (stored in a
795/// blob), indexed based on the file name, so that we only create
796/// entries for files that we actually need. In the common case (no
797/// errors), we probably won't have to create file entries for any of
798/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000799void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000800 const Preprocessor &PP,
801 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000802 RecordData Record;
803
Chris Lattnerf04ad692009-04-10 17:16:57 +0000804 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000805 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000806
807 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000808 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
809 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
810 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
811 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000812
Douglas Gregorbd945002009-04-13 16:31:14 +0000813 // Write the line table.
814 if (SourceMgr.hasLineTable()) {
815 LineTableInfo &LineTable = SourceMgr.getLineTable();
816
817 // Emit the file names
818 Record.push_back(LineTable.getNumFilenames());
819 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
820 // Emit the file name
821 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000822 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000823 unsigned FilenameLen = Filename? strlen(Filename) : 0;
824 Record.push_back(FilenameLen);
825 if (FilenameLen)
826 Record.insert(Record.end(), Filename, Filename + FilenameLen);
827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Douglas Gregorbd945002009-04-13 16:31:14 +0000829 // Emit the line entries
830 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
831 L != LEnd; ++L) {
832 // Emit the file ID
833 Record.push_back(L->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregorbd945002009-04-13 16:31:14 +0000835 // Emit the line entries
836 Record.push_back(L->second.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000837 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
Douglas Gregorbd945002009-04-13 16:31:14 +0000838 LEEnd = L->second.end();
839 LE != LEEnd; ++LE) {
840 Record.push_back(LE->FileOffset);
841 Record.push_back(LE->LineNo);
842 Record.push_back(LE->FilenameID);
843 Record.push_back((unsigned)LE->FileKind);
844 Record.push_back(LE->IncludeOffset);
845 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000846 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000847 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000848 }
849
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000850 // Write out entries for all of the header files we know about.
Mike Stump1eb44332009-09-09 15:08:12 +0000851 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000852 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000853 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000854 E = HS.header_file_end();
855 I != E; ++I) {
856 Record.push_back(I->isImport);
857 Record.push_back(I->DirInfo);
858 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000859 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000860 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
861 Record.clear();
862 }
863
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000864 // Write out the source location entry table. We skip the first
865 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000866 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000867 RecordData PreloadSLocs;
868 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000869 for (SourceManager::sloc_entry_iterator
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000870 SLoc = SourceMgr.sloc_entry_begin() + 1,
871 SLocEnd = SourceMgr.sloc_entry_end();
872 SLoc != SLocEnd; ++SLoc) {
873 // Record the offset of this source-location entry.
874 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
875
876 // Figure out which record code to use.
877 unsigned Code;
878 if (SLoc->isFile()) {
879 if (SLoc->getFile().getContentCache()->Entry)
880 Code = pch::SM_SLOC_FILE_ENTRY;
881 else
882 Code = pch::SM_SLOC_BUFFER_ENTRY;
883 } else
884 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
885 Record.clear();
886 Record.push_back(Code);
887
888 Record.push_back(SLoc->getOffset());
889 if (SLoc->isFile()) {
890 const SrcMgr::FileInfo &File = SLoc->getFile();
891 Record.push_back(File.getIncludeLoc().getRawEncoding());
892 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
893 Record.push_back(File.hasLineDirectives());
894
895 const SrcMgr::ContentCache *Content = File.getContentCache();
896 if (Content->Entry) {
897 // The source location entry is a file. The blob associated
898 // with this entry is the file name.
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Douglas Gregore650c8c2009-07-07 00:12:59 +0000900 // Turn the file name into an absolute path, if it isn't already.
901 const char *Filename = Content->Entry->getName();
902 llvm::sys::Path FilePath(Filename, strlen(Filename));
903 std::string FilenameStr;
904 if (!FilePath.isAbsolute()) {
905 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000906 P.appendComponent(FilePath.str());
907 FilenameStr = P.str();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000908 Filename = FilenameStr.c_str();
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Douglas Gregore650c8c2009-07-07 00:12:59 +0000911 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000912 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913
914 // FIXME: For now, preload all file source locations, so that
915 // we get the appropriate File entries in the reader. This is
916 // a temporary measure.
917 PreloadSLocs.push_back(SLocEntryOffsets.size());
918 } else {
919 // The source location entry is a buffer. The blob associated
920 // with this entry contains the contents of the buffer.
921
922 // We add one to the size so that we capture the trailing NULL
923 // that is required by llvm::MemoryBuffer::getMemBuffer (on
924 // the reader side).
925 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
926 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000927 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
928 llvm::StringRef(Name, strlen(Name) + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000929 Record.clear();
930 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
931 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Daniel Dunbarec312a12009-08-24 09:31:37 +0000932 llvm::StringRef(Buffer->getBufferStart(),
933 Buffer->getBufferSize() + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000934
935 if (strcmp(Name, "<built-in>") == 0)
936 PreloadSLocs.push_back(SLocEntryOffsets.size());
937 }
938 } else {
939 // The source location entry is an instantiation.
940 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
941 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
942 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
943 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
944
945 // Compute the token length for this macro expansion.
946 unsigned NextOffset = SourceMgr.getNextOffset();
947 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
948 if (++NextSLoc != SLocEnd)
949 NextOffset = NextSLoc->getOffset();
950 Record.push_back(NextOffset - SLoc->getOffset() - 1);
951 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
952 }
953 }
954
Douglas Gregorc9490c02009-04-16 22:23:12 +0000955 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000956
957 if (SLocEntryOffsets.empty())
958 return;
959
960 // Write the source-location offsets table into the PCH block. This
961 // table is used for lazily loading source-location information.
962 using namespace llvm;
963 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
964 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
965 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
966 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
967 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
968 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000970 Record.clear();
971 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
972 Record.push_back(SLocEntryOffsets.size());
973 Record.push_back(SourceMgr.getNextOffset());
974 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +0000975 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000976 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000977
978 // Write the source location entry preloads array, telling the PCH
979 // reader which source locations entries it should load eagerly.
980 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000981}
982
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000983//===----------------------------------------------------------------------===//
984// Preprocessor Serialization
985//===----------------------------------------------------------------------===//
986
Chris Lattner0b1fb982009-04-10 17:15:23 +0000987/// \brief Writes the block containing the serialized form of the
988/// preprocessor.
989///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000990void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000991 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000992
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000993 // If the preprocessor __COUNTER__ value has been bumped, remember it.
994 if (PP.getCounterValue() != 0) {
995 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000996 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000997 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000998 }
999
1000 // Enter the preprocessor block.
1001 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001003 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1004 // FIXME: use diagnostics subsystem for localization etc.
1005 if (PP.SawDateOrTime())
1006 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001008 // Loop over all the macro definitions that are live at the end of the file,
1009 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001010 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1011 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001012 // FIXME: This emits macros in hash table order, we should do it in a stable
1013 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001014 MacroInfo *MI = I->second;
1015
1016 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1017 // been redefined by the header (in which case they are not isBuiltinMacro).
1018 if (MI->isBuiltinMacro())
1019 continue;
1020
Douglas Gregor37e26842009-04-21 23:56:24 +00001021 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001022 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001023 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001024 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1025 Record.push_back(MI->isUsed());
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001027 unsigned Code;
1028 if (MI->isObjectLike()) {
1029 Code = pch::PP_MACRO_OBJECT_LIKE;
1030 } else {
1031 Code = pch::PP_MACRO_FUNCTION_LIKE;
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001033 Record.push_back(MI->isC99Varargs());
1034 Record.push_back(MI->isGNUVarargs());
1035 Record.push_back(MI->getNumArgs());
1036 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1037 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001038 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001039 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001040 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001041 Record.clear();
1042
Chris Lattnerdf961c22009-04-10 18:08:30 +00001043 // Emit the tokens array.
1044 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1045 // Note that we know that the preprocessor does not have any annotation
1046 // tokens in it because they are created by the parser, and thus can't be
1047 // in a macro definition.
1048 const Token &Tok = MI->getReplacementToken(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattnerdf961c22009-04-10 18:08:30 +00001050 Record.push_back(Tok.getLocation().getRawEncoding());
1051 Record.push_back(Tok.getLength());
1052
Chris Lattnerdf961c22009-04-10 18:08:30 +00001053 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1054 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001055 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Chris Lattnerdf961c22009-04-10 18:08:30 +00001057 // FIXME: Should translate token kind to a stable encoding.
1058 Record.push_back(Tok.getKind());
1059 // FIXME: Should translate token flags to a stable encoding.
1060 Record.push_back(Tok.getFlags());
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregorc9490c02009-04-16 22:23:12 +00001062 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001063 Record.clear();
1064 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001065 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001066 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001067 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001068}
1069
Douglas Gregor2e222532009-07-02 17:08:52 +00001070void PCHWriter::WriteComments(ASTContext &Context) {
1071 using namespace llvm;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregor2e222532009-07-02 17:08:52 +00001073 if (Context.Comments.empty())
1074 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Douglas Gregor2e222532009-07-02 17:08:52 +00001076 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1077 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1078 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1079 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregor2e222532009-07-02 17:08:52 +00001081 RecordData Record;
1082 Record.push_back(pch::COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +00001083 Stream.EmitRecordWithBlob(CommentCode, Record,
Douglas Gregor2e222532009-07-02 17:08:52 +00001084 (const char*)&Context.Comments[0],
1085 Context.Comments.size() * sizeof(SourceRange));
1086}
1087
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001088//===----------------------------------------------------------------------===//
1089// Type Serialization
1090//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001091
Douglas Gregor2cf26342009-04-09 22:27:44 +00001092/// \brief Write the representation of a type to the PCH stream.
John McCall0953e762009-09-24 19:53:00 +00001093void PCHWriter::WriteType(QualType T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001094 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001095 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001096 ID = NextTypeID++;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregor2cf26342009-04-09 22:27:44 +00001098 // Record the offset for this type.
1099 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001100 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001101 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1102 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001103 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001104 }
1105
1106 RecordData Record;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregor2cf26342009-04-09 22:27:44 +00001108 // Emit the type's representation.
1109 PCHTypeWriter W(*this, Record);
John McCall0953e762009-09-24 19:53:00 +00001110
1111 if (T.hasNonFastQualifiers()) {
1112 Qualifiers Qs = T.getQualifiers();
1113 AddTypeRef(T.getUnqualifiedType(), Record);
1114 Record.push_back(Qs.getAsOpaqueValue());
1115 W.Code = pch::TYPE_EXT_QUAL;
1116 } else {
1117 switch (T->getTypeClass()) {
1118 // For all of the concrete, non-dependent types, call the
1119 // appropriate visitor function.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001120#define TYPE(Class, Base) \
John McCall0953e762009-09-24 19:53:00 +00001121 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001122#define ABSTRACT_TYPE(Class, Base)
1123#define DEPENDENT_TYPE(Class, Base)
1124#include "clang/AST/TypeNodes.def"
1125
John McCall0953e762009-09-24 19:53:00 +00001126 // For all of the dependent type nodes (which only occur in C++
1127 // templates), produce an error.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001128#define TYPE(Class, Base)
1129#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1130#include "clang/AST/TypeNodes.def"
John McCall0953e762009-09-24 19:53:00 +00001131 assert(false && "Cannot serialize dependent type nodes");
1132 break;
1133 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001134 }
1135
1136 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001137 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001138
1139 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001140 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001141}
1142
1143/// \brief Write a block containing all of the types.
1144void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001145 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001146 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001147
Douglas Gregor366809a2009-04-26 03:49:13 +00001148 // Emit all of the types that need to be emitted (so far).
1149 while (!TypesToEmit.empty()) {
John McCall0953e762009-09-24 19:53:00 +00001150 QualType T = TypesToEmit.front();
Douglas Gregor366809a2009-04-26 03:49:13 +00001151 TypesToEmit.pop();
Douglas Gregor366809a2009-04-26 03:49:13 +00001152 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001153 }
1154
1155 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001156 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001157}
1158
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001159//===----------------------------------------------------------------------===//
1160// Declaration Serialization
1161//===----------------------------------------------------------------------===//
1162
Douglas Gregor2cf26342009-04-09 22:27:44 +00001163/// \brief Write the block containing all of the declaration IDs
1164/// lexically declared within the given DeclContext.
1165///
1166/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1167/// bistream, or 0 if no block was written.
Mike Stump1eb44332009-09-09 15:08:12 +00001168uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregor2cf26342009-04-09 22:27:44 +00001169 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001170 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001171 return 0;
1172
Douglas Gregorc9490c02009-04-16 22:23:12 +00001173 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001174 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001175 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1176 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001177 AddDeclRef(*D, Record);
1178
Douglas Gregor25123082009-04-22 22:34:57 +00001179 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001180 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001181 return Offset;
1182}
1183
1184/// \brief Write the block containing all of the declaration IDs
1185/// visible from the given DeclContext.
1186///
1187/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1188/// bistream, or 0 if no block was written.
1189uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1190 DeclContext *DC) {
1191 if (DC->getPrimaryContext() != DC)
1192 return 0;
1193
Douglas Gregoraff22df2009-04-21 22:32:33 +00001194 // Since there is no name lookup into functions or methods, and we
1195 // perform name lookup for the translation unit via the
1196 // IdentifierInfo chains, don't bother to build a
1197 // visible-declarations table for these entities.
1198 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001199 return 0;
1200
Douglas Gregor2cf26342009-04-09 22:27:44 +00001201 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001202 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001203
1204 // Serialize the contents of the mapping used for lookup. Note that,
1205 // although we have two very different code paths, the serialized
1206 // representation is the same for both cases: a declaration name,
1207 // followed by a size, followed by references to the visible
1208 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001209 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001210 RecordData Record;
1211 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001212 if (!Map)
1213 return 0;
1214
Douglas Gregor2cf26342009-04-09 22:27:44 +00001215 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1216 D != DEnd; ++D) {
1217 AddDeclarationName(D->first, Record);
1218 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1219 Record.push_back(Result.second - Result.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001220 for (; Result.first != Result.second; ++Result.first)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001221 AddDeclRef(*Result.first, Record);
1222 }
1223
1224 if (Record.size() == 0)
1225 return 0;
1226
Douglas Gregorc9490c02009-04-16 22:23:12 +00001227 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001228 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001229 return Offset;
1230}
1231
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001232//===----------------------------------------------------------------------===//
1233// Global Method Pool and Selector Serialization
1234//===----------------------------------------------------------------------===//
1235
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001236namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001237// Trait used for the on-disk hash table used in the method pool.
1238class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1239 PCHWriter &Writer;
1240
1241public:
1242 typedef Selector key_type;
1243 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001245 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1246 typedef const data_type& data_type_ref;
1247
1248 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001250 static unsigned ComputeHash(Selector Sel) {
1251 unsigned N = Sel.getNumArgs();
1252 if (N == 0)
1253 ++N;
1254 unsigned R = 5381;
1255 for (unsigned I = 0; I != N; ++I)
1256 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1257 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1258 return R;
1259 }
Mike Stump1eb44332009-09-09 15:08:12 +00001260
1261 std::pair<unsigned,unsigned>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001262 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1263 data_type_ref Methods) {
1264 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1265 clang::io::Emit16(Out, KeyLen);
1266 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
Mike Stump1eb44332009-09-09 15:08:12 +00001267 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001268 Method = Method->Next)
1269 if (Method->Method)
1270 DataLen += 4;
Mike Stump1eb44332009-09-09 15:08:12 +00001271 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001272 Method = Method->Next)
1273 if (Method->Method)
1274 DataLen += 4;
1275 clang::io::Emit16(Out, DataLen);
1276 return std::make_pair(KeyLen, DataLen);
1277 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Douglas Gregor83941df2009-04-25 17:48:32 +00001279 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump1eb44332009-09-09 15:08:12 +00001280 uint64_t Start = Out.tell();
Douglas Gregor83941df2009-04-25 17:48:32 +00001281 assert((Start >> 32) == 0 && "Selector key offset too large");
1282 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001283 unsigned N = Sel.getNumArgs();
1284 clang::io::Emit16(Out, N);
1285 if (N == 0)
1286 N = 1;
1287 for (unsigned I = 0; I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001288 clang::io::Emit32(Out,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001289 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001292 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001293 data_type_ref Methods, unsigned DataLen) {
1294 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001295 unsigned NumInstanceMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001296 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001297 Method = Method->Next)
1298 if (Method->Method)
1299 ++NumInstanceMethods;
1300
1301 unsigned NumFactoryMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001302 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001303 Method = Method->Next)
1304 if (Method->Method)
1305 ++NumFactoryMethods;
1306
1307 clang::io::Emit16(Out, NumInstanceMethods);
1308 clang::io::Emit16(Out, NumFactoryMethods);
Mike Stump1eb44332009-09-09 15:08:12 +00001309 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001310 Method = Method->Next)
1311 if (Method->Method)
1312 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Mike Stump1eb44332009-09-09 15:08:12 +00001313 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001314 Method = Method->Next)
1315 if (Method->Method)
1316 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001317
1318 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001319 }
1320};
1321} // end anonymous namespace
1322
1323/// \brief Write the method pool into the PCH file.
1324///
1325/// The method pool contains both instance and factory methods, stored
1326/// in an on-disk hash table indexed by the selector.
1327void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1328 using namespace llvm;
1329
1330 // Create and write out the blob that contains the instance and
1331 // factor method pools.
1332 bool Empty = true;
1333 {
1334 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001336 // Create the on-disk hash table representation. Start by
1337 // iterating through the instance method pool.
1338 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001339 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001340 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001341 Instance = SemaRef.InstanceMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001342 InstanceEnd = SemaRef.InstanceMethodPool.end();
1343 Instance != InstanceEnd; ++Instance) {
1344 // Check whether there is a factory method with the same
1345 // selector.
1346 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1347 = SemaRef.FactoryMethodPool.find(Instance->first);
1348
1349 if (Factory == SemaRef.FactoryMethodPool.end())
1350 Generator.insert(Instance->first,
Mike Stump1eb44332009-09-09 15:08:12 +00001351 std::make_pair(Instance->second,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001352 ObjCMethodList()));
1353 else
1354 Generator.insert(Instance->first,
1355 std::make_pair(Instance->second, Factory->second));
1356
Douglas Gregor83941df2009-04-25 17:48:32 +00001357 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001358 Empty = false;
1359 }
1360
1361 // Now iterate through the factory method pool, to pick up any
1362 // selectors that weren't already in the instance method pool.
1363 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001364 Factory = SemaRef.FactoryMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001365 FactoryEnd = SemaRef.FactoryMethodPool.end();
1366 Factory != FactoryEnd; ++Factory) {
1367 // Check whether there is an instance method with the same
1368 // selector. If so, there is no work to do here.
1369 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1370 = SemaRef.InstanceMethodPool.find(Factory->first);
1371
Douglas Gregor83941df2009-04-25 17:48:32 +00001372 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001373 Generator.insert(Factory->first,
1374 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001375 ++NumSelectorsInMethodPool;
1376 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001377
1378 Empty = false;
1379 }
1380
Douglas Gregor83941df2009-04-25 17:48:32 +00001381 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001382 return;
1383
1384 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001385 llvm::SmallString<4096> MethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001386 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001387 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001388 {
1389 PCHMethodPoolTrait Trait(*this);
1390 llvm::raw_svector_ostream Out(MethodPool);
1391 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001392 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001393 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001394
1395 // For every selector that we have seen but which was not
1396 // written into the hash table, write the selector itself and
1397 // record it's offset.
1398 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1399 if (SelectorOffsets[I] == 0)
1400 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001401 }
1402
1403 // Create a blob abbreviation
1404 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1405 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1406 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001407 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1409 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1410
Douglas Gregor83941df2009-04-25 17:48:32 +00001411 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001412 RecordData Record;
1413 Record.push_back(pch::METHOD_POOL);
1414 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001415 Record.push_back(NumSelectorsInMethodPool);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001416 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor83941df2009-04-25 17:48:32 +00001417
1418 // Create a blob abbreviation for the selector table offsets.
1419 Abbrev = new BitCodeAbbrev();
1420 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1422 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1423 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1424
1425 // Write the selector offsets table.
1426 Record.clear();
1427 Record.push_back(pch::SELECTOR_OFFSETS);
1428 Record.push_back(SelectorOffsets.size());
1429 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1430 (const char *)&SelectorOffsets.front(),
1431 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001432 }
1433}
1434
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001435//===----------------------------------------------------------------------===//
1436// Identifier Table Serialization
1437//===----------------------------------------------------------------------===//
1438
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001439namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001440class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1441 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001442 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001443
Douglas Gregora92193e2009-04-28 21:18:29 +00001444 /// \brief Determines whether this is an "interesting" identifier
1445 /// that needs a full IdentifierInfo structure written into the hash
1446 /// table.
1447 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1448 return II->isPoisoned() ||
1449 II->isExtensionToken() ||
1450 II->hasMacroDefinition() ||
1451 II->getObjCOrBuiltinID() ||
1452 II->getFETokenInfo<void>();
1453 }
1454
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001455public:
1456 typedef const IdentifierInfo* key_type;
1457 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001459 typedef pch::IdentID data_type;
1460 typedef data_type data_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001461
1462 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
Douglas Gregor37e26842009-04-21 23:56:24 +00001463 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001464
1465 static unsigned ComputeHash(const IdentifierInfo* II) {
1466 return clang::BernsteinHash(II->getName());
1467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
1469 std::pair<unsigned,unsigned>
1470 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001471 pch::IdentID ID) {
1472 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001473 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1474 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001475 DataLen += 2; // 2 bytes for builtin ID, flags
Mike Stump1eb44332009-09-09 15:08:12 +00001476 if (II->hasMacroDefinition() &&
Douglas Gregora92193e2009-04-28 21:18:29 +00001477 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001478 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001479 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1480 DEnd = IdentifierResolver::end();
1481 D != DEnd; ++D)
1482 DataLen += sizeof(pch::DeclID);
1483 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001484 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001485 // We emit the key length after the data length so that every
1486 // string is preceded by a 16-bit length. This matches the PTH
1487 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001488 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001489 return std::make_pair(KeyLen, DataLen);
1490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
1492 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001493 unsigned KeyLen) {
1494 // Record the location of the key data. This is used when generating
1495 // the mapping from persistent IDs to strings.
1496 Writer.SetIdentifierOffset(II, Out.tell());
1497 Out.write(II->getName(), KeyLen);
1498 }
Mike Stump1eb44332009-09-09 15:08:12 +00001499
1500 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001501 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001502 if (!isInterestingIdentifier(II)) {
1503 clang::io::Emit32(Out, ID << 1);
1504 return;
1505 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001506
Douglas Gregora92193e2009-04-28 21:18:29 +00001507 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001508 uint32_t Bits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001509 bool hasMacroDefinition =
1510 II->hasMacroDefinition() &&
Douglas Gregor37e26842009-04-21 23:56:24 +00001511 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001512 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001513 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001514 Bits = (Bits << 1) | II->isExtensionToken();
1515 Bits = (Bits << 1) | II->isPoisoned();
1516 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001517 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001518
Douglas Gregor37e26842009-04-21 23:56:24 +00001519 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001520 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001521
Douglas Gregor668c1a42009-04-21 22:25:48 +00001522 // Emit the declaration IDs in reverse order, because the
1523 // IdentifierResolver provides the declarations as they would be
1524 // visible (e.g., the function "stat" would come before the struct
1525 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1526 // adds declarations to the end of the list (so we need to see the
1527 // struct "status" before the function "status").
Mike Stump1eb44332009-09-09 15:08:12 +00001528 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
Douglas Gregor668c1a42009-04-21 22:25:48 +00001529 IdentifierResolver::end());
1530 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1531 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001532 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001533 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001534 }
1535};
1536} // end anonymous namespace
1537
Douglas Gregorafaf3082009-04-11 00:14:32 +00001538/// \brief Write the identifier table into the PCH file.
1539///
1540/// The identifier table consists of a blob containing string data
1541/// (the actual identifiers themselves) and a separate "offsets" index
1542/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001543void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001544 using namespace llvm;
1545
1546 // Create and write out the blob that contains the identifier
1547 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001548 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001549 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Douglas Gregor92b059e2009-04-28 20:33:11 +00001551 // Look for any identifiers that were named while processing the
1552 // headers, but are otherwise not needed. We add these to the hash
1553 // table to enable checking of the predefines buffer in the case
1554 // where the user adds new macro definitions when building the PCH
1555 // file.
1556 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1557 IDEnd = PP.getIdentifierTable().end();
1558 ID != IDEnd; ++ID)
1559 getIdentifierRef(ID->second);
1560
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001561 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001562 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001563 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1564 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1565 ID != IDEnd; ++ID) {
1566 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001567 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001568 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001569
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001570 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001571 llvm::SmallString<4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001572 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001573 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001574 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001575 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001576 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001577 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001578 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001579 }
1580
1581 // Create a blob abbreviation
1582 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1583 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001585 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001586 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001587
1588 // Write the identifier table
1589 RecordData Record;
1590 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001591 Record.push_back(BucketOffset);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001592 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001593 }
1594
1595 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001596 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1597 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1600 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1601
1602 RecordData Record;
1603 Record.push_back(pch::IDENTIFIER_OFFSET);
1604 Record.push_back(IdentifierOffsets.size());
1605 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1606 (const char *)&IdentifierOffsets.front(),
1607 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001608}
1609
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001610//===----------------------------------------------------------------------===//
1611// General Serialization Routines
1612//===----------------------------------------------------------------------===//
1613
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001614/// \brief Write a record containing the given attributes.
1615void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1616 RecordData Record;
1617 for (; Attr; Attr = Attr->getNext()) {
1618 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1619 Record.push_back(Attr->isInherited());
1620 switch (Attr->getKind()) {
1621 case Attr::Alias:
1622 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1623 break;
1624
1625 case Attr::Aligned:
1626 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1627 break;
1628
1629 case Attr::AlwaysInline:
1630 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001632 case Attr::AnalyzerNoReturn:
1633 break;
1634
1635 case Attr::Annotate:
1636 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1637 break;
1638
1639 case Attr::AsmLabel:
1640 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1641 break;
1642
1643 case Attr::Blocks:
1644 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1645 break;
1646
1647 case Attr::Cleanup:
1648 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1649 break;
1650
1651 case Attr::Const:
1652 break;
1653
1654 case Attr::Constructor:
1655 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1656 break;
1657
1658 case Attr::DLLExport:
1659 case Attr::DLLImport:
1660 case Attr::Deprecated:
1661 break;
1662
1663 case Attr::Destructor:
1664 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1665 break;
1666
1667 case Attr::FastCall:
1668 break;
1669
1670 case Attr::Format: {
1671 const FormatAttr *Format = cast<FormatAttr>(Attr);
1672 AddString(Format->getType(), Record);
1673 Record.push_back(Format->getFormatIdx());
1674 Record.push_back(Format->getFirstArg());
1675 break;
1676 }
1677
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001678 case Attr::FormatArg: {
1679 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1680 Record.push_back(Format->getFormatIdx());
1681 break;
1682 }
1683
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001684 case Attr::Sentinel : {
1685 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1686 Record.push_back(Sentinel->getSentinel());
1687 Record.push_back(Sentinel->getNullPos());
1688 break;
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Chris Lattnercf2a7212009-04-20 19:12:28 +00001691 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001692 case Attr::IBOutletKind:
Ryan Flynn76168e22009-08-09 20:07:29 +00001693 case Attr::Malloc:
Mike Stump1feade82009-08-26 22:31:08 +00001694 case Attr::NoDebug:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001695 case Attr::NoReturn:
1696 case Attr::NoThrow:
Mike Stump1feade82009-08-26 22:31:08 +00001697 case Attr::NoInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001698 break;
1699
1700 case Attr::NonNull: {
1701 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1702 Record.push_back(NonNull->size());
1703 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1704 break;
1705 }
1706
1707 case Attr::ObjCException:
1708 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001709 case Attr::CFReturnsRetained:
1710 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001711 case Attr::Overloadable:
1712 break;
1713
Anders Carlssona860e752009-08-08 18:23:56 +00001714 case Attr::PragmaPack:
1715 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001716 break;
1717
Anders Carlssona860e752009-08-08 18:23:56 +00001718 case Attr::Packed:
1719 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001721 case Attr::Pure:
1722 break;
1723
1724 case Attr::Regparm:
1725 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1726 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Nate Begeman6f3d8382009-06-26 06:32:41 +00001728 case Attr::ReqdWorkGroupSize:
1729 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1730 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1731 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1732 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001733
1734 case Attr::Section:
1735 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1736 break;
1737
1738 case Attr::StdCall:
1739 case Attr::TransparentUnion:
1740 case Attr::Unavailable:
1741 case Attr::Unused:
1742 case Attr::Used:
1743 break;
1744
1745 case Attr::Visibility:
1746 // FIXME: stable encoding
Mike Stump1eb44332009-09-09 15:08:12 +00001747 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001748 break;
1749
1750 case Attr::WarnUnusedResult:
1751 case Attr::Weak:
1752 case Attr::WeakImport:
1753 break;
1754 }
1755 }
1756
Douglas Gregorc9490c02009-04-16 22:23:12 +00001757 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001758}
1759
1760void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1761 Record.push_back(Str.size());
1762 Record.insert(Record.end(), Str.begin(), Str.end());
1763}
1764
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001765/// \brief Note that the identifier II occurs at the given offset
1766/// within the identifier table.
1767void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001768 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001769}
1770
Douglas Gregor83941df2009-04-25 17:48:32 +00001771/// \brief Note that the selector Sel occurs at the given offset
1772/// within the method pool/selector table.
1773void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1774 unsigned ID = SelectorIDs[Sel];
1775 assert(ID && "Unknown selector");
1776 SelectorOffsets[ID - 1] = Offset;
1777}
1778
Mike Stump1eb44332009-09-09 15:08:12 +00001779PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1780 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001781 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1782 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783
Douglas Gregore650c8c2009-07-07 00:12:59 +00001784void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1785 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001786 using namespace llvm;
1787
Douglas Gregore7785042009-04-20 15:53:59 +00001788 ASTContext &Context = SemaRef.Context;
1789 Preprocessor &PP = SemaRef.PP;
1790
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001792 Stream.Emit((unsigned)'C', 8);
1793 Stream.Emit((unsigned)'P', 8);
1794 Stream.Emit((unsigned)'C', 8);
1795 Stream.Emit((unsigned)'H', 8);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001797 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001798
1799 // The translation unit is the first declaration we'll emit.
1800 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1801 DeclsToEmit.push(Context.getTranslationUnitDecl());
1802
Douglas Gregor2deaea32009-04-22 18:49:13 +00001803 // Make sure that we emit IdentifierInfos (and any attached
1804 // declarations) for builtins.
1805 {
1806 IdentifierTable &Table = PP.getIdentifierTable();
1807 llvm::SmallVector<const char *, 32> BuiltinNames;
1808 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1809 Context.getLangOptions().NoBuiltin);
1810 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1811 getIdentifierRef(&Table.get(BuiltinNames[I]));
1812 }
1813
Chris Lattner63d65f82009-09-08 18:19:27 +00001814 // Build a record containing all of the tentative definitions in this file, in
1815 // TentativeDefinitionList order. Generally, this record will be empty for
1816 // headers.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001817 RecordData TentativeDefinitions;
Chris Lattner63d65f82009-09-08 18:19:27 +00001818 for (unsigned i = 0, e = SemaRef.TentativeDefinitionList.size(); i != e; ++i){
1819 VarDecl *VD =
1820 SemaRef.TentativeDefinitions.lookup(SemaRef.TentativeDefinitionList[i]);
1821 if (VD) AddDeclRef(VD, TentativeDefinitions);
1822 }
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001823
Douglas Gregor14c22f22009-04-22 22:18:58 +00001824 // Build a record containing all of the locally-scoped external
1825 // declarations in this header file. Generally, this record will be
1826 // empty.
1827 RecordData LocallyScopedExternalDecls;
Chris Lattner63d65f82009-09-08 18:19:27 +00001828 // FIXME: This is filling in the PCH file in densemap order which is
1829 // nondeterminstic!
Mike Stump1eb44332009-09-09 15:08:12 +00001830 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Douglas Gregor14c22f22009-04-22 22:18:58 +00001831 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1832 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1833 TD != TDEnd; ++TD)
1834 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1835
Douglas Gregorb81c1702009-04-27 20:06:05 +00001836 // Build a record containing all of the ext_vector declarations.
1837 RecordData ExtVectorDecls;
1838 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1839 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1840
Douglas Gregor2cf26342009-04-09 22:27:44 +00001841 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001842 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001843 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001844 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001845 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001846 if (StatCalls && !isysroot)
1847 WriteStatCache(*StatCalls, isysroot);
1848 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001849 WritePreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +00001850 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001851 // Write the record of special types.
1852 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001854 AddTypeRef(Context.getBuiltinVaListType(), Record);
1855 AddTypeRef(Context.getObjCIdType(), Record);
1856 AddTypeRef(Context.getObjCSelType(), Record);
1857 AddTypeRef(Context.getObjCProtoType(), Record);
1858 AddTypeRef(Context.getObjCClassType(), Record);
1859 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1860 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1861 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001862 AddTypeRef(Context.getjmp_bufType(), Record);
1863 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregord1571ac2009-08-21 00:27:50 +00001864 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1865 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001866 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Douglas Gregor366809a2009-04-26 03:49:13 +00001868 // Keep writing types and declarations until all types and
1869 // declarations have been written.
1870 do {
1871 if (!DeclsToEmit.empty())
1872 WriteDeclsBlock(Context);
1873 if (!TypesToEmit.empty())
1874 WriteTypesBlock(Context);
1875 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1876
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001877 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001878 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001879
1880 // Write the type offsets array
1881 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1882 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1883 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1884 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1885 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1886 Record.clear();
1887 Record.push_back(pch::TYPE_OFFSET);
1888 Record.push_back(TypeOffsets.size());
1889 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001890 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001891 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001893 // Write the declaration offsets array
1894 Abbrev = new BitCodeAbbrev();
1895 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1898 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1899 Record.clear();
1900 Record.push_back(pch::DECL_OFFSET);
1901 Record.push_back(DeclOffsets.size());
1902 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001903 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001904 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001905
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001906 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001907 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001908 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001909
1910 // Write the record containing tentative definitions.
1911 if (!TentativeDefinitions.empty())
1912 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001913
1914 // Write the record containing locally-scoped external definitions.
1915 if (!LocallyScopedExternalDecls.empty())
Mike Stump1eb44332009-09-09 15:08:12 +00001916 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
Douglas Gregor14c22f22009-04-22 22:18:58 +00001917 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001918
1919 // Write the record containing ext_vector type names.
1920 if (!ExtVectorDecls.empty())
1921 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Douglas Gregor3e1af842009-04-17 22:13:46 +00001923 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001924 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001925 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001926 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001927 Record.push_back(NumLexicalDeclContexts);
1928 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001929 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001930 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001931}
1932
1933void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1934 Record.push_back(Loc.getRawEncoding());
1935}
1936
1937void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1938 Record.push_back(Value.getBitWidth());
1939 unsigned N = Value.getNumWords();
1940 const uint64_t* Words = Value.getRawData();
1941 for (unsigned I = 0; I != N; ++I)
1942 Record.push_back(Words[I]);
1943}
1944
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001945void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1946 Record.push_back(Value.isUnsigned());
1947 AddAPInt(Value, Record);
1948}
1949
Douglas Gregor17fc2232009-04-14 21:55:33 +00001950void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1951 AddAPInt(Value.bitcastToAPInt(), Record);
1952}
1953
Douglas Gregor2cf26342009-04-09 22:27:44 +00001954void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001955 Record.push_back(getIdentifierRef(II));
1956}
1957
1958pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1959 if (II == 0)
1960 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001961
1962 pch::IdentID &ID = IdentifierIDs[II];
1963 if (ID == 0)
1964 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001965 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001966}
1967
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001968void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1969 if (SelRef.getAsOpaquePtr() == 0) {
1970 Record.push_back(0);
1971 return;
1972 }
1973
1974 pch::SelectorID &SID = SelectorIDs[SelRef];
1975 if (SID == 0) {
1976 SID = SelectorIDs.size();
1977 SelVector.push_back(SelRef);
1978 }
1979 Record.push_back(SID);
1980}
1981
Douglas Gregor2cf26342009-04-09 22:27:44 +00001982void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1983 if (T.isNull()) {
1984 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1985 return;
1986 }
1987
John McCall0953e762009-09-24 19:53:00 +00001988 unsigned FastQuals = T.getFastQualifiers();
1989 T.removeFastQualifiers();
1990
1991 if (T.hasNonFastQualifiers()) {
1992 pch::TypeID &ID = TypeIDs[T];
1993 if (ID == 0) {
1994 // We haven't seen these qualifiers applied to this type before.
1995 // Assign it a new ID. This is the only time we enqueue a
1996 // qualified type, and it has no CV qualifiers.
1997 ID = NextTypeID++;
1998 TypesToEmit.push(T);
1999 }
2000
2001 // Encode the type qualifiers in the type reference.
2002 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2003 return;
2004 }
2005
2006 assert(!T.hasQualifiers());
2007
Douglas Gregor2cf26342009-04-09 22:27:44 +00002008 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002009 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002010 switch (BT->getKind()) {
2011 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2012 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2013 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2014 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2015 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2016 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2017 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2018 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002019 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2021 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2022 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2023 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2024 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2025 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2026 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002027 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002028 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2029 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2030 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002031 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002032 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2033 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002034 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2035 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002036 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2037 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002038 case BuiltinType::UndeducedAuto:
2039 assert(0 && "Should not see undeduced auto here");
2040 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002041 }
2042
John McCall0953e762009-09-24 19:53:00 +00002043 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002044 return;
2045 }
2046
John McCall0953e762009-09-24 19:53:00 +00002047 pch::TypeID &ID = TypeIDs[T];
Douglas Gregor366809a2009-04-26 03:49:13 +00002048 if (ID == 0) {
2049 // We haven't seen this type before. Assign it a new ID and put it
John McCall0953e762009-09-24 19:53:00 +00002050 // into the queue of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002051 ID = NextTypeID++;
John McCall0953e762009-09-24 19:53:00 +00002052 TypesToEmit.push(T);
Douglas Gregor366809a2009-04-26 03:49:13 +00002053 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002054
2055 // Encode the type qualifiers in the type reference.
John McCall0953e762009-09-24 19:53:00 +00002056 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002057}
2058
2059void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2060 if (D == 0) {
2061 Record.push_back(0);
2062 return;
2063 }
2064
Douglas Gregor8038d512009-04-10 17:25:41 +00002065 pch::DeclID &ID = DeclIDs[D];
Mike Stump1eb44332009-09-09 15:08:12 +00002066 if (ID == 0) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002067 // We haven't seen this declaration before. Give it a new ID and
2068 // enqueue it in the list of declarations to emit.
2069 ID = DeclIDs.size();
2070 DeclsToEmit.push(const_cast<Decl *>(D));
2071 }
2072
2073 Record.push_back(ID);
2074}
2075
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002076pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2077 if (D == 0)
2078 return 0;
2079
2080 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2081 return DeclIDs[D];
2082}
2083
Douglas Gregor2cf26342009-04-09 22:27:44 +00002084void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002085 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002086 Record.push_back(Name.getNameKind());
2087 switch (Name.getNameKind()) {
2088 case DeclarationName::Identifier:
2089 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2090 break;
2091
2092 case DeclarationName::ObjCZeroArgSelector:
2093 case DeclarationName::ObjCOneArgSelector:
2094 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002095 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002096 break;
2097
2098 case DeclarationName::CXXConstructorName:
2099 case DeclarationName::CXXDestructorName:
2100 case DeclarationName::CXXConversionFunctionName:
2101 AddTypeRef(Name.getCXXNameType(), Record);
2102 break;
2103
2104 case DeclarationName::CXXOperatorName:
2105 Record.push_back(Name.getCXXOverloadedOperator());
2106 break;
2107
2108 case DeclarationName::CXXUsingDirective:
2109 // No extra data to emit
2110 break;
2111 }
2112}
Douglas Gregor0b748912009-04-14 21:18:50 +00002113