blob: 391a1f91659010d52186ce73beeb3a0bf26b11f8 [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
Douglas Gregor3251ceb2009-04-20 20:36:09 +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 Gregor17fc2232009-04-14 21:55:33 +000030#include "llvm/ADT/APFloat.h"
31#include "llvm/ADT/APInt.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamWriter.h"
33#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000034#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000035#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
39// Type serialization
40//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000041
Douglas Gregor2cf26342009-04-09 22:27:44 +000042namespace {
43 class VISIBILITY_HIDDEN PCHTypeWriter {
44 PCHWriter &Writer;
45 PCHWriter::RecordData &Record;
46
47 public:
48 /// \brief Type code that corresponds to the record generated.
49 pch::TypeCode Code;
50
51 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
52 : Writer(Writer), Record(Record) { }
53
54 void VisitArrayType(const ArrayType *T);
55 void VisitFunctionType(const FunctionType *T);
56 void VisitTagType(const TagType *T);
57
58#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
59#define ABSTRACT_TYPE(Class, Base)
60#define DEPENDENT_TYPE(Class, Base)
61#include "clang/AST/TypeNodes.def"
62 };
63}
64
65void PCHTypeWriter::VisitExtQualType(const ExtQualType *T) {
66 Writer.AddTypeRef(QualType(T->getBaseType(), 0), Record);
67 Record.push_back(T->getObjCGCAttr()); // FIXME: use stable values
68 Record.push_back(T->getAddressSpace());
69 Code = pch::TYPE_EXT_QUAL;
70}
71
72void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
73 assert(false && "Built-in types are never serialized");
74}
75
76void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
77 Record.push_back(T->getWidth());
78 Record.push_back(T->isSigned());
79 Code = pch::TYPE_FIXED_WIDTH_INT;
80}
81
82void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
83 Writer.AddTypeRef(T->getElementType(), Record);
84 Code = pch::TYPE_COMPLEX;
85}
86
87void PCHTypeWriter::VisitPointerType(const PointerType *T) {
88 Writer.AddTypeRef(T->getPointeeType(), Record);
89 Code = pch::TYPE_POINTER;
90}
91
92void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_BLOCK_POINTER;
95}
96
97void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Code = pch::TYPE_LVALUE_REFERENCE;
100}
101
102void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
103 Writer.AddTypeRef(T->getPointeeType(), Record);
104 Code = pch::TYPE_RVALUE_REFERENCE;
105}
106
107void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
108 Writer.AddTypeRef(T->getPointeeType(), Record);
109 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
110 Code = pch::TYPE_MEMBER_POINTER;
111}
112
113void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
114 Writer.AddTypeRef(T->getElementType(), Record);
115 Record.push_back(T->getSizeModifier()); // FIXME: stable values
116 Record.push_back(T->getIndexTypeQualifier()); // FIXME: stable values
117}
118
119void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
120 VisitArrayType(T);
121 Writer.AddAPInt(T->getSize(), Record);
122 Code = pch::TYPE_CONSTANT_ARRAY;
123}
124
125void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
126 VisitArrayType(T);
127 Code = pch::TYPE_INCOMPLETE_ARRAY;
128}
129
130void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
131 VisitArrayType(T);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000132 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000133 Code = pch::TYPE_VARIABLE_ARRAY;
134}
135
136void PCHTypeWriter::VisitVectorType(const VectorType *T) {
137 Writer.AddTypeRef(T->getElementType(), Record);
138 Record.push_back(T->getNumElements());
139 Code = pch::TYPE_VECTOR;
140}
141
142void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
143 VisitVectorType(T);
144 Code = pch::TYPE_EXT_VECTOR;
145}
146
147void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
148 Writer.AddTypeRef(T->getResultType(), Record);
149}
150
151void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
152 VisitFunctionType(T);
153 Code = pch::TYPE_FUNCTION_NO_PROTO;
154}
155
156void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
157 VisitFunctionType(T);
158 Record.push_back(T->getNumArgs());
159 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
160 Writer.AddTypeRef(T->getArgType(I), Record);
161 Record.push_back(T->isVariadic());
162 Record.push_back(T->getTypeQuals());
163 Code = pch::TYPE_FUNCTION_PROTO;
164}
165
166void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
167 Writer.AddDeclRef(T->getDecl(), Record);
168 Code = pch::TYPE_TYPEDEF;
169}
170
171void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000172 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000173 Code = pch::TYPE_TYPEOF_EXPR;
174}
175
176void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
177 Writer.AddTypeRef(T->getUnderlyingType(), Record);
178 Code = pch::TYPE_TYPEOF;
179}
180
181void PCHTypeWriter::VisitTagType(const TagType *T) {
182 Writer.AddDeclRef(T->getDecl(), Record);
183 assert(!T->isBeingDefined() &&
184 "Cannot serialize in the middle of a type definition");
185}
186
187void PCHTypeWriter::VisitRecordType(const RecordType *T) {
188 VisitTagType(T);
189 Code = pch::TYPE_RECORD;
190}
191
192void PCHTypeWriter::VisitEnumType(const EnumType *T) {
193 VisitTagType(T);
194 Code = pch::TYPE_ENUM;
195}
196
197void
198PCHTypeWriter::VisitTemplateSpecializationType(
199 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000200 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000201 assert(false && "Cannot serialize template specialization types");
202}
203
204void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000205 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000206 assert(false && "Cannot serialize qualified name types");
207}
208
209void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
210 Writer.AddDeclRef(T->getDecl(), Record);
211 Code = pch::TYPE_OBJC_INTERFACE;
212}
213
214void
215PCHTypeWriter::VisitObjCQualifiedInterfaceType(
216 const ObjCQualifiedInterfaceType *T) {
217 VisitObjCInterfaceType(T);
218 Record.push_back(T->getNumProtocols());
219 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
220 Writer.AddDeclRef(T->getProtocol(I), Record);
221 Code = pch::TYPE_OBJC_QUALIFIED_INTERFACE;
222}
223
224void PCHTypeWriter::VisitObjCQualifiedIdType(const ObjCQualifiedIdType *T) {
225 Record.push_back(T->getNumProtocols());
226 for (unsigned I = 0, N = T->getNumProtocols(); I != N; ++I)
227 Writer.AddDeclRef(T->getProtocols(I), Record);
228 Code = pch::TYPE_OBJC_QUALIFIED_ID;
229}
230
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000231//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000232// PCHWriter Implementation
233//===----------------------------------------------------------------------===//
234
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000235static void EmitBlockID(unsigned ID, const char *Name,
236 llvm::BitstreamWriter &Stream,
237 PCHWriter::RecordData &Record) {
238 Record.clear();
239 Record.push_back(ID);
240 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
241
242 // Emit the block name if present.
243 if (Name == 0 || Name[0] == 0) return;
244 Record.clear();
245 while (*Name)
246 Record.push_back(*Name++);
247 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
248}
249
250static void EmitRecordID(unsigned ID, const char *Name,
251 llvm::BitstreamWriter &Stream,
252 PCHWriter::RecordData &Record) {
253 Record.clear();
254 Record.push_back(ID);
255 while (*Name)
256 Record.push_back(*Name++);
257 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000258}
259
260static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
261 PCHWriter::RecordData &Record) {
262#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
263 RECORD(STMT_STOP);
264 RECORD(STMT_NULL_PTR);
265 RECORD(STMT_NULL);
266 RECORD(STMT_COMPOUND);
267 RECORD(STMT_CASE);
268 RECORD(STMT_DEFAULT);
269 RECORD(STMT_LABEL);
270 RECORD(STMT_IF);
271 RECORD(STMT_SWITCH);
272 RECORD(STMT_WHILE);
273 RECORD(STMT_DO);
274 RECORD(STMT_FOR);
275 RECORD(STMT_GOTO);
276 RECORD(STMT_INDIRECT_GOTO);
277 RECORD(STMT_CONTINUE);
278 RECORD(STMT_BREAK);
279 RECORD(STMT_RETURN);
280 RECORD(STMT_DECL);
281 RECORD(STMT_ASM);
282 RECORD(EXPR_PREDEFINED);
283 RECORD(EXPR_DECL_REF);
284 RECORD(EXPR_INTEGER_LITERAL);
285 RECORD(EXPR_FLOATING_LITERAL);
286 RECORD(EXPR_IMAGINARY_LITERAL);
287 RECORD(EXPR_STRING_LITERAL);
288 RECORD(EXPR_CHARACTER_LITERAL);
289 RECORD(EXPR_PAREN);
290 RECORD(EXPR_UNARY_OPERATOR);
291 RECORD(EXPR_SIZEOF_ALIGN_OF);
292 RECORD(EXPR_ARRAY_SUBSCRIPT);
293 RECORD(EXPR_CALL);
294 RECORD(EXPR_MEMBER);
295 RECORD(EXPR_BINARY_OPERATOR);
296 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
297 RECORD(EXPR_CONDITIONAL_OPERATOR);
298 RECORD(EXPR_IMPLICIT_CAST);
299 RECORD(EXPR_CSTYLE_CAST);
300 RECORD(EXPR_COMPOUND_LITERAL);
301 RECORD(EXPR_EXT_VECTOR_ELEMENT);
302 RECORD(EXPR_INIT_LIST);
303 RECORD(EXPR_DESIGNATED_INIT);
304 RECORD(EXPR_IMPLICIT_VALUE_INIT);
305 RECORD(EXPR_VA_ARG);
306 RECORD(EXPR_ADDR_LABEL);
307 RECORD(EXPR_STMT);
308 RECORD(EXPR_TYPES_COMPATIBLE);
309 RECORD(EXPR_CHOOSE);
310 RECORD(EXPR_GNU_NULL);
311 RECORD(EXPR_SHUFFLE_VECTOR);
312 RECORD(EXPR_BLOCK);
313 RECORD(EXPR_BLOCK_DECL_REF);
314 RECORD(EXPR_OBJC_STRING_LITERAL);
315 RECORD(EXPR_OBJC_ENCODE);
316 RECORD(EXPR_OBJC_SELECTOR_EXPR);
317 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
318 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
319 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
320 RECORD(EXPR_OBJC_KVC_REF_EXPR);
321 RECORD(EXPR_OBJC_MESSAGE_EXPR);
322 RECORD(EXPR_OBJC_SUPER_EXPR);
323 RECORD(STMT_OBJC_FOR_COLLECTION);
324 RECORD(STMT_OBJC_CATCH);
325 RECORD(STMT_OBJC_FINALLY);
326 RECORD(STMT_OBJC_AT_TRY);
327 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
328 RECORD(STMT_OBJC_AT_THROW);
329#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000330}
331
332void PCHWriter::WriteBlockInfoBlock() {
333 RecordData Record;
334 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
335
Chris Lattner2f4efd12009-04-27 00:40:25 +0000336#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000337#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
338
339 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000340 BLOCK(PCH_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000341 RECORD(TYPE_OFFSET);
342 RECORD(DECL_OFFSET);
343 RECORD(LANGUAGE_OPTIONS);
344 RECORD(TARGET_TRIPLE);
345 RECORD(IDENTIFIER_OFFSET);
346 RECORD(IDENTIFIER_TABLE);
347 RECORD(EXTERNAL_DEFINITIONS);
348 RECORD(SPECIAL_TYPES);
349 RECORD(STATISTICS);
350 RECORD(TENTATIVE_DEFINITIONS);
351 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
352 RECORD(SELECTOR_OFFSETS);
353 RECORD(METHOD_POOL);
354 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000355 RECORD(SOURCE_LOCATION_OFFSETS);
356 RECORD(SOURCE_LOCATION_PRELOADS);
357
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000358 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000359 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000360 RECORD(SM_SLOC_FILE_ENTRY);
361 RECORD(SM_SLOC_BUFFER_ENTRY);
362 RECORD(SM_SLOC_BUFFER_BLOB);
363 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
364 RECORD(SM_LINE_TABLE);
365 RECORD(SM_HEADER_FILE_INFO);
366
367 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000368 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000369 RECORD(PP_MACRO_OBJECT_LIKE);
370 RECORD(PP_MACRO_FUNCTION_LIKE);
371 RECORD(PP_TOKEN);
372
373 // Types block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000374 BLOCK(TYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000375 RECORD(TYPE_EXT_QUAL);
376 RECORD(TYPE_FIXED_WIDTH_INT);
377 RECORD(TYPE_COMPLEX);
378 RECORD(TYPE_POINTER);
379 RECORD(TYPE_BLOCK_POINTER);
380 RECORD(TYPE_LVALUE_REFERENCE);
381 RECORD(TYPE_RVALUE_REFERENCE);
382 RECORD(TYPE_MEMBER_POINTER);
383 RECORD(TYPE_CONSTANT_ARRAY);
384 RECORD(TYPE_INCOMPLETE_ARRAY);
385 RECORD(TYPE_VARIABLE_ARRAY);
386 RECORD(TYPE_VECTOR);
387 RECORD(TYPE_EXT_VECTOR);
388 RECORD(TYPE_FUNCTION_PROTO);
389 RECORD(TYPE_FUNCTION_NO_PROTO);
390 RECORD(TYPE_TYPEDEF);
391 RECORD(TYPE_TYPEOF_EXPR);
392 RECORD(TYPE_TYPEOF);
393 RECORD(TYPE_RECORD);
394 RECORD(TYPE_ENUM);
395 RECORD(TYPE_OBJC_INTERFACE);
396 RECORD(TYPE_OBJC_QUALIFIED_INTERFACE);
397 RECORD(TYPE_OBJC_QUALIFIED_ID);
Chris Lattner0558df22009-04-27 00:49:53 +0000398 // Statements and Exprs can occur in the Types block.
399 AddStmtsExprs(Stream, Record);
400
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000401 // Decls block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000402 BLOCK(DECLS_BLOCK);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000403 RECORD(DECL_ATTR);
404 RECORD(DECL_TRANSLATION_UNIT);
405 RECORD(DECL_TYPEDEF);
406 RECORD(DECL_ENUM);
407 RECORD(DECL_RECORD);
408 RECORD(DECL_ENUM_CONSTANT);
409 RECORD(DECL_FUNCTION);
410 RECORD(DECL_OBJC_METHOD);
411 RECORD(DECL_OBJC_INTERFACE);
412 RECORD(DECL_OBJC_PROTOCOL);
413 RECORD(DECL_OBJC_IVAR);
414 RECORD(DECL_OBJC_AT_DEFS_FIELD);
415 RECORD(DECL_OBJC_CLASS);
416 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
417 RECORD(DECL_OBJC_CATEGORY);
418 RECORD(DECL_OBJC_CATEGORY_IMPL);
419 RECORD(DECL_OBJC_IMPLEMENTATION);
420 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
421 RECORD(DECL_OBJC_PROPERTY);
422 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000423 RECORD(DECL_FIELD);
424 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000425 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000426 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000427 RECORD(DECL_ORIGINAL_PARM_VAR);
428 RECORD(DECL_FILE_SCOPE_ASM);
429 RECORD(DECL_BLOCK);
430 RECORD(DECL_CONTEXT_LEXICAL);
431 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattner0558df22009-04-27 00:49:53 +0000432 // Statements and Exprs can occur in the Decls block.
433 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000434#undef RECORD
435#undef BLOCK
436 Stream.ExitBlock();
437}
438
439
Douglas Gregor2bec0412009-04-10 21:16:55 +0000440/// \brief Write the target triple (e.g., i686-apple-darwin9).
441void PCHWriter::WriteTargetTriple(const TargetInfo &Target) {
442 using namespace llvm;
443 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
444 Abbrev->Add(BitCodeAbbrevOp(pch::TARGET_TRIPLE));
445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Triple name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000446 unsigned TripleAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor2bec0412009-04-10 21:16:55 +0000447
448 RecordData Record;
449 Record.push_back(pch::TARGET_TRIPLE);
450 const char *Triple = Target.getTargetTriple();
Douglas Gregorc9490c02009-04-16 22:23:12 +0000451 Stream.EmitRecordWithBlob(TripleAbbrev, Record, Triple, strlen(Triple));
Douglas Gregor2bec0412009-04-10 21:16:55 +0000452}
453
454/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000455void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
456 RecordData Record;
457 Record.push_back(LangOpts.Trigraphs);
458 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
459 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
460 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
461 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
462 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
463 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
464 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
465 Record.push_back(LangOpts.C99); // C99 Support
466 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
467 Record.push_back(LangOpts.CPlusPlus); // C++ Support
468 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
469 Record.push_back(LangOpts.NoExtensions); // All extensions are disabled, strict mode.
470 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
471
472 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
473 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
474 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
475
476 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
477 Record.push_back(LangOpts.Boolean); // Allow bool/true/false
478 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
479 Record.push_back(LangOpts.LaxVectorConversions);
480 Record.push_back(LangOpts.Exceptions); // Support exception handling.
481
482 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
483 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
484 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
485
Chris Lattnerea5ce472009-04-27 07:35:58 +0000486 // Whether static initializers are protected by locks.
487 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000488 Record.push_back(LangOpts.Blocks); // block extension to C
489 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
490 // they are unused.
491 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
492 // (modulo the platform support).
493
494 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
495 // signed integer arithmetic overflows.
496
497 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
498 // may be ripped out at any time.
499
500 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
501 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
502 // defined.
503 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
504 // opposed to __DYNAMIC__).
505 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
506
507 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
508 // used (instead of C99 semantics).
509 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
510 Record.push_back(LangOpts.getGCMode());
511 Record.push_back(LangOpts.getVisibilityMode());
512 Record.push_back(LangOpts.InstantiationDepth);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000513 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000514}
515
Douglas Gregor14f79002009-04-10 03:52:48 +0000516//===----------------------------------------------------------------------===//
517// Source Manager Serialization
518//===----------------------------------------------------------------------===//
519
520/// \brief Create an abbreviation for the SLocEntry that refers to a
521/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000522static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000523 using namespace llvm;
524 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
525 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000530 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000531 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000532}
533
534/// \brief Create an abbreviation for the SLocEntry that refers to a
535/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000536static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000537 using namespace llvm;
538 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
539 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
540 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
541 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
544 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000545 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000546}
547
548/// \brief Create an abbreviation for the SLocEntry that refers to a
549/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000550static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000551 using namespace llvm;
552 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
553 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000555 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000556}
557
558/// \brief Create an abbreviation for the SLocEntry that refers to an
559/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000560static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000561 using namespace llvm;
562 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
563 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
565 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000569 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000570}
571
572/// \brief Writes the block containing the serialized form of the
573/// source manager.
574///
575/// TODO: We should probably use an on-disk hash table (stored in a
576/// blob), indexed based on the file name, so that we only create
577/// entries for files that we actually need. In the common case (no
578/// errors), we probably won't have to create file entries for any of
579/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000580void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
581 const Preprocessor &PP) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000582 RecordData Record;
583
Chris Lattnerf04ad692009-04-10 17:16:57 +0000584 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000585 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000586
587 // Abbreviations for the various kinds of source-location entries.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000588 int SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
589 int SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
590 int SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
591 int SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000592
Douglas Gregorbd945002009-04-13 16:31:14 +0000593 // Write the line table.
594 if (SourceMgr.hasLineTable()) {
595 LineTableInfo &LineTable = SourceMgr.getLineTable();
596
597 // Emit the file names
598 Record.push_back(LineTable.getNumFilenames());
599 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
600 // Emit the file name
601 const char *Filename = LineTable.getFilename(I);
602 unsigned FilenameLen = Filename? strlen(Filename) : 0;
603 Record.push_back(FilenameLen);
604 if (FilenameLen)
605 Record.insert(Record.end(), Filename, Filename + FilenameLen);
606 }
607
608 // Emit the line entries
609 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
610 L != LEnd; ++L) {
611 // Emit the file ID
612 Record.push_back(L->first);
613
614 // Emit the line entries
615 Record.push_back(L->second.size());
616 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
617 LEEnd = L->second.end();
618 LE != LEEnd; ++LE) {
619 Record.push_back(LE->FileOffset);
620 Record.push_back(LE->LineNo);
621 Record.push_back(LE->FilenameID);
622 Record.push_back((unsigned)LE->FileKind);
623 Record.push_back(LE->IncludeOffset);
624 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000625 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000626 }
627 }
628
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000629 // Write out entries for all of the header files we know about.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000630 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000631 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000632 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
633 E = HS.header_file_end();
634 I != E; ++I) {
635 Record.push_back(I->isImport);
636 Record.push_back(I->DirInfo);
637 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000638 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000639 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
640 Record.clear();
641 }
642
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000643 // Write out the source location entry table. We skip the first
644 // entry, which is always the same dummy entry.
645 std::vector<uint64_t> SLocEntryOffsets;
646 RecordData PreloadSLocs;
647 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
648 for (SourceManager::sloc_entry_iterator
649 SLoc = SourceMgr.sloc_entry_begin() + 1,
650 SLocEnd = SourceMgr.sloc_entry_end();
651 SLoc != SLocEnd; ++SLoc) {
652 // Record the offset of this source-location entry.
653 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
654
655 // Figure out which record code to use.
656 unsigned Code;
657 if (SLoc->isFile()) {
658 if (SLoc->getFile().getContentCache()->Entry)
659 Code = pch::SM_SLOC_FILE_ENTRY;
660 else
661 Code = pch::SM_SLOC_BUFFER_ENTRY;
662 } else
663 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
664 Record.clear();
665 Record.push_back(Code);
666
667 Record.push_back(SLoc->getOffset());
668 if (SLoc->isFile()) {
669 const SrcMgr::FileInfo &File = SLoc->getFile();
670 Record.push_back(File.getIncludeLoc().getRawEncoding());
671 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
672 Record.push_back(File.hasLineDirectives());
673
674 const SrcMgr::ContentCache *Content = File.getContentCache();
675 if (Content->Entry) {
676 // The source location entry is a file. The blob associated
677 // with this entry is the file name.
678 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record,
679 Content->Entry->getName(),
680 strlen(Content->Entry->getName()));
681
682 // FIXME: For now, preload all file source locations, so that
683 // we get the appropriate File entries in the reader. This is
684 // a temporary measure.
685 PreloadSLocs.push_back(SLocEntryOffsets.size());
686 } else {
687 // The source location entry is a buffer. The blob associated
688 // with this entry contains the contents of the buffer.
689
690 // We add one to the size so that we capture the trailing NULL
691 // that is required by llvm::MemoryBuffer::getMemBuffer (on
692 // the reader side).
693 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
694 const char *Name = Buffer->getBufferIdentifier();
695 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, Name, strlen(Name) + 1);
696 Record.clear();
697 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
698 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
699 Buffer->getBufferStart(),
700 Buffer->getBufferSize() + 1);
701
702 if (strcmp(Name, "<built-in>") == 0)
703 PreloadSLocs.push_back(SLocEntryOffsets.size());
704 }
705 } else {
706 // The source location entry is an instantiation.
707 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
708 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
709 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
710 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
711
712 // Compute the token length for this macro expansion.
713 unsigned NextOffset = SourceMgr.getNextOffset();
714 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
715 if (++NextSLoc != SLocEnd)
716 NextOffset = NextSLoc->getOffset();
717 Record.push_back(NextOffset - SLoc->getOffset() - 1);
718 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
719 }
720 }
721
Douglas Gregorc9490c02009-04-16 22:23:12 +0000722 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000723
724 if (SLocEntryOffsets.empty())
725 return;
726
727 // Write the source-location offsets table into the PCH block. This
728 // table is used for lazily loading source-location information.
729 using namespace llvm;
730 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
731 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
732 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
733 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
735 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
736
737 Record.clear();
738 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
739 Record.push_back(SLocEntryOffsets.size());
740 Record.push_back(SourceMgr.getNextOffset());
741 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
742 (const char *)&SLocEntryOffsets.front(),
743 SLocEntryOffsets.size() * 8);
744
745 // Write the source location entry preloads array, telling the PCH
746 // reader which source locations entries it should load eagerly.
747 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +0000748}
749
Chris Lattner0b1fb982009-04-10 17:15:23 +0000750/// \brief Writes the block containing the serialized form of the
751/// preprocessor.
752///
Chris Lattnerdf961c22009-04-10 18:08:30 +0000753void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000754 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +0000755
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000756 // If the preprocessor __COUNTER__ value has been bumped, remember it.
757 if (PP.getCounterValue() != 0) {
758 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +0000759 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000760 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000761 }
762
763 // Enter the preprocessor block.
764 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Chris Lattnerc1f9d822009-04-13 01:29:17 +0000765
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000766 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
767 // FIXME: use diagnostics subsystem for localization etc.
768 if (PP.SawDateOrTime())
769 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
770
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000771 // Loop over all the macro definitions that are live at the end of the file,
772 // emitting each to the PP section.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000773 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
774 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +0000775 // FIXME: This emits macros in hash table order, we should do it in a stable
776 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000777 MacroInfo *MI = I->second;
778
779 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
780 // been redefined by the header (in which case they are not isBuiltinMacro).
781 if (MI->isBuiltinMacro())
782 continue;
783
Douglas Gregor37e26842009-04-21 23:56:24 +0000784 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +0000785 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +0000786 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000787 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
788 Record.push_back(MI->isUsed());
789
790 unsigned Code;
791 if (MI->isObjectLike()) {
792 Code = pch::PP_MACRO_OBJECT_LIKE;
793 } else {
794 Code = pch::PP_MACRO_FUNCTION_LIKE;
795
796 Record.push_back(MI->isC99Varargs());
797 Record.push_back(MI->isGNUVarargs());
798 Record.push_back(MI->getNumArgs());
799 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
800 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +0000801 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000802 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000803 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000804 Record.clear();
805
Chris Lattnerdf961c22009-04-10 18:08:30 +0000806 // Emit the tokens array.
807 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
808 // Note that we know that the preprocessor does not have any annotation
809 // tokens in it because they are created by the parser, and thus can't be
810 // in a macro definition.
811 const Token &Tok = MI->getReplacementToken(TokNo);
812
813 Record.push_back(Tok.getLocation().getRawEncoding());
814 Record.push_back(Tok.getLength());
815
Chris Lattnerdf961c22009-04-10 18:08:30 +0000816 // FIXME: When reading literal tokens, reconstruct the literal pointer if
817 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +0000818 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000819
820 // FIXME: Should translate token kind to a stable encoding.
821 Record.push_back(Tok.getKind());
822 // FIXME: Should translate token flags to a stable encoding.
823 Record.push_back(Tok.getFlags());
824
Douglas Gregorc9490c02009-04-16 22:23:12 +0000825 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +0000826 Record.clear();
827 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000828 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +0000829 }
Douglas Gregorc9490c02009-04-16 22:23:12 +0000830 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +0000831}
832
833
Douglas Gregor2cf26342009-04-09 22:27:44 +0000834/// \brief Write the representation of a type to the PCH stream.
835void PCHWriter::WriteType(const Type *T) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000836 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +0000837 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000838 ID = NextTypeID++;
839
840 // Record the offset for this type.
841 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +0000842 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000843 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
844 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000845 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000846 }
847
848 RecordData Record;
849
850 // Emit the type's representation.
851 PCHTypeWriter W(*this, Record);
852 switch (T->getTypeClass()) {
853 // For all of the concrete, non-dependent types, call the
854 // appropriate visitor function.
855#define TYPE(Class, Base) \
856 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
857#define ABSTRACT_TYPE(Class, Base)
858#define DEPENDENT_TYPE(Class, Base)
859#include "clang/AST/TypeNodes.def"
860
861 // For all of the dependent type nodes (which only occur in C++
862 // templates), produce an error.
863#define TYPE(Class, Base)
864#define DEPENDENT_TYPE(Class, Base) case Type::Class:
865#include "clang/AST/TypeNodes.def"
866 assert(false && "Cannot serialize dependent type nodes");
867 break;
868 }
869
870 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000871 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +0000872
873 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000874 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000875}
876
877/// \brief Write a block containing all of the types.
878void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattnerf04ad692009-04-10 17:16:57 +0000879 // Enter the types block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000880 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000881
Douglas Gregor366809a2009-04-26 03:49:13 +0000882 // Emit all of the types that need to be emitted (so far).
883 while (!TypesToEmit.empty()) {
884 const Type *T = TypesToEmit.front();
885 TypesToEmit.pop();
886 assert(!isa<BuiltinType>(T) && "Built-in types are not serialized");
887 WriteType(T);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000888 }
889
890 // Exit the types block
Douglas Gregorc9490c02009-04-16 22:23:12 +0000891 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000892}
893
894/// \brief Write the block containing all of the declaration IDs
895/// lexically declared within the given DeclContext.
896///
897/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
898/// bistream, or 0 if no block was written.
899uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
900 DeclContext *DC) {
Douglas Gregor8038d512009-04-10 17:25:41 +0000901 if (DC->decls_empty(Context))
Douglas Gregor2cf26342009-04-09 22:27:44 +0000902 return 0;
903
Douglas Gregorc9490c02009-04-16 22:23:12 +0000904 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000905 RecordData Record;
906 for (DeclContext::decl_iterator D = DC->decls_begin(Context),
907 DEnd = DC->decls_end(Context);
908 D != DEnd; ++D)
909 AddDeclRef(*D, Record);
910
Douglas Gregor25123082009-04-22 22:34:57 +0000911 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +0000912 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000913 return Offset;
914}
915
916/// \brief Write the block containing all of the declaration IDs
917/// visible from the given DeclContext.
918///
919/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
920/// bistream, or 0 if no block was written.
921uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
922 DeclContext *DC) {
923 if (DC->getPrimaryContext() != DC)
924 return 0;
925
Douglas Gregoraff22df2009-04-21 22:32:33 +0000926 // Since there is no name lookup into functions or methods, and we
927 // perform name lookup for the translation unit via the
928 // IdentifierInfo chains, don't bother to build a
929 // visible-declarations table for these entities.
930 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +0000931 return 0;
932
Douglas Gregor2cf26342009-04-09 22:27:44 +0000933 // Force the DeclContext to build a its name-lookup table.
934 DC->lookup(Context, DeclarationName());
935
936 // Serialize the contents of the mapping used for lookup. Note that,
937 // although we have two very different code paths, the serialized
938 // representation is the same for both cases: a declaration name,
939 // followed by a size, followed by references to the visible
940 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000941 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +0000942 RecordData Record;
943 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +0000944 if (!Map)
945 return 0;
946
Douglas Gregor2cf26342009-04-09 22:27:44 +0000947 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
948 D != DEnd; ++D) {
949 AddDeclarationName(D->first, Record);
950 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
951 Record.push_back(Result.second - Result.first);
952 for(; Result.first != Result.second; ++Result.first)
953 AddDeclRef(*Result.first, Record);
954 }
955
956 if (Record.size() == 0)
957 return 0;
958
Douglas Gregorc9490c02009-04-16 22:23:12 +0000959 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +0000960 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000961 return Offset;
962}
963
Douglas Gregor3251ceb2009-04-20 20:36:09 +0000964namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000965// Trait used for the on-disk hash table used in the method pool.
966class VISIBILITY_HIDDEN PCHMethodPoolTrait {
967 PCHWriter &Writer;
968
969public:
970 typedef Selector key_type;
971 typedef key_type key_type_ref;
972
973 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
974 typedef const data_type& data_type_ref;
975
976 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
977
978 static unsigned ComputeHash(Selector Sel) {
979 unsigned N = Sel.getNumArgs();
980 if (N == 0)
981 ++N;
982 unsigned R = 5381;
983 for (unsigned I = 0; I != N; ++I)
984 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
985 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
986 return R;
987 }
988
989 std::pair<unsigned,unsigned>
990 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
991 data_type_ref Methods) {
992 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
993 clang::io::Emit16(Out, KeyLen);
994 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
995 for (const ObjCMethodList *Method = &Methods.first; Method;
996 Method = Method->Next)
997 if (Method->Method)
998 DataLen += 4;
999 for (const ObjCMethodList *Method = &Methods.second; Method;
1000 Method = Method->Next)
1001 if (Method->Method)
1002 DataLen += 4;
1003 clang::io::Emit16(Out, DataLen);
1004 return std::make_pair(KeyLen, DataLen);
1005 }
1006
Douglas Gregor83941df2009-04-25 17:48:32 +00001007 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1008 uint64_t Start = Out.tell();
1009 assert((Start >> 32) == 0 && "Selector key offset too large");
1010 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001011 unsigned N = Sel.getNumArgs();
1012 clang::io::Emit16(Out, N);
1013 if (N == 0)
1014 N = 1;
1015 for (unsigned I = 0; I != N; ++I)
1016 clang::io::Emit32(Out,
1017 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1018 }
1019
1020 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001021 data_type_ref Methods, unsigned DataLen) {
1022 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001023 unsigned NumInstanceMethods = 0;
1024 for (const ObjCMethodList *Method = &Methods.first; Method;
1025 Method = Method->Next)
1026 if (Method->Method)
1027 ++NumInstanceMethods;
1028
1029 unsigned NumFactoryMethods = 0;
1030 for (const ObjCMethodList *Method = &Methods.second; Method;
1031 Method = Method->Next)
1032 if (Method->Method)
1033 ++NumFactoryMethods;
1034
1035 clang::io::Emit16(Out, NumInstanceMethods);
1036 clang::io::Emit16(Out, NumFactoryMethods);
1037 for (const ObjCMethodList *Method = &Methods.first; Method;
1038 Method = Method->Next)
1039 if (Method->Method)
1040 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001041 for (const ObjCMethodList *Method = &Methods.second; Method;
1042 Method = Method->Next)
1043 if (Method->Method)
1044 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001045
1046 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001047 }
1048};
1049} // end anonymous namespace
1050
1051/// \brief Write the method pool into the PCH file.
1052///
1053/// The method pool contains both instance and factory methods, stored
1054/// in an on-disk hash table indexed by the selector.
1055void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1056 using namespace llvm;
1057
1058 // Create and write out the blob that contains the instance and
1059 // factor method pools.
1060 bool Empty = true;
1061 {
1062 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1063
1064 // Create the on-disk hash table representation. Start by
1065 // iterating through the instance method pool.
1066 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001067 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001068 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1069 Instance = SemaRef.InstanceMethodPool.begin(),
1070 InstanceEnd = SemaRef.InstanceMethodPool.end();
1071 Instance != InstanceEnd; ++Instance) {
1072 // Check whether there is a factory method with the same
1073 // selector.
1074 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1075 = SemaRef.FactoryMethodPool.find(Instance->first);
1076
1077 if (Factory == SemaRef.FactoryMethodPool.end())
1078 Generator.insert(Instance->first,
1079 std::make_pair(Instance->second,
1080 ObjCMethodList()));
1081 else
1082 Generator.insert(Instance->first,
1083 std::make_pair(Instance->second, Factory->second));
1084
Douglas Gregor83941df2009-04-25 17:48:32 +00001085 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001086 Empty = false;
1087 }
1088
1089 // Now iterate through the factory method pool, to pick up any
1090 // selectors that weren't already in the instance method pool.
1091 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1092 Factory = SemaRef.FactoryMethodPool.begin(),
1093 FactoryEnd = SemaRef.FactoryMethodPool.end();
1094 Factory != FactoryEnd; ++Factory) {
1095 // Check whether there is an instance method with the same
1096 // selector. If so, there is no work to do here.
1097 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1098 = SemaRef.InstanceMethodPool.find(Factory->first);
1099
Douglas Gregor83941df2009-04-25 17:48:32 +00001100 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001101 Generator.insert(Factory->first,
1102 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001103 ++NumSelectorsInMethodPool;
1104 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001105
1106 Empty = false;
1107 }
1108
Douglas Gregor83941df2009-04-25 17:48:32 +00001109 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001110 return;
1111
1112 // Create the on-disk hash table in a buffer.
1113 llvm::SmallVector<char, 4096> MethodPool;
1114 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001115 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001116 {
1117 PCHMethodPoolTrait Trait(*this);
1118 llvm::raw_svector_ostream Out(MethodPool);
1119 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001120 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001121 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001122
1123 // For every selector that we have seen but which was not
1124 // written into the hash table, write the selector itself and
1125 // record it's offset.
1126 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1127 if (SelectorOffsets[I] == 0)
1128 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001129 }
1130
1131 // Create a blob abbreviation
1132 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1133 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1134 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001135 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001136 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1137 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1138
Douglas Gregor83941df2009-04-25 17:48:32 +00001139 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001140 RecordData Record;
1141 Record.push_back(pch::METHOD_POOL);
1142 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001143 Record.push_back(NumSelectorsInMethodPool);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001144 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record,
1145 &MethodPool.front(),
1146 MethodPool.size());
Douglas Gregor83941df2009-04-25 17:48:32 +00001147
1148 // Create a blob abbreviation for the selector table offsets.
1149 Abbrev = new BitCodeAbbrev();
1150 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1151 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1153 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1154
1155 // Write the selector offsets table.
1156 Record.clear();
1157 Record.push_back(pch::SELECTOR_OFFSETS);
1158 Record.push_back(SelectorOffsets.size());
1159 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1160 (const char *)&SelectorOffsets.front(),
1161 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001162 }
1163}
1164
1165namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001166class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1167 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001168 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001169
1170public:
1171 typedef const IdentifierInfo* key_type;
1172 typedef key_type key_type_ref;
1173
1174 typedef pch::IdentID data_type;
1175 typedef data_type data_type_ref;
1176
Douglas Gregor37e26842009-04-21 23:56:24 +00001177 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1178 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001179
1180 static unsigned ComputeHash(const IdentifierInfo* II) {
1181 return clang::BernsteinHash(II->getName());
1182 }
1183
Douglas Gregor37e26842009-04-21 23:56:24 +00001184 std::pair<unsigned,unsigned>
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001185 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1186 pch::IdentID ID) {
1187 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001188 unsigned DataLen = 4 + 4; // 4 bytes for token ID, builtin, flags
1189 // 4 bytes for the persistent ID
Douglas Gregor37e26842009-04-21 23:56:24 +00001190 if (II->hasMacroDefinition() &&
1191 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1192 DataLen += 8;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001193 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1194 DEnd = IdentifierResolver::end();
1195 D != DEnd; ++D)
1196 DataLen += sizeof(pch::DeclID);
Douglas Gregord6595a42009-04-25 21:04:17 +00001197 // We emit the key length after the data length so that the
1198 // "uninteresting" identifiers following the identifier hash table
1199 // structure will have the same (key length, key characters)
1200 // layout as the keys in the hash table. This also matches the
1201 // format for identifiers in pretokenized headers.
Douglas Gregor668c1a42009-04-21 22:25:48 +00001202 clang::io::Emit16(Out, DataLen);
Douglas Gregord6595a42009-04-25 21:04:17 +00001203 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001204 return std::make_pair(KeyLen, DataLen);
1205 }
1206
1207 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1208 unsigned KeyLen) {
1209 // Record the location of the key data. This is used when generating
1210 // the mapping from persistent IDs to strings.
1211 Writer.SetIdentifierOffset(II, Out.tell());
1212 Out.write(II->getName(), KeyLen);
1213 }
1214
1215 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1216 pch::IdentID ID, unsigned) {
1217 uint32_t Bits = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001218 bool hasMacroDefinition =
1219 II->hasMacroDefinition() &&
1220 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001221 Bits = Bits | (uint32_t)II->getTokenID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001222 Bits = (Bits << 10) | (uint32_t)II->getObjCOrBuiltinID();
1223 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001224 Bits = (Bits << 1) | II->isExtensionToken();
1225 Bits = (Bits << 1) | II->isPoisoned();
1226 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
1227 clang::io::Emit32(Out, Bits);
1228 clang::io::Emit32(Out, ID);
1229
Douglas Gregor37e26842009-04-21 23:56:24 +00001230 if (hasMacroDefinition)
1231 clang::io::Emit64(Out, Writer.getMacroOffset(II));
1232
Douglas Gregor668c1a42009-04-21 22:25:48 +00001233 // Emit the declaration IDs in reverse order, because the
1234 // IdentifierResolver provides the declarations as they would be
1235 // visible (e.g., the function "stat" would come before the struct
1236 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1237 // adds declarations to the end of the list (so we need to see the
1238 // struct "status" before the function "status").
1239 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1240 IdentifierResolver::end());
1241 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1242 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001243 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001244 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001245 }
1246};
1247} // end anonymous namespace
1248
Douglas Gregorafaf3082009-04-11 00:14:32 +00001249/// \brief Write the identifier table into the PCH file.
1250///
1251/// The identifier table consists of a blob containing string data
1252/// (the actual identifiers themselves) and a separate "offsets" index
1253/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001254void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001255 using namespace llvm;
1256
1257 // Create and write out the blob that contains the identifier
1258 // strings.
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001259 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001260 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001261 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1262
Douglas Gregord6595a42009-04-25 21:04:17 +00001263 llvm::SmallVector<const IdentifierInfo *, 32> UninterestingIdentifiers;
1264
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001265 // Create the on-disk hash table representation.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001266 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1267 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1268 ID != IDEnd; ++ID) {
1269 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregord6595a42009-04-25 21:04:17 +00001270
1271 // Classify each identifier as either "interesting" or "not
1272 // interesting". Interesting identifiers are those that have
1273 // additional information that needs to be read from the PCH
1274 // file, e.g., a built-in ID, declaration chain, or macro
1275 // definition. These identifiers are placed into the hash table
1276 // so that they can be found when looked up in the user program.
1277 // All other identifiers are "uninteresting", which means that
1278 // the IdentifierInfo built by default has all of the
1279 // information we care about. Such identifiers are placed after
1280 // the hash table.
1281 const IdentifierInfo *II = ID->first;
1282 if (II->isPoisoned() ||
1283 II->isExtensionToken() ||
1284 II->hasMacroDefinition() ||
1285 II->getObjCOrBuiltinID() ||
1286 II->getFETokenInfo<void>())
1287 Generator.insert(ID->first, ID->second);
1288 else
1289 UninterestingIdentifiers.push_back(II);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001290 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001291
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001292 // Create the on-disk hash table in a buffer.
1293 llvm::SmallVector<char, 4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001294 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001295 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001296 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001297 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001298 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001299 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001300 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregord6595a42009-04-25 21:04:17 +00001301
1302 for (unsigned I = 0, N = UninterestingIdentifiers.size(); I != N; ++I) {
1303 const IdentifierInfo *II = UninterestingIdentifiers[I];
1304 unsigned N = II->getLength() + 1;
1305 clang::io::Emit16(Out, N);
1306 SetIdentifierOffset(II, Out.tell());
1307 Out.write(II->getName(), N);
1308 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001309 }
1310
1311 // Create a blob abbreviation
1312 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1313 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001314 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001315 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001316 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001317
1318 // Write the identifier table
1319 RecordData Record;
1320 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001321 Record.push_back(BucketOffset);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001322 Stream.EmitRecordWithBlob(IDTableAbbrev, Record,
1323 &IdentifierTable.front(),
1324 IdentifierTable.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001325 }
1326
1327 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001328 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1329 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1330 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1332 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1333
1334 RecordData Record;
1335 Record.push_back(pch::IDENTIFIER_OFFSET);
1336 Record.push_back(IdentifierOffsets.size());
1337 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1338 (const char *)&IdentifierOffsets.front(),
1339 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001340}
1341
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001342/// \brief Write a record containing the given attributes.
1343void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1344 RecordData Record;
1345 for (; Attr; Attr = Attr->getNext()) {
1346 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1347 Record.push_back(Attr->isInherited());
1348 switch (Attr->getKind()) {
1349 case Attr::Alias:
1350 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1351 break;
1352
1353 case Attr::Aligned:
1354 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1355 break;
1356
1357 case Attr::AlwaysInline:
1358 break;
1359
1360 case Attr::AnalyzerNoReturn:
1361 break;
1362
1363 case Attr::Annotate:
1364 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1365 break;
1366
1367 case Attr::AsmLabel:
1368 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1369 break;
1370
1371 case Attr::Blocks:
1372 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1373 break;
1374
1375 case Attr::Cleanup:
1376 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1377 break;
1378
1379 case Attr::Const:
1380 break;
1381
1382 case Attr::Constructor:
1383 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1384 break;
1385
1386 case Attr::DLLExport:
1387 case Attr::DLLImport:
1388 case Attr::Deprecated:
1389 break;
1390
1391 case Attr::Destructor:
1392 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1393 break;
1394
1395 case Attr::FastCall:
1396 break;
1397
1398 case Attr::Format: {
1399 const FormatAttr *Format = cast<FormatAttr>(Attr);
1400 AddString(Format->getType(), Record);
1401 Record.push_back(Format->getFormatIdx());
1402 Record.push_back(Format->getFirstArg());
1403 break;
1404 }
1405
Chris Lattnercf2a7212009-04-20 19:12:28 +00001406 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001407 case Attr::IBOutletKind:
1408 case Attr::NoReturn:
1409 case Attr::NoThrow:
1410 case Attr::Nodebug:
1411 case Attr::Noinline:
1412 break;
1413
1414 case Attr::NonNull: {
1415 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1416 Record.push_back(NonNull->size());
1417 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1418 break;
1419 }
1420
1421 case Attr::ObjCException:
1422 case Attr::ObjCNSObject:
Ted Kremenek4064de92009-04-27 18:27:22 +00001423 case Attr::ObjCOwnershipCFRetain:
Ted Kremenekde9a81b2009-04-25 00:17:17 +00001424 case Attr::ObjCOwnershipRetain:
Ted Kremenek0fc169e2009-04-24 23:09:54 +00001425 case Attr::ObjCOwnershipReturns:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001426 case Attr::Overloadable:
1427 break;
1428
1429 case Attr::Packed:
1430 Record.push_back(cast<PackedAttr>(Attr)->getAlignment());
1431 break;
1432
1433 case Attr::Pure:
1434 break;
1435
1436 case Attr::Regparm:
1437 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1438 break;
1439
1440 case Attr::Section:
1441 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1442 break;
1443
1444 case Attr::StdCall:
1445 case Attr::TransparentUnion:
1446 case Attr::Unavailable:
1447 case Attr::Unused:
1448 case Attr::Used:
1449 break;
1450
1451 case Attr::Visibility:
1452 // FIXME: stable encoding
1453 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1454 break;
1455
1456 case Attr::WarnUnusedResult:
1457 case Attr::Weak:
1458 case Attr::WeakImport:
1459 break;
1460 }
1461 }
1462
Douglas Gregorc9490c02009-04-16 22:23:12 +00001463 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001464}
1465
1466void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1467 Record.push_back(Str.size());
1468 Record.insert(Record.end(), Str.begin(), Str.end());
1469}
1470
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001471/// \brief Note that the identifier II occurs at the given offset
1472/// within the identifier table.
1473void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001474 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001475}
1476
Douglas Gregor83941df2009-04-25 17:48:32 +00001477/// \brief Note that the selector Sel occurs at the given offset
1478/// within the method pool/selector table.
1479void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1480 unsigned ID = SelectorIDs[Sel];
1481 assert(ID && "Unknown selector");
1482 SelectorOffsets[ID - 1] = Offset;
1483}
1484
Douglas Gregorc9490c02009-04-16 22:23:12 +00001485PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
Douglas Gregor37e26842009-04-21 23:56:24 +00001486 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001487 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1488 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001489
Douglas Gregore7785042009-04-20 15:53:59 +00001490void PCHWriter::WritePCH(Sema &SemaRef) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001491 using namespace llvm;
1492
Douglas Gregore7785042009-04-20 15:53:59 +00001493 ASTContext &Context = SemaRef.Context;
1494 Preprocessor &PP = SemaRef.PP;
1495
Douglas Gregor2cf26342009-04-09 22:27:44 +00001496 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001497 Stream.Emit((unsigned)'C', 8);
1498 Stream.Emit((unsigned)'P', 8);
1499 Stream.Emit((unsigned)'C', 8);
1500 Stream.Emit((unsigned)'H', 8);
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001501
1502 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001503
1504 // The translation unit is the first declaration we'll emit.
1505 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1506 DeclsToEmit.push(Context.getTranslationUnitDecl());
1507
Douglas Gregor2deaea32009-04-22 18:49:13 +00001508 // Make sure that we emit IdentifierInfos (and any attached
1509 // declarations) for builtins.
1510 {
1511 IdentifierTable &Table = PP.getIdentifierTable();
1512 llvm::SmallVector<const char *, 32> BuiltinNames;
1513 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1514 Context.getLangOptions().NoBuiltin);
1515 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1516 getIdentifierRef(&Table.get(BuiltinNames[I]));
1517 }
1518
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001519 // Build a record containing all of the tentative definitions in
1520 // this header file. Generally, this record will be empty.
1521 RecordData TentativeDefinitions;
1522 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
1523 TD = SemaRef.TentativeDefinitions.begin(),
1524 TDEnd = SemaRef.TentativeDefinitions.end();
1525 TD != TDEnd; ++TD)
1526 AddDeclRef(TD->second, TentativeDefinitions);
1527
Douglas Gregor14c22f22009-04-22 22:18:58 +00001528 // Build a record containing all of the locally-scoped external
1529 // declarations in this header file. Generally, this record will be
1530 // empty.
1531 RecordData LocallyScopedExternalDecls;
1532 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1533 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1534 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1535 TD != TDEnd; ++TD)
1536 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1537
Douglas Gregor2cf26342009-04-09 22:27:44 +00001538 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001539 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001540 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregor2bec0412009-04-10 21:16:55 +00001541 WriteTargetTriple(Context.Target);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001542 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001543 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Chris Lattner0b1fb982009-04-10 17:15:23 +00001544 WritePreprocessor(PP);
Douglas Gregor366809a2009-04-26 03:49:13 +00001545
1546 // Keep writing types and declarations until all types and
1547 // declarations have been written.
1548 do {
1549 if (!DeclsToEmit.empty())
1550 WriteDeclsBlock(Context);
1551 if (!TypesToEmit.empty())
1552 WriteTypesBlock(Context);
1553 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1554
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001555 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001556 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001557
1558 // Write the type offsets array
1559 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1560 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1563 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1564 Record.clear();
1565 Record.push_back(pch::TYPE_OFFSET);
1566 Record.push_back(TypeOffsets.size());
1567 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
1568 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001569 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001570
1571 // Write the declaration offsets array
1572 Abbrev = new BitCodeAbbrev();
1573 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1576 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1577 Record.clear();
1578 Record.push_back(pch::DECL_OFFSET);
1579 Record.push_back(DeclOffsets.size());
1580 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
1581 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001582 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001583
1584 // Write the record of special types.
1585 Record.clear();
1586 AddTypeRef(Context.getBuiltinVaListType(), Record);
Douglas Gregor319ac892009-04-23 22:29:11 +00001587 AddTypeRef(Context.getObjCIdType(), Record);
1588 AddTypeRef(Context.getObjCSelType(), Record);
1589 AddTypeRef(Context.getObjCProtoType(), Record);
1590 AddTypeRef(Context.getObjCClassType(), Record);
1591 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1592 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
Douglas Gregorad1de002009-04-18 05:55:16 +00001593 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
1594
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001595 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001596 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001597 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001598
1599 // Write the record containing tentative definitions.
1600 if (!TentativeDefinitions.empty())
1601 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001602
1603 // Write the record containing locally-scoped external definitions.
1604 if (!LocallyScopedExternalDecls.empty())
1605 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
1606 LocallyScopedExternalDecls);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001607
1608 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001609 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001610 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001611 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001612 Record.push_back(NumLexicalDeclContexts);
1613 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001614 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001615 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001616}
1617
1618void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1619 Record.push_back(Loc.getRawEncoding());
1620}
1621
1622void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1623 Record.push_back(Value.getBitWidth());
1624 unsigned N = Value.getNumWords();
1625 const uint64_t* Words = Value.getRawData();
1626 for (unsigned I = 0; I != N; ++I)
1627 Record.push_back(Words[I]);
1628}
1629
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001630void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1631 Record.push_back(Value.isUnsigned());
1632 AddAPInt(Value, Record);
1633}
1634
Douglas Gregor17fc2232009-04-14 21:55:33 +00001635void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1636 AddAPInt(Value.bitcastToAPInt(), Record);
1637}
1638
Douglas Gregor2cf26342009-04-09 22:27:44 +00001639void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00001640 Record.push_back(getIdentifierRef(II));
1641}
1642
1643pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
1644 if (II == 0)
1645 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001646
1647 pch::IdentID &ID = IdentifierIDs[II];
1648 if (ID == 0)
1649 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001650 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001651}
1652
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001653void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
1654 if (SelRef.getAsOpaquePtr() == 0) {
1655 Record.push_back(0);
1656 return;
1657 }
1658
1659 pch::SelectorID &SID = SelectorIDs[SelRef];
1660 if (SID == 0) {
1661 SID = SelectorIDs.size();
1662 SelVector.push_back(SelRef);
1663 }
1664 Record.push_back(SID);
1665}
1666
Douglas Gregor2cf26342009-04-09 22:27:44 +00001667void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
1668 if (T.isNull()) {
1669 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
1670 return;
1671 }
1672
1673 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001674 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001675 switch (BT->getKind()) {
1676 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
1677 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
1678 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
1679 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
1680 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
1681 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
1682 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
1683 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
1684 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
1685 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
1686 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
1687 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
1688 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
1689 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
1690 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
1691 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
1692 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
1693 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
1694 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
1695 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
1696 }
1697
1698 Record.push_back((ID << 3) | T.getCVRQualifiers());
1699 return;
1700 }
1701
Douglas Gregor8038d512009-04-10 17:25:41 +00001702 pch::TypeID &ID = TypeIDs[T.getTypePtr()];
Douglas Gregor366809a2009-04-26 03:49:13 +00001703 if (ID == 0) {
1704 // We haven't seen this type before. Assign it a new ID and put it
1705 // into the queu of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001706 ID = NextTypeID++;
Douglas Gregor366809a2009-04-26 03:49:13 +00001707 TypesToEmit.push(T.getTypePtr());
1708 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001709
1710 // Encode the type qualifiers in the type reference.
1711 Record.push_back((ID << 3) | T.getCVRQualifiers());
1712}
1713
1714void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
1715 if (D == 0) {
1716 Record.push_back(0);
1717 return;
1718 }
1719
Douglas Gregor8038d512009-04-10 17:25:41 +00001720 pch::DeclID &ID = DeclIDs[D];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001721 if (ID == 0) {
1722 // We haven't seen this declaration before. Give it a new ID and
1723 // enqueue it in the list of declarations to emit.
1724 ID = DeclIDs.size();
1725 DeclsToEmit.push(const_cast<Decl *>(D));
1726 }
1727
1728 Record.push_back(ID);
1729}
1730
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001731pch::DeclID PCHWriter::getDeclID(const Decl *D) {
1732 if (D == 0)
1733 return 0;
1734
1735 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
1736 return DeclIDs[D];
1737}
1738
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00001740 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001741 Record.push_back(Name.getNameKind());
1742 switch (Name.getNameKind()) {
1743 case DeclarationName::Identifier:
1744 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
1745 break;
1746
1747 case DeclarationName::ObjCZeroArgSelector:
1748 case DeclarationName::ObjCOneArgSelector:
1749 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001750 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001751 break;
1752
1753 case DeclarationName::CXXConstructorName:
1754 case DeclarationName::CXXDestructorName:
1755 case DeclarationName::CXXConversionFunctionName:
1756 AddTypeRef(Name.getCXXNameType(), Record);
1757 break;
1758
1759 case DeclarationName::CXXOperatorName:
1760 Record.push_back(Name.getCXXOverloadedOperator());
1761 break;
1762
1763 case DeclarationName::CXXUsingDirective:
1764 // No extra data to emit
1765 break;
1766 }
1767}
Douglas Gregor0b748912009-04-14 21:18:50 +00001768