blob: 64a678ea450bf05037a6ae3379fe781eeb6578ba [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);
Douglas Gregor445e23e2009-10-05 21:07:28 +0000397 RECORD(SVN_BRANCH_REVISION);
398
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000399 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000400 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000401 RECORD(SM_SLOC_FILE_ENTRY);
402 RECORD(SM_SLOC_BUFFER_ENTRY);
403 RECORD(SM_SLOC_BUFFER_BLOB);
404 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
405 RECORD(SM_LINE_TABLE);
406 RECORD(SM_HEADER_FILE_INFO);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000408 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000409 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000410 RECORD(PP_MACRO_OBJECT_LIKE);
411 RECORD(PP_MACRO_FUNCTION_LIKE);
412 RECORD(PP_TOKEN);
413
414 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000415 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000416 RECORD(TYPE_EXT_QUAL);
417 RECORD(TYPE_FIXED_WIDTH_INT);
418 RECORD(TYPE_COMPLEX);
419 RECORD(TYPE_POINTER);
420 RECORD(TYPE_BLOCK_POINTER);
421 RECORD(TYPE_LVALUE_REFERENCE);
422 RECORD(TYPE_RVALUE_REFERENCE);
423 RECORD(TYPE_MEMBER_POINTER);
424 RECORD(TYPE_CONSTANT_ARRAY);
425 RECORD(TYPE_INCOMPLETE_ARRAY);
426 RECORD(TYPE_VARIABLE_ARRAY);
427 RECORD(TYPE_VECTOR);
428 RECORD(TYPE_EXT_VECTOR);
429 RECORD(TYPE_FUNCTION_PROTO);
430 RECORD(TYPE_FUNCTION_NO_PROTO);
431 RECORD(TYPE_TYPEDEF);
432 RECORD(TYPE_TYPEOF_EXPR);
433 RECORD(TYPE_TYPEOF);
434 RECORD(TYPE_RECORD);
435 RECORD(TYPE_ENUM);
436 RECORD(TYPE_OBJC_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000437 RECORD(TYPE_OBJC_OBJECT_POINTER);
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000438 RECORD(TYPE_OBJC_PROTOCOL_LIST);
Chris Lattner0558df22009-04-27 00:49:53 +0000439 // Statements and Exprs can occur in the Types block.
440 AddStmtsExprs(Stream, Record);
441
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000442 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000443 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000444 RECORD(DECL_ATTR);
445 RECORD(DECL_TRANSLATION_UNIT);
446 RECORD(DECL_TYPEDEF);
447 RECORD(DECL_ENUM);
448 RECORD(DECL_RECORD);
449 RECORD(DECL_ENUM_CONSTANT);
450 RECORD(DECL_FUNCTION);
451 RECORD(DECL_OBJC_METHOD);
452 RECORD(DECL_OBJC_INTERFACE);
453 RECORD(DECL_OBJC_PROTOCOL);
454 RECORD(DECL_OBJC_IVAR);
455 RECORD(DECL_OBJC_AT_DEFS_FIELD);
456 RECORD(DECL_OBJC_CLASS);
457 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
458 RECORD(DECL_OBJC_CATEGORY);
459 RECORD(DECL_OBJC_CATEGORY_IMPL);
460 RECORD(DECL_OBJC_IMPLEMENTATION);
461 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
462 RECORD(DECL_OBJC_PROPERTY);
463 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000464 RECORD(DECL_FIELD);
465 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000466 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000467 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000468 RECORD(DECL_ORIGINAL_PARM_VAR);
469 RECORD(DECL_FILE_SCOPE_ASM);
470 RECORD(DECL_BLOCK);
471 RECORD(DECL_CONTEXT_LEXICAL);
472 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000473 // Statements and Exprs can occur in the Decls block.
474 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000475#undef RECORD
476#undef BLOCK
477 Stream.ExitBlock();
478}
479
Douglas Gregore650c8c2009-07-07 00:12:59 +0000480/// \brief Adjusts the given filename to only write out the portion of the
481/// filename that is not part of the system root directory.
Mike Stump1eb44332009-09-09 15:08:12 +0000482///
Douglas Gregore650c8c2009-07-07 00:12:59 +0000483/// \param Filename the file name to adjust.
484///
485/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
486/// the returned filename will be adjusted by this system root.
487///
488/// \returns either the original filename (if it needs no adjustment) or the
489/// adjusted filename (which points into the @p Filename parameter).
Mike Stump1eb44332009-09-09 15:08:12 +0000490static const char *
Douglas Gregore650c8c2009-07-07 00:12:59 +0000491adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
492 assert(Filename && "No file name to adjust?");
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregore650c8c2009-07-07 00:12:59 +0000494 if (!isysroot)
495 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Douglas Gregore650c8c2009-07-07 00:12:59 +0000497 // Verify that the filename and the system root have the same prefix.
498 unsigned Pos = 0;
499 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
500 if (Filename[Pos] != isysroot[Pos])
501 return Filename; // Prefixes don't match.
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregore650c8c2009-07-07 00:12:59 +0000503 // We hit the end of the filename before we hit the end of the system root.
504 if (!Filename[Pos])
505 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregore650c8c2009-07-07 00:12:59 +0000507 // If the file name has a '/' at the current position, skip over the '/'.
508 // We distinguish sysroot-based includes from absolute includes by the
509 // absence of '/' at the beginning of sysroot-based includes.
510 if (Filename[Pos] == '/')
511 ++Pos;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregore650c8c2009-07-07 00:12:59 +0000513 return Filename + Pos;
514}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000515
Douglas Gregorab41e632009-04-27 22:23:34 +0000516/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000517void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000518 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000519
Douglas Gregore650c8c2009-07-07 00:12:59 +0000520 // Metadata
521 const TargetInfo &Target = Context.Target;
522 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
523 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
524 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
525 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
526 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
527 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
528 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
529 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
530 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregore650c8c2009-07-07 00:12:59 +0000532 RecordData Record;
533 Record.push_back(pch::METADATA);
534 Record.push_back(pch::VERSION_MAJOR);
535 Record.push_back(pch::VERSION_MINOR);
536 Record.push_back(CLANG_VERSION_MAJOR);
537 Record.push_back(CLANG_VERSION_MINOR);
538 Record.push_back(isysroot != 0);
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000539 const std::string &TripleStr = Target.getTriple().getTriple();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000540 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Douglas Gregorb64c1932009-05-12 01:31:05 +0000542 // Original file name
543 SourceManager &SM = Context.getSourceManager();
544 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
545 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
546 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
547 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
548 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
549
550 llvm::sys::Path MainFilePath(MainFile->getName());
551 std::string MainFileName;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Douglas Gregorb64c1932009-05-12 01:31:05 +0000553 if (!MainFilePath.isAbsolute()) {
554 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000555 P.appendComponent(MainFilePath.str());
556 MainFileName = P.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000557 } else {
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000558 MainFileName = MainFilePath.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000559 }
560
Douglas Gregore650c8c2009-07-07 00:12:59 +0000561 const char *MainFileNameStr = MainFileName.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +0000562 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000563 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000564 RecordData Record;
565 Record.push_back(pch::ORIGINAL_FILE_NAME);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000566 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000567 }
Douglas Gregor445e23e2009-10-05 21:07:28 +0000568
569 // Subversion branch/version information.
570 BitCodeAbbrev *SvnAbbrev = new BitCodeAbbrev();
571 SvnAbbrev->Add(BitCodeAbbrevOp(pch::SVN_BRANCH_REVISION));
572 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // SVN revision
573 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
574 unsigned SvnAbbrevCode = Stream.EmitAbbrev(SvnAbbrev);
575 Record.clear();
576 Record.push_back(pch::SVN_BRANCH_REVISION);
577 Record.push_back(getClangSubversionRevision());
578 Stream.EmitRecordWithBlob(SvnAbbrevCode, Record, getClangSubversionPath());
Douglas Gregor2bec0412009-04-10 21:16:55 +0000579}
580
581/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000582void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
583 RecordData Record;
584 Record.push_back(LangOpts.Trigraphs);
585 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
586 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
587 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
588 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
589 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
590 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
591 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
592 Record.push_back(LangOpts.C99); // C99 Support
593 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
594 Record.push_back(LangOpts.CPlusPlus); // C++ Support
595 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000596 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000598 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
599 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
600 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000602 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000603 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
604 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000605 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000606 Record.push_back(LangOpts.Exceptions); // Support exception handling.
607
608 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
609 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
610 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
611
Chris Lattnerea5ce472009-04-27 07:35:58 +0000612 // Whether static initializers are protected by locks.
613 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +0000614 Record.push_back(LangOpts.POSIXThreads);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000615 Record.push_back(LangOpts.Blocks); // block extension to C
616 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
617 // they are unused.
618 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
619 // (modulo the platform support).
620
621 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
622 // signed integer arithmetic overflows.
623
624 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
625 // may be ripped out at any time.
626
627 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
Mike Stump1eb44332009-09-09 15:08:12 +0000628 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000629 // defined.
630 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
631 // opposed to __DYNAMIC__).
632 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
633
634 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
635 // used (instead of C99 semantics).
636 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000637 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
638 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000639 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
640 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000641 Record.push_back(LangOpts.getGCMode());
642 Record.push_back(LangOpts.getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000643 Record.push_back(LangOpts.getStackProtectorMode());
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000644 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000645 Record.push_back(LangOpts.OpenCL);
Anders Carlsson92f58222009-08-22 22:30:33 +0000646 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000647 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000648}
649
Douglas Gregor14f79002009-04-10 03:52:48 +0000650//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000651// stat cache Serialization
652//===----------------------------------------------------------------------===//
653
654namespace {
655// Trait used for the on-disk hash table of stat cache results.
656class VISIBILITY_HIDDEN PCHStatCacheTrait {
657public:
658 typedef const char * key_type;
659 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000661 typedef std::pair<int, struct stat> data_type;
662 typedef const data_type& data_type_ref;
663
664 static unsigned ComputeHash(const char *path) {
665 return BernsteinHash(path);
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
668 std::pair<unsigned,unsigned>
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000669 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
670 data_type_ref Data) {
671 unsigned StrLen = strlen(path);
672 clang::io::Emit16(Out, StrLen);
673 unsigned DataLen = 1; // result value
674 if (Data.first == 0)
675 DataLen += 4 + 4 + 2 + 8 + 8;
676 clang::io::Emit8(Out, DataLen);
677 return std::make_pair(StrLen + 1, DataLen);
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000680 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
681 Out.write(path, KeyLen);
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000684 void EmitData(llvm::raw_ostream& Out, key_type_ref,
685 data_type_ref Data, unsigned DataLen) {
686 using namespace clang::io;
687 uint64_t Start = Out.tell(); (void)Start;
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000689 // Result of stat()
690 Emit8(Out, Data.first? 1 : 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000692 if (Data.first == 0) {
693 Emit32(Out, (uint32_t) Data.second.st_ino);
694 Emit32(Out, (uint32_t) Data.second.st_dev);
695 Emit16(Out, (uint16_t) Data.second.st_mode);
696 Emit64(Out, (uint64_t) Data.second.st_mtime);
697 Emit64(Out, (uint64_t) Data.second.st_size);
698 }
699
700 assert(Out.tell() - Start == DataLen && "Wrong data length");
701 }
702};
703} // end anonymous namespace
704
705/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000706void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
707 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000708 // Build the on-disk hash table containing information about every
709 // stat() call.
710 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
711 unsigned NumStatEntries = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000712 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000713 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000714 Stat != StatEnd; ++Stat, ++NumStatEntries) {
715 const char *Filename = Stat->first();
716 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
717 Generator.insert(Filename, Stat->second);
718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000720 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000721 llvm::SmallString<4096> StatCacheData;
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000722 uint32_t BucketOffset;
723 {
724 llvm::raw_svector_ostream Out(StatCacheData);
725 // Make sure that no bucket is at offset 0
726 clang::io::Emit32(Out, 0);
727 BucketOffset = Generator.Emit(Out);
728 }
729
730 // Create a blob abbreviation
731 using namespace llvm;
732 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
733 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
736 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
737 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
738
739 // Write the stat cache
740 RecordData Record;
741 Record.push_back(pch::STAT_CACHE);
742 Record.push_back(BucketOffset);
743 Record.push_back(NumStatEntries);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000744 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000745}
746
747//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000748// Source Manager Serialization
749//===----------------------------------------------------------------------===//
750
751/// \brief Create an abbreviation for the SLocEntry that refers to a
752/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000753static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000754 using namespace llvm;
755 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
756 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
759 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
760 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000761 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000762 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000763}
764
765/// \brief Create an abbreviation for the SLocEntry that refers to a
766/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000767static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000768 using namespace llvm;
769 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
770 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
771 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
772 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
773 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
774 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
775 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000776 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000777}
778
779/// \brief Create an abbreviation for the SLocEntry that refers to a
780/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000781static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000782 using namespace llvm;
783 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
784 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000786 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000787}
788
789/// \brief Create an abbreviation for the SLocEntry that refers to an
790/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000791static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000792 using namespace llvm;
793 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
794 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
797 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
798 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000800 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000801}
802
803/// \brief Writes the block containing the serialized form of the
804/// source manager.
805///
806/// TODO: We should probably use an on-disk hash table (stored in a
807/// blob), indexed based on the file name, so that we only create
808/// entries for files that we actually need. In the common case (no
809/// errors), we probably won't have to create file entries for any of
810/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000811void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000812 const Preprocessor &PP,
813 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000814 RecordData Record;
815
Chris Lattnerf04ad692009-04-10 17:16:57 +0000816 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000817 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000818
819 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000820 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
821 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
822 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
823 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000824
Douglas Gregorbd945002009-04-13 16:31:14 +0000825 // Write the line table.
826 if (SourceMgr.hasLineTable()) {
827 LineTableInfo &LineTable = SourceMgr.getLineTable();
828
829 // Emit the file names
830 Record.push_back(LineTable.getNumFilenames());
831 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
832 // Emit the file name
833 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000834 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000835 unsigned FilenameLen = Filename? strlen(Filename) : 0;
836 Record.push_back(FilenameLen);
837 if (FilenameLen)
838 Record.insert(Record.end(), Filename, Filename + FilenameLen);
839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregorbd945002009-04-13 16:31:14 +0000841 // Emit the line entries
842 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
843 L != LEnd; ++L) {
844 // Emit the file ID
845 Record.push_back(L->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregorbd945002009-04-13 16:31:14 +0000847 // Emit the line entries
848 Record.push_back(L->second.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000849 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
Douglas Gregorbd945002009-04-13 16:31:14 +0000850 LEEnd = L->second.end();
851 LE != LEEnd; ++LE) {
852 Record.push_back(LE->FileOffset);
853 Record.push_back(LE->LineNo);
854 Record.push_back(LE->FilenameID);
855 Record.push_back((unsigned)LE->FileKind);
856 Record.push_back(LE->IncludeOffset);
857 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000858 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000859 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000860 }
861
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000862 // Write out entries for all of the header files we know about.
Mike Stump1eb44332009-09-09 15:08:12 +0000863 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000864 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000865 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000866 E = HS.header_file_end();
867 I != E; ++I) {
868 Record.push_back(I->isImport);
869 Record.push_back(I->DirInfo);
870 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000871 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000872 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
873 Record.clear();
874 }
875
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000876 // Write out the source location entry table. We skip the first
877 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000878 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000879 RecordData PreloadSLocs;
880 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000881 for (SourceManager::sloc_entry_iterator
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000882 SLoc = SourceMgr.sloc_entry_begin() + 1,
883 SLocEnd = SourceMgr.sloc_entry_end();
884 SLoc != SLocEnd; ++SLoc) {
885 // Record the offset of this source-location entry.
886 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
887
888 // Figure out which record code to use.
889 unsigned Code;
890 if (SLoc->isFile()) {
891 if (SLoc->getFile().getContentCache()->Entry)
892 Code = pch::SM_SLOC_FILE_ENTRY;
893 else
894 Code = pch::SM_SLOC_BUFFER_ENTRY;
895 } else
896 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
897 Record.clear();
898 Record.push_back(Code);
899
900 Record.push_back(SLoc->getOffset());
901 if (SLoc->isFile()) {
902 const SrcMgr::FileInfo &File = SLoc->getFile();
903 Record.push_back(File.getIncludeLoc().getRawEncoding());
904 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
905 Record.push_back(File.hasLineDirectives());
906
907 const SrcMgr::ContentCache *Content = File.getContentCache();
908 if (Content->Entry) {
909 // The source location entry is a file. The blob associated
910 // with this entry is the file name.
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregore650c8c2009-07-07 00:12:59 +0000912 // Turn the file name into an absolute path, if it isn't already.
913 const char *Filename = Content->Entry->getName();
914 llvm::sys::Path FilePath(Filename, strlen(Filename));
915 std::string FilenameStr;
916 if (!FilePath.isAbsolute()) {
917 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000918 P.appendComponent(FilePath.str());
919 FilenameStr = P.str();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000920 Filename = FilenameStr.c_str();
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregore650c8c2009-07-07 00:12:59 +0000923 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000924 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000925
926 // FIXME: For now, preload all file source locations, so that
927 // we get the appropriate File entries in the reader. This is
928 // a temporary measure.
929 PreloadSLocs.push_back(SLocEntryOffsets.size());
930 } else {
931 // The source location entry is a buffer. The blob associated
932 // with this entry contains the contents of the buffer.
933
934 // We add one to the size so that we capture the trailing NULL
935 // that is required by llvm::MemoryBuffer::getMemBuffer (on
936 // the reader side).
937 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
938 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000939 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
940 llvm::StringRef(Name, strlen(Name) + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000941 Record.clear();
942 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
943 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Daniel Dunbarec312a12009-08-24 09:31:37 +0000944 llvm::StringRef(Buffer->getBufferStart(),
945 Buffer->getBufferSize() + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000946
947 if (strcmp(Name, "<built-in>") == 0)
948 PreloadSLocs.push_back(SLocEntryOffsets.size());
949 }
950 } else {
951 // The source location entry is an instantiation.
952 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
953 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
954 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
955 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
956
957 // Compute the token length for this macro expansion.
958 unsigned NextOffset = SourceMgr.getNextOffset();
959 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
960 if (++NextSLoc != SLocEnd)
961 NextOffset = NextSLoc->getOffset();
962 Record.push_back(NextOffset - SLoc->getOffset() - 1);
963 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
964 }
965 }
966
Douglas Gregorc9490c02009-04-16 22:23:12 +0000967 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000968
969 if (SLocEntryOffsets.empty())
970 return;
971
972 // Write the source-location offsets table into the PCH block. This
973 // table is used for lazily loading source-location information.
974 using namespace llvm;
975 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
976 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
977 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
978 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
979 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
980 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000982 Record.clear();
983 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
984 Record.push_back(SLocEntryOffsets.size());
985 Record.push_back(SourceMgr.getNextOffset());
986 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +0000987 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +0000988 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000989
990 // Write the source location entry preloads array, telling the PCH
991 // reader which source locations entries it should load eagerly.
992 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000993}
994
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000995//===----------------------------------------------------------------------===//
996// Preprocessor Serialization
997//===----------------------------------------------------------------------===//
998
Chris Lattner0b1fb982009-04-10 17:15:23 +0000999/// \brief Writes the block containing the serialized form of the
1000/// preprocessor.
1001///
Chris Lattnerdf961c22009-04-10 18:08:30 +00001002void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001003 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +00001004
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001005 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1006 if (PP.getCounterValue() != 0) {
1007 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +00001008 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001009 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001010 }
1011
1012 // Enter the preprocessor block.
1013 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001015 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1016 // FIXME: use diagnostics subsystem for localization etc.
1017 if (PP.SawDateOrTime())
1018 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001020 // Loop over all the macro definitions that are live at the end of the file,
1021 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001022 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1023 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001024 // FIXME: This emits macros in hash table order, we should do it in a stable
1025 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001026 MacroInfo *MI = I->second;
1027
1028 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1029 // been redefined by the header (in which case they are not isBuiltinMacro).
1030 if (MI->isBuiltinMacro())
1031 continue;
1032
Douglas Gregor37e26842009-04-21 23:56:24 +00001033 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001034 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001035 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001036 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1037 Record.push_back(MI->isUsed());
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001039 unsigned Code;
1040 if (MI->isObjectLike()) {
1041 Code = pch::PP_MACRO_OBJECT_LIKE;
1042 } else {
1043 Code = pch::PP_MACRO_FUNCTION_LIKE;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001045 Record.push_back(MI->isC99Varargs());
1046 Record.push_back(MI->isGNUVarargs());
1047 Record.push_back(MI->getNumArgs());
1048 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1049 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001050 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001051 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001052 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001053 Record.clear();
1054
Chris Lattnerdf961c22009-04-10 18:08:30 +00001055 // Emit the tokens array.
1056 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1057 // Note that we know that the preprocessor does not have any annotation
1058 // tokens in it because they are created by the parser, and thus can't be
1059 // in a macro definition.
1060 const Token &Tok = MI->getReplacementToken(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattnerdf961c22009-04-10 18:08:30 +00001062 Record.push_back(Tok.getLocation().getRawEncoding());
1063 Record.push_back(Tok.getLength());
1064
Chris Lattnerdf961c22009-04-10 18:08:30 +00001065 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1066 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001067 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Chris Lattnerdf961c22009-04-10 18:08:30 +00001069 // FIXME: Should translate token kind to a stable encoding.
1070 Record.push_back(Tok.getKind());
1071 // FIXME: Should translate token flags to a stable encoding.
1072 Record.push_back(Tok.getFlags());
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Douglas Gregorc9490c02009-04-16 22:23:12 +00001074 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001075 Record.clear();
1076 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001077 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001078 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001079 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001080}
1081
Douglas Gregor2e222532009-07-02 17:08:52 +00001082void PCHWriter::WriteComments(ASTContext &Context) {
1083 using namespace llvm;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Douglas Gregor2e222532009-07-02 17:08:52 +00001085 if (Context.Comments.empty())
1086 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Douglas Gregor2e222532009-07-02 17:08:52 +00001088 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1089 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1090 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1091 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregor2e222532009-07-02 17:08:52 +00001093 RecordData Record;
1094 Record.push_back(pch::COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +00001095 Stream.EmitRecordWithBlob(CommentCode, Record,
Douglas Gregor2e222532009-07-02 17:08:52 +00001096 (const char*)&Context.Comments[0],
1097 Context.Comments.size() * sizeof(SourceRange));
1098}
1099
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001100//===----------------------------------------------------------------------===//
1101// Type Serialization
1102//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001103
Douglas Gregor2cf26342009-04-09 22:27:44 +00001104/// \brief Write the representation of a type to the PCH stream.
John McCall0953e762009-09-24 19:53:00 +00001105void PCHWriter::WriteType(QualType T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001106 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001107 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001108 ID = NextTypeID++;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Douglas Gregor2cf26342009-04-09 22:27:44 +00001110 // Record the offset for this type.
1111 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001112 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001113 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1114 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001115 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001116 }
1117
1118 RecordData Record;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregor2cf26342009-04-09 22:27:44 +00001120 // Emit the type's representation.
1121 PCHTypeWriter W(*this, Record);
John McCall0953e762009-09-24 19:53:00 +00001122
1123 if (T.hasNonFastQualifiers()) {
1124 Qualifiers Qs = T.getQualifiers();
1125 AddTypeRef(T.getUnqualifiedType(), Record);
1126 Record.push_back(Qs.getAsOpaqueValue());
1127 W.Code = pch::TYPE_EXT_QUAL;
1128 } else {
1129 switch (T->getTypeClass()) {
1130 // For all of the concrete, non-dependent types, call the
1131 // appropriate visitor function.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001132#define TYPE(Class, Base) \
John McCall0953e762009-09-24 19:53:00 +00001133 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001134#define ABSTRACT_TYPE(Class, Base)
1135#define DEPENDENT_TYPE(Class, Base)
1136#include "clang/AST/TypeNodes.def"
1137
John McCall0953e762009-09-24 19:53:00 +00001138 // For all of the dependent type nodes (which only occur in C++
1139 // templates), produce an error.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001140#define TYPE(Class, Base)
1141#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1142#include "clang/AST/TypeNodes.def"
John McCall0953e762009-09-24 19:53:00 +00001143 assert(false && "Cannot serialize dependent type nodes");
1144 break;
1145 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001146 }
1147
1148 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001149 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001150
1151 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001152 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001153}
1154
1155/// \brief Write a block containing all of the types.
1156void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +00001157 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001158 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159
Douglas Gregor366809a2009-04-26 03:49:13 +00001160 // Emit all of the types that need to be emitted (so far).
1161 while (!TypesToEmit.empty()) {
John McCall0953e762009-09-24 19:53:00 +00001162 QualType T = TypesToEmit.front();
Douglas Gregor366809a2009-04-26 03:49:13 +00001163 TypesToEmit.pop();
Douglas Gregor366809a2009-04-26 03:49:13 +00001164 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001165 }
1166
1167 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +00001168 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001169}
1170
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001171//===----------------------------------------------------------------------===//
1172// Declaration Serialization
1173//===----------------------------------------------------------------------===//
1174
Douglas Gregor2cf26342009-04-09 22:27:44 +00001175/// \brief Write the block containing all of the declaration IDs
1176/// lexically declared within the given DeclContext.
1177///
1178/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1179/// bistream, or 0 if no block was written.
Mike Stump1eb44332009-09-09 15:08:12 +00001180uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregor2cf26342009-04-09 22:27:44 +00001181 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001182 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001183 return 0;
1184
Douglas Gregorc9490c02009-04-16 22:23:12 +00001185 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001186 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001187 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1188 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001189 AddDeclRef(*D, Record);
1190
Douglas Gregor25123082009-04-22 22:34:57 +00001191 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001192 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001193 return Offset;
1194}
1195
1196/// \brief Write the block containing all of the declaration IDs
1197/// visible from the given DeclContext.
1198///
1199/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1200/// bistream, or 0 if no block was written.
1201uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1202 DeclContext *DC) {
1203 if (DC->getPrimaryContext() != DC)
1204 return 0;
1205
Douglas Gregoraff22df2009-04-21 22:32:33 +00001206 // Since there is no name lookup into functions or methods, and we
1207 // perform name lookup for the translation unit via the
1208 // IdentifierInfo chains, don't bother to build a
1209 // visible-declarations table for these entities.
1210 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001211 return 0;
1212
Douglas Gregor2cf26342009-04-09 22:27:44 +00001213 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001215
1216 // Serialize the contents of the mapping used for lookup. Note that,
1217 // although we have two very different code paths, the serialized
1218 // representation is the same for both cases: a declaration name,
1219 // followed by a size, followed by references to the visible
1220 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001221 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001222 RecordData Record;
1223 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001224 if (!Map)
1225 return 0;
1226
Douglas Gregor2cf26342009-04-09 22:27:44 +00001227 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1228 D != DEnd; ++D) {
1229 AddDeclarationName(D->first, Record);
1230 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1231 Record.push_back(Result.second - Result.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001232 for (; Result.first != Result.second; ++Result.first)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001233 AddDeclRef(*Result.first, Record);
1234 }
1235
1236 if (Record.size() == 0)
1237 return 0;
1238
Douglas Gregorc9490c02009-04-16 22:23:12 +00001239 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001240 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001241 return Offset;
1242}
1243
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001244//===----------------------------------------------------------------------===//
1245// Global Method Pool and Selector Serialization
1246//===----------------------------------------------------------------------===//
1247
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001248namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001249// Trait used for the on-disk hash table used in the method pool.
1250class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1251 PCHWriter &Writer;
1252
1253public:
1254 typedef Selector key_type;
1255 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001257 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1258 typedef const data_type& data_type_ref;
1259
1260 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001262 static unsigned ComputeHash(Selector Sel) {
1263 unsigned N = Sel.getNumArgs();
1264 if (N == 0)
1265 ++N;
1266 unsigned R = 5381;
1267 for (unsigned I = 0; I != N; ++I)
1268 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1269 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1270 return R;
1271 }
Mike Stump1eb44332009-09-09 15:08:12 +00001272
1273 std::pair<unsigned,unsigned>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001274 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1275 data_type_ref Methods) {
1276 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1277 clang::io::Emit16(Out, KeyLen);
1278 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
Mike Stump1eb44332009-09-09 15:08:12 +00001279 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001280 Method = Method->Next)
1281 if (Method->Method)
1282 DataLen += 4;
Mike Stump1eb44332009-09-09 15:08:12 +00001283 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001284 Method = Method->Next)
1285 if (Method->Method)
1286 DataLen += 4;
1287 clang::io::Emit16(Out, DataLen);
1288 return std::make_pair(KeyLen, DataLen);
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Douglas Gregor83941df2009-04-25 17:48:32 +00001291 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump1eb44332009-09-09 15:08:12 +00001292 uint64_t Start = Out.tell();
Douglas Gregor83941df2009-04-25 17:48:32 +00001293 assert((Start >> 32) == 0 && "Selector key offset too large");
1294 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001295 unsigned N = Sel.getNumArgs();
1296 clang::io::Emit16(Out, N);
1297 if (N == 0)
1298 N = 1;
1299 for (unsigned I = 0; I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001300 clang::io::Emit32(Out,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001301 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001304 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001305 data_type_ref Methods, unsigned DataLen) {
1306 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001307 unsigned NumInstanceMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001308 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001309 Method = Method->Next)
1310 if (Method->Method)
1311 ++NumInstanceMethods;
1312
1313 unsigned NumFactoryMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001314 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001315 Method = Method->Next)
1316 if (Method->Method)
1317 ++NumFactoryMethods;
1318
1319 clang::io::Emit16(Out, NumInstanceMethods);
1320 clang::io::Emit16(Out, NumFactoryMethods);
Mike Stump1eb44332009-09-09 15:08:12 +00001321 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001322 Method = Method->Next)
1323 if (Method->Method)
1324 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Mike Stump1eb44332009-09-09 15:08:12 +00001325 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001326 Method = Method->Next)
1327 if (Method->Method)
1328 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001329
1330 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001331 }
1332};
1333} // end anonymous namespace
1334
1335/// \brief Write the method pool into the PCH file.
1336///
1337/// The method pool contains both instance and factory methods, stored
1338/// in an on-disk hash table indexed by the selector.
1339void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1340 using namespace llvm;
1341
1342 // Create and write out the blob that contains the instance and
1343 // factor method pools.
1344 bool Empty = true;
1345 {
1346 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001348 // Create the on-disk hash table representation. Start by
1349 // iterating through the instance method pool.
1350 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001351 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001352 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001353 Instance = SemaRef.InstanceMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001354 InstanceEnd = SemaRef.InstanceMethodPool.end();
1355 Instance != InstanceEnd; ++Instance) {
1356 // Check whether there is a factory method with the same
1357 // selector.
1358 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1359 = SemaRef.FactoryMethodPool.find(Instance->first);
1360
1361 if (Factory == SemaRef.FactoryMethodPool.end())
1362 Generator.insert(Instance->first,
Mike Stump1eb44332009-09-09 15:08:12 +00001363 std::make_pair(Instance->second,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001364 ObjCMethodList()));
1365 else
1366 Generator.insert(Instance->first,
1367 std::make_pair(Instance->second, Factory->second));
1368
Douglas Gregor83941df2009-04-25 17:48:32 +00001369 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001370 Empty = false;
1371 }
1372
1373 // Now iterate through the factory method pool, to pick up any
1374 // selectors that weren't already in the instance method pool.
1375 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001376 Factory = SemaRef.FactoryMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001377 FactoryEnd = SemaRef.FactoryMethodPool.end();
1378 Factory != FactoryEnd; ++Factory) {
1379 // Check whether there is an instance method with the same
1380 // selector. If so, there is no work to do here.
1381 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1382 = SemaRef.InstanceMethodPool.find(Factory->first);
1383
Douglas Gregor83941df2009-04-25 17:48:32 +00001384 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001385 Generator.insert(Factory->first,
1386 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001387 ++NumSelectorsInMethodPool;
1388 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001389
1390 Empty = false;
1391 }
1392
Douglas Gregor83941df2009-04-25 17:48:32 +00001393 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001394 return;
1395
1396 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001397 llvm::SmallString<4096> MethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001398 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001399 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001400 {
1401 PCHMethodPoolTrait Trait(*this);
1402 llvm::raw_svector_ostream Out(MethodPool);
1403 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001404 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001405 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001406
1407 // For every selector that we have seen but which was not
1408 // written into the hash table, write the selector itself and
1409 // record it's offset.
1410 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1411 if (SelectorOffsets[I] == 0)
1412 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001413 }
1414
1415 // Create a blob abbreviation
1416 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1417 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1418 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1421 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1422
Douglas Gregor83941df2009-04-25 17:48:32 +00001423 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001424 RecordData Record;
1425 Record.push_back(pch::METHOD_POOL);
1426 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001427 Record.push_back(NumSelectorsInMethodPool);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001428 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor83941df2009-04-25 17:48:32 +00001429
1430 // Create a blob abbreviation for the selector table offsets.
1431 Abbrev = new BitCodeAbbrev();
1432 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1433 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1435 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1436
1437 // Write the selector offsets table.
1438 Record.clear();
1439 Record.push_back(pch::SELECTOR_OFFSETS);
1440 Record.push_back(SelectorOffsets.size());
1441 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1442 (const char *)&SelectorOffsets.front(),
1443 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001444 }
1445}
1446
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001447//===----------------------------------------------------------------------===//
1448// Identifier Table Serialization
1449//===----------------------------------------------------------------------===//
1450
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001451namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001452class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1453 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001454 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001455
Douglas Gregora92193e2009-04-28 21:18:29 +00001456 /// \brief Determines whether this is an "interesting" identifier
1457 /// that needs a full IdentifierInfo structure written into the hash
1458 /// table.
1459 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1460 return II->isPoisoned() ||
1461 II->isExtensionToken() ||
1462 II->hasMacroDefinition() ||
1463 II->getObjCOrBuiltinID() ||
1464 II->getFETokenInfo<void>();
1465 }
1466
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001467public:
1468 typedef const IdentifierInfo* key_type;
1469 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001471 typedef pch::IdentID data_type;
1472 typedef data_type data_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
1474 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
Douglas Gregor37e26842009-04-21 23:56:24 +00001475 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001476
1477 static unsigned ComputeHash(const IdentifierInfo* II) {
1478 return clang::BernsteinHash(II->getName());
1479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
1481 std::pair<unsigned,unsigned>
1482 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001483 pch::IdentID ID) {
1484 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001485 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1486 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001487 DataLen += 2; // 2 bytes for builtin ID, flags
Mike Stump1eb44332009-09-09 15:08:12 +00001488 if (II->hasMacroDefinition() &&
Douglas Gregora92193e2009-04-28 21:18:29 +00001489 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001490 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001491 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1492 DEnd = IdentifierResolver::end();
1493 D != DEnd; ++D)
1494 DataLen += sizeof(pch::DeclID);
1495 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001496 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001497 // We emit the key length after the data length so that every
1498 // string is preceded by a 16-bit length. This matches the PTH
1499 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001500 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001501 return std::make_pair(KeyLen, DataLen);
1502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
1504 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001505 unsigned KeyLen) {
1506 // Record the location of the key data. This is used when generating
1507 // the mapping from persistent IDs to strings.
1508 Writer.SetIdentifierOffset(II, Out.tell());
1509 Out.write(II->getName(), KeyLen);
1510 }
Mike Stump1eb44332009-09-09 15:08:12 +00001511
1512 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001513 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001514 if (!isInterestingIdentifier(II)) {
1515 clang::io::Emit32(Out, ID << 1);
1516 return;
1517 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001518
Douglas Gregora92193e2009-04-28 21:18:29 +00001519 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001520 uint32_t Bits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001521 bool hasMacroDefinition =
1522 II->hasMacroDefinition() &&
Douglas Gregor37e26842009-04-21 23:56:24 +00001523 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001524 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001525 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001526 Bits = (Bits << 1) | II->isExtensionToken();
1527 Bits = (Bits << 1) | II->isPoisoned();
1528 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001529 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001530
Douglas Gregor37e26842009-04-21 23:56:24 +00001531 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001532 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001533
Douglas Gregor668c1a42009-04-21 22:25:48 +00001534 // Emit the declaration IDs in reverse order, because the
1535 // IdentifierResolver provides the declarations as they would be
1536 // visible (e.g., the function "stat" would come before the struct
1537 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1538 // adds declarations to the end of the list (so we need to see the
1539 // struct "status" before the function "status").
Mike Stump1eb44332009-09-09 15:08:12 +00001540 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
Douglas Gregor668c1a42009-04-21 22:25:48 +00001541 IdentifierResolver::end());
1542 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1543 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001544 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001545 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001546 }
1547};
1548} // end anonymous namespace
1549
Douglas Gregorafaf3082009-04-11 00:14:32 +00001550/// \brief Write the identifier table into the PCH file.
1551///
1552/// The identifier table consists of a blob containing string data
1553/// (the actual identifiers themselves) and a separate "offsets" index
1554/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001555void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001556 using namespace llvm;
1557
1558 // Create and write out the blob that contains the identifier
1559 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001560 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001561 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Douglas Gregor92b059e2009-04-28 20:33:11 +00001563 // Look for any identifiers that were named while processing the
1564 // headers, but are otherwise not needed. We add these to the hash
1565 // table to enable checking of the predefines buffer in the case
1566 // where the user adds new macro definitions when building the PCH
1567 // file.
1568 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1569 IDEnd = PP.getIdentifierTable().end();
1570 ID != IDEnd; ++ID)
1571 getIdentifierRef(ID->second);
1572
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001573 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001574 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001575 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1576 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1577 ID != IDEnd; ++ID) {
1578 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001579 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001580 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001581
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001582 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 llvm::SmallString<4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001584 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001585 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001586 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001587 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001588 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001589 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001590 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001591 }
1592
1593 // Create a blob abbreviation
1594 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1595 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001596 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001598 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001599
1600 // Write the identifier table
1601 RecordData Record;
1602 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001603 Record.push_back(BucketOffset);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001604 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001605 }
1606
1607 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001608 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1609 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1610 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1611 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1612 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1613
1614 RecordData Record;
1615 Record.push_back(pch::IDENTIFIER_OFFSET);
1616 Record.push_back(IdentifierOffsets.size());
1617 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1618 (const char *)&IdentifierOffsets.front(),
1619 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001620}
1621
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001622//===----------------------------------------------------------------------===//
1623// General Serialization Routines
1624//===----------------------------------------------------------------------===//
1625
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001626/// \brief Write a record containing the given attributes.
1627void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1628 RecordData Record;
1629 for (; Attr; Attr = Attr->getNext()) {
1630 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1631 Record.push_back(Attr->isInherited());
1632 switch (Attr->getKind()) {
1633 case Attr::Alias:
1634 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1635 break;
1636
1637 case Attr::Aligned:
1638 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1639 break;
1640
1641 case Attr::AlwaysInline:
1642 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001644 case Attr::AnalyzerNoReturn:
1645 break;
1646
1647 case Attr::Annotate:
1648 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1649 break;
1650
1651 case Attr::AsmLabel:
1652 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1653 break;
1654
1655 case Attr::Blocks:
1656 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1657 break;
1658
1659 case Attr::Cleanup:
1660 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1661 break;
1662
1663 case Attr::Const:
1664 break;
1665
1666 case Attr::Constructor:
1667 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1668 break;
1669
1670 case Attr::DLLExport:
1671 case Attr::DLLImport:
1672 case Attr::Deprecated:
1673 break;
1674
1675 case Attr::Destructor:
1676 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1677 break;
1678
1679 case Attr::FastCall:
1680 break;
1681
1682 case Attr::Format: {
1683 const FormatAttr *Format = cast<FormatAttr>(Attr);
1684 AddString(Format->getType(), Record);
1685 Record.push_back(Format->getFormatIdx());
1686 Record.push_back(Format->getFirstArg());
1687 break;
1688 }
1689
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001690 case Attr::FormatArg: {
1691 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1692 Record.push_back(Format->getFormatIdx());
1693 break;
1694 }
1695
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001696 case Attr::Sentinel : {
1697 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1698 Record.push_back(Sentinel->getSentinel());
1699 Record.push_back(Sentinel->getNullPos());
1700 break;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Chris Lattnercf2a7212009-04-20 19:12:28 +00001703 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001704 case Attr::IBOutletKind:
Ryan Flynn76168e22009-08-09 20:07:29 +00001705 case Attr::Malloc:
Mike Stump1feade82009-08-26 22:31:08 +00001706 case Attr::NoDebug:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001707 case Attr::NoReturn:
1708 case Attr::NoThrow:
Mike Stump1feade82009-08-26 22:31:08 +00001709 case Attr::NoInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001710 break;
1711
1712 case Attr::NonNull: {
1713 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1714 Record.push_back(NonNull->size());
1715 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1716 break;
1717 }
1718
1719 case Attr::ObjCException:
1720 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001721 case Attr::CFReturnsRetained:
1722 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001723 case Attr::Overloadable:
1724 break;
1725
Anders Carlssona860e752009-08-08 18:23:56 +00001726 case Attr::PragmaPack:
1727 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001728 break;
1729
Anders Carlssona860e752009-08-08 18:23:56 +00001730 case Attr::Packed:
1731 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001733 case Attr::Pure:
1734 break;
1735
1736 case Attr::Regparm:
1737 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1738 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Nate Begeman6f3d8382009-06-26 06:32:41 +00001740 case Attr::ReqdWorkGroupSize:
1741 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1742 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1743 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1744 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001745
1746 case Attr::Section:
1747 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1748 break;
1749
1750 case Attr::StdCall:
1751 case Attr::TransparentUnion:
1752 case Attr::Unavailable:
1753 case Attr::Unused:
1754 case Attr::Used:
1755 break;
1756
1757 case Attr::Visibility:
1758 // FIXME: stable encoding
Mike Stump1eb44332009-09-09 15:08:12 +00001759 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001760 break;
1761
1762 case Attr::WarnUnusedResult:
1763 case Attr::Weak:
1764 case Attr::WeakImport:
1765 break;
1766 }
1767 }
1768
Douglas Gregorc9490c02009-04-16 22:23:12 +00001769 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001770}
1771
1772void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1773 Record.push_back(Str.size());
1774 Record.insert(Record.end(), Str.begin(), Str.end());
1775}
1776
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001777/// \brief Note that the identifier II occurs at the given offset
1778/// within the identifier table.
1779void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001780 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001781}
1782
Douglas Gregor83941df2009-04-25 17:48:32 +00001783/// \brief Note that the selector Sel occurs at the given offset
1784/// within the method pool/selector table.
1785void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1786 unsigned ID = SelectorIDs[Sel];
1787 assert(ID && "Unknown selector");
1788 SelectorOffsets[ID - 1] = Offset;
1789}
1790
Mike Stump1eb44332009-09-09 15:08:12 +00001791PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1792 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001793 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1794 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001795
Douglas Gregore650c8c2009-07-07 00:12:59 +00001796void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1797 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001798 using namespace llvm;
1799
Douglas Gregore7785042009-04-20 15:53:59 +00001800 ASTContext &Context = SemaRef.Context;
1801 Preprocessor &PP = SemaRef.PP;
1802
Douglas Gregor2cf26342009-04-09 22:27:44 +00001803 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001804 Stream.Emit((unsigned)'C', 8);
1805 Stream.Emit((unsigned)'P', 8);
1806 Stream.Emit((unsigned)'C', 8);
1807 Stream.Emit((unsigned)'H', 8);
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001809 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001810
1811 // The translation unit is the first declaration we'll emit.
1812 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1813 DeclsToEmit.push(Context.getTranslationUnitDecl());
1814
Douglas Gregor2deaea32009-04-22 18:49:13 +00001815 // Make sure that we emit IdentifierInfos (and any attached
1816 // declarations) for builtins.
1817 {
1818 IdentifierTable &Table = PP.getIdentifierTable();
1819 llvm::SmallVector<const char *, 32> BuiltinNames;
1820 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1821 Context.getLangOptions().NoBuiltin);
1822 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1823 getIdentifierRef(&Table.get(BuiltinNames[I]));
1824 }
1825
Chris Lattner63d65f82009-09-08 18:19:27 +00001826 // Build a record containing all of the tentative definitions in this file, in
1827 // TentativeDefinitionList order. Generally, this record will be empty for
1828 // headers.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001829 RecordData TentativeDefinitions;
Chris Lattner63d65f82009-09-08 18:19:27 +00001830 for (unsigned i = 0, e = SemaRef.TentativeDefinitionList.size(); i != e; ++i){
1831 VarDecl *VD =
1832 SemaRef.TentativeDefinitions.lookup(SemaRef.TentativeDefinitionList[i]);
1833 if (VD) AddDeclRef(VD, TentativeDefinitions);
1834 }
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001835
Douglas Gregor14c22f22009-04-22 22:18:58 +00001836 // Build a record containing all of the locally-scoped external
1837 // declarations in this header file. Generally, this record will be
1838 // empty.
1839 RecordData LocallyScopedExternalDecls;
Chris Lattner63d65f82009-09-08 18:19:27 +00001840 // FIXME: This is filling in the PCH file in densemap order which is
1841 // nondeterminstic!
Mike Stump1eb44332009-09-09 15:08:12 +00001842 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Douglas Gregor14c22f22009-04-22 22:18:58 +00001843 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1844 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1845 TD != TDEnd; ++TD)
1846 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1847
Douglas Gregorb81c1702009-04-27 20:06:05 +00001848 // Build a record containing all of the ext_vector declarations.
1849 RecordData ExtVectorDecls;
1850 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1851 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1852
Douglas Gregor2cf26342009-04-09 22:27:44 +00001853 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001854 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001855 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001856 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001857 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001858 if (StatCalls && !isysroot)
1859 WriteStatCache(*StatCalls, isysroot);
1860 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001861 WritePreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +00001862 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001863 // Write the record of special types.
1864 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001866 AddTypeRef(Context.getBuiltinVaListType(), Record);
1867 AddTypeRef(Context.getObjCIdType(), Record);
1868 AddTypeRef(Context.getObjCSelType(), Record);
1869 AddTypeRef(Context.getObjCProtoType(), Record);
1870 AddTypeRef(Context.getObjCClassType(), Record);
1871 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1872 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1873 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001874 AddTypeRef(Context.getjmp_bufType(), Record);
1875 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregord1571ac2009-08-21 00:27:50 +00001876 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1877 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001878 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Douglas Gregor366809a2009-04-26 03:49:13 +00001880 // Keep writing types and declarations until all types and
1881 // declarations have been written.
1882 do {
1883 if (!DeclsToEmit.empty())
1884 WriteDeclsBlock(Context);
1885 if (!TypesToEmit.empty())
1886 WriteTypesBlock(Context);
1887 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1888
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001889 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001890 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001891
1892 // Write the type offsets array
1893 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1894 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1897 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1898 Record.clear();
1899 Record.push_back(pch::TYPE_OFFSET);
1900 Record.push_back(TypeOffsets.size());
1901 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001902 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001903 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001905 // Write the declaration offsets array
1906 Abbrev = new BitCodeAbbrev();
1907 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1908 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1910 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1911 Record.clear();
1912 Record.push_back(pch::DECL_OFFSET);
1913 Record.push_back(DeclOffsets.size());
1914 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001915 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001916 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001917
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001918 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001919 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001920 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001921
1922 // Write the record containing tentative definitions.
1923 if (!TentativeDefinitions.empty())
1924 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001925
1926 // Write the record containing locally-scoped external definitions.
1927 if (!LocallyScopedExternalDecls.empty())
Mike Stump1eb44332009-09-09 15:08:12 +00001928 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
Douglas Gregor14c22f22009-04-22 22:18:58 +00001929 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001930
1931 // Write the record containing ext_vector type names.
1932 if (!ExtVectorDecls.empty())
1933 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor3e1af842009-04-17 22:13:46 +00001935 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001936 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001937 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001938 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001939 Record.push_back(NumLexicalDeclContexts);
1940 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001941 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001942 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001943}
1944
1945void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1946 Record.push_back(Loc.getRawEncoding());
1947}
1948
1949void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1950 Record.push_back(Value.getBitWidth());
1951 unsigned N = Value.getNumWords();
1952 const uint64_t* Words = Value.getRawData();
1953 for (unsigned I = 0; I != N; ++I)
1954 Record.push_back(Words[I]);
1955}
1956
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001957void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1958 Record.push_back(Value.isUnsigned());
1959 AddAPInt(Value, Record);
1960}
1961
Douglas Gregor17fc2232009-04-14 21:55:33 +00001962void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1963 AddAPInt(Value.bitcastToAPInt(), Record);
1964}
1965
Douglas Gregor2cf26342009-04-09 22:27:44 +00001966void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001967 Record.push_back(getIdentifierRef(II));
1968}
1969
1970pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1971 if (II == 0)
1972 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001973
1974 pch::IdentID &ID = IdentifierIDs[II];
1975 if (ID == 0)
1976 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001977 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978}
1979
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001980void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1981 if (SelRef.getAsOpaquePtr() == 0) {
1982 Record.push_back(0);
1983 return;
1984 }
1985
1986 pch::SelectorID &SID = SelectorIDs[SelRef];
1987 if (SID == 0) {
1988 SID = SelectorIDs.size();
1989 SelVector.push_back(SelRef);
1990 }
1991 Record.push_back(SID);
1992}
1993
Douglas Gregor2cf26342009-04-09 22:27:44 +00001994void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1995 if (T.isNull()) {
1996 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1997 return;
1998 }
1999
John McCall0953e762009-09-24 19:53:00 +00002000 unsigned FastQuals = T.getFastQualifiers();
2001 T.removeFastQualifiers();
2002
2003 if (T.hasNonFastQualifiers()) {
2004 pch::TypeID &ID = TypeIDs[T];
2005 if (ID == 0) {
2006 // We haven't seen these qualifiers applied to this type before.
2007 // Assign it a new ID. This is the only time we enqueue a
2008 // qualified type, and it has no CV qualifiers.
2009 ID = NextTypeID++;
2010 TypesToEmit.push(T);
2011 }
2012
2013 // Encode the type qualifiers in the type reference.
2014 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2015 return;
2016 }
2017
2018 assert(!T.hasQualifiers());
2019
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002021 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022 switch (BT->getKind()) {
2023 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2024 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2025 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2026 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2027 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2028 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2029 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2030 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002031 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002032 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2033 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2034 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2035 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2036 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2037 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2038 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002039 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002040 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2041 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2042 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002043 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002044 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2045 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002046 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2047 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002048 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2049 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002050 case BuiltinType::UndeducedAuto:
2051 assert(0 && "Should not see undeduced auto here");
2052 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002053 }
2054
John McCall0953e762009-09-24 19:53:00 +00002055 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002056 return;
2057 }
2058
John McCall0953e762009-09-24 19:53:00 +00002059 pch::TypeID &ID = TypeIDs[T];
Douglas Gregor366809a2009-04-26 03:49:13 +00002060 if (ID == 0) {
2061 // We haven't seen this type before. Assign it a new ID and put it
John McCall0953e762009-09-24 19:53:00 +00002062 // into the queue of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002063 ID = NextTypeID++;
John McCall0953e762009-09-24 19:53:00 +00002064 TypesToEmit.push(T);
Douglas Gregor366809a2009-04-26 03:49:13 +00002065 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002066
2067 // Encode the type qualifiers in the type reference.
John McCall0953e762009-09-24 19:53:00 +00002068 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002069}
2070
2071void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2072 if (D == 0) {
2073 Record.push_back(0);
2074 return;
2075 }
2076
Douglas Gregor8038d512009-04-10 17:25:41 +00002077 pch::DeclID &ID = DeclIDs[D];
Mike Stump1eb44332009-09-09 15:08:12 +00002078 if (ID == 0) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002079 // We haven't seen this declaration before. Give it a new ID and
2080 // enqueue it in the list of declarations to emit.
2081 ID = DeclIDs.size();
2082 DeclsToEmit.push(const_cast<Decl *>(D));
2083 }
2084
2085 Record.push_back(ID);
2086}
2087
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002088pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2089 if (D == 0)
2090 return 0;
2091
2092 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2093 return DeclIDs[D];
2094}
2095
Douglas Gregor2cf26342009-04-09 22:27:44 +00002096void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002097 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002098 Record.push_back(Name.getNameKind());
2099 switch (Name.getNameKind()) {
2100 case DeclarationName::Identifier:
2101 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2102 break;
2103
2104 case DeclarationName::ObjCZeroArgSelector:
2105 case DeclarationName::ObjCOneArgSelector:
2106 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002107 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002108 break;
2109
2110 case DeclarationName::CXXConstructorName:
2111 case DeclarationName::CXXDestructorName:
2112 case DeclarationName::CXXConversionFunctionName:
2113 AddTypeRef(Name.getCXXNameType(), Record);
2114 break;
2115
2116 case DeclarationName::CXXOperatorName:
2117 Record.push_back(Name.getCXXOverloadedOperator());
2118 break;
2119
2120 case DeclarationName::CXXUsingDirective:
2121 // No extra data to emit
2122 break;
2123 }
2124}
Douglas Gregor0b748912009-04-14 21:18:50 +00002125