blob: 74bd9677abd8912d4dd4d618143e07d184693962 [file] [log] [blame]
Douglas Gregoref84c4b2009-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 Gregor162dd022009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Mike Stump11289f42009-09-09 15:08:12 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregoref84c4b2009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattnerbaa52f42009-04-10 18:00:12 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Basic/FileManager.h"
Douglas Gregore84a9da2009-04-20 20:36:09 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000031#include "clang/Basic/Version.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000032#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "llvm/Bitcode/BitstreamWriter.h"
35#include "llvm/Support/Compiler.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000036#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor45fe0362009-05-12 01:31:05 +000037#include "llvm/System/Path.h"
Chris Lattner225dd6c2009-04-11 18:40:46 +000038#include <cstdio>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// Type serialization
43//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000044
Douglas Gregoref84c4b2009-04-09 22:27:44 +000045namespace {
46 class VISIBILITY_HIDDEN PCHTypeWriter {
47 PCHWriter &Writer;
48 PCHWriter::RecordData &Record;
49
50 public:
51 /// \brief Type code that corresponds to the record generated.
52 pch::TypeCode Code;
53
Mike Stump11289f42009-09-09 15:08:12 +000054 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregorc5046832009-04-27 18:38:38 +000055 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +000056
57 void VisitArrayType(const ArrayType *T);
58 void VisitFunctionType(const FunctionType *T);
59 void VisitTagType(const TagType *T);
60
61#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
62#define ABSTRACT_TYPE(Class, Base)
63#define DEPENDENT_TYPE(Class, Base)
64#include "clang/AST/TypeNodes.def"
65 };
66}
67
Douglas Gregoref84c4b2009-04-09 22:27:44 +000068void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
69 assert(false && "Built-in types are never serialized");
70}
71
72void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
73 Record.push_back(T->getWidth());
74 Record.push_back(T->isSigned());
75 Code = pch::TYPE_FIXED_WIDTH_INT;
76}
77
78void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
79 Writer.AddTypeRef(T->getElementType(), Record);
80 Code = pch::TYPE_COMPLEX;
81}
82
83void PCHTypeWriter::VisitPointerType(const PointerType *T) {
84 Writer.AddTypeRef(T->getPointeeType(), Record);
85 Code = pch::TYPE_POINTER;
86}
87
88void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +000089 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +000090 Code = pch::TYPE_BLOCK_POINTER;
91}
92
93void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
94 Writer.AddTypeRef(T->getPointeeType(), Record);
95 Code = pch::TYPE_LVALUE_REFERENCE;
96}
97
98void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
99 Writer.AddTypeRef(T->getPointeeType(), Record);
100 Code = pch::TYPE_RVALUE_REFERENCE;
101}
102
103void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000104 Writer.AddTypeRef(T->getPointeeType(), Record);
105 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000106 Code = pch::TYPE_MEMBER_POINTER;
107}
108
109void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
110 Writer.AddTypeRef(T->getElementType(), Record);
111 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000112 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000113}
114
115void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
116 VisitArrayType(T);
117 Writer.AddAPInt(T->getSize(), Record);
118 Code = pch::TYPE_CONSTANT_ARRAY;
119}
120
121void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
122 VisitArrayType(T);
123 Code = pch::TYPE_INCOMPLETE_ARRAY;
124}
125
126void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
127 VisitArrayType(T);
Douglas Gregor04318252009-07-06 15:59:29 +0000128 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
129 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +0000130 Writer.AddStmt(T->getSizeExpr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131 Code = pch::TYPE_VARIABLE_ARRAY;
132}
133
134void PCHTypeWriter::VisitVectorType(const VectorType *T) {
135 Writer.AddTypeRef(T->getElementType(), Record);
136 Record.push_back(T->getNumElements());
137 Code = pch::TYPE_VECTOR;
138}
139
140void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
141 VisitVectorType(T);
142 Code = pch::TYPE_EXT_VECTOR;
143}
144
145void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
146 Writer.AddTypeRef(T->getResultType(), Record);
147}
148
149void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
150 VisitFunctionType(T);
151 Code = pch::TYPE_FUNCTION_NO_PROTO;
152}
153
154void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
155 VisitFunctionType(T);
156 Record.push_back(T->getNumArgs());
157 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
158 Writer.AddTypeRef(T->getArgType(I), Record);
159 Record.push_back(T->isVariadic());
160 Record.push_back(T->getTypeQuals());
Sebastian Redl5068f77ac2009-05-27 22:11:52 +0000161 Record.push_back(T->hasExceptionSpec());
162 Record.push_back(T->hasAnyExceptionSpec());
163 Record.push_back(T->getNumExceptions());
164 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
165 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166 Code = pch::TYPE_FUNCTION_PROTO;
167}
168
169void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
170 Writer.AddDeclRef(T->getDecl(), Record);
171 Code = pch::TYPE_TYPEDEF;
172}
173
174void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregor8f45df52009-04-16 22:23:12 +0000175 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000176 Code = pch::TYPE_TYPEOF_EXPR;
177}
178
179void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
180 Writer.AddTypeRef(T->getUnderlyingType(), Record);
181 Code = pch::TYPE_TYPEOF;
182}
183
Anders Carlsson81df7b82009-06-24 19:06:50 +0000184void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
185 Writer.AddStmt(T->getUnderlyingExpr());
186 Code = pch::TYPE_DECLTYPE;
187}
188
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189void PCHTypeWriter::VisitTagType(const TagType *T) {
190 Writer.AddDeclRef(T->getDecl(), Record);
Mike Stump11289f42009-09-09 15:08:12 +0000191 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000192 "Cannot serialize in the middle of a type definition");
193}
194
195void PCHTypeWriter::VisitRecordType(const RecordType *T) {
196 VisitTagType(T);
197 Code = pch::TYPE_RECORD;
198}
199
200void PCHTypeWriter::VisitEnumType(const EnumType *T) {
201 VisitTagType(T);
202 Code = pch::TYPE_ENUM;
203}
204
John McCallfcc33b02009-09-05 00:15:47 +0000205void PCHTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
206 Writer.AddTypeRef(T->getUnderlyingType(), Record);
207 Record.push_back(T->getTagKind());
208 Code = pch::TYPE_ELABORATED;
209}
210
Mike Stump11289f42009-09-09 15:08:12 +0000211void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000212PCHTypeWriter::VisitTemplateSpecializationType(
213 const TemplateSpecializationType *T) {
Douglas Gregore95304a2009-04-15 18:43:11 +0000214 // FIXME: Serialize this type (C++ only)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000215 assert(false && "Cannot serialize template specialization types");
216}
217
218void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregore95304a2009-04-15 18:43:11 +0000219 // FIXME: Serialize this type (C++ only)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000220 assert(false && "Cannot serialize qualified name types");
221}
222
223void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
224 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000225 Record.push_back(T->getNumProtocols());
Steve Naroff4fc95aa2009-05-27 16:21:00 +0000226 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
227 E = T->qual_end(); I != E; ++I)
228 Writer.AddDeclRef(*I, Record);
Steve Naroffc277ad12009-07-18 15:33:26 +0000229 Code = pch::TYPE_OBJC_INTERFACE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000230}
231
Steve Narofffb4330f2009-06-17 22:40:22 +0000232void
233PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000234 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000235 Record.push_back(T->getNumProtocols());
Steve Narofffb4330f2009-06-17 22:40:22 +0000236 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff4fc95aa2009-05-27 16:21:00 +0000237 E = T->qual_end(); I != E; ++I)
238 Writer.AddDeclRef(*I, Record);
Steve Narofffb4330f2009-06-17 22:40:22 +0000239 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000240}
241
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +0000242void PCHTypeWriter::VisitObjCProtocolListType(const ObjCProtocolListType *T) {
243 Writer.AddTypeRef(T->getBaseType(), Record);
244 Record.push_back(T->getNumProtocols());
245 for (ObjCProtocolListType::qual_iterator I = T->qual_begin(),
246 E = T->qual_end(); I != E; ++I)
247 Writer.AddDeclRef(*I, Record);
248 Code = pch::TYPE_OBJC_PROTOCOL_LIST;
249}
250
John McCall8f115c62009-10-16 21:56:05 +0000251namespace {
252
253class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
254 PCHWriter &Writer;
255 PCHWriter::RecordData &Record;
256
257public:
258 TypeLocWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
259 : Writer(Writer), Record(Record) { }
260
261#define ABSTRACT_TYPELOC(CLASS)
262#define TYPELOC(CLASS, PARENT) \
263 void Visit##CLASS(CLASS TyLoc);
264#include "clang/AST/TypeLocNodes.def"
265
266 void VisitTypeLoc(TypeLoc TyLoc) {
267 assert(0 && "A type loc wrapper was not handled!");
268 }
269};
270
271}
272
273void TypeLocWriter::VisitQualifiedLoc(QualifiedLoc TyLoc) {
274 // nothing to do here
275}
276void TypeLocWriter::VisitDefaultTypeSpecLoc(DefaultTypeSpecLoc TyLoc) {
277 Writer.AddSourceLocation(TyLoc.getStartLoc(), Record);
278}
279void TypeLocWriter::VisitTypedefLoc(TypedefLoc TyLoc) {
280 Writer.AddSourceLocation(TyLoc.getNameLoc(), Record);
281}
282void TypeLocWriter::VisitObjCInterfaceLoc(ObjCInterfaceLoc TyLoc) {
283 Writer.AddSourceLocation(TyLoc.getNameLoc(), Record);
284}
285void TypeLocWriter::VisitObjCProtocolListLoc(ObjCProtocolListLoc TyLoc) {
286 Writer.AddSourceLocation(TyLoc.getLAngleLoc(), Record);
287 Writer.AddSourceLocation(TyLoc.getRAngleLoc(), Record);
288 for (unsigned i = 0, e = TyLoc.getNumProtocols(); i != e; ++i)
289 Writer.AddSourceLocation(TyLoc.getProtocolLoc(i), Record);
290}
291void TypeLocWriter::VisitPointerLoc(PointerLoc TyLoc) {
292 Writer.AddSourceLocation(TyLoc.getStarLoc(), Record);
293}
294void TypeLocWriter::VisitBlockPointerLoc(BlockPointerLoc TyLoc) {
295 Writer.AddSourceLocation(TyLoc.getCaretLoc(), Record);
296}
297void TypeLocWriter::VisitMemberPointerLoc(MemberPointerLoc TyLoc) {
298 Writer.AddSourceLocation(TyLoc.getStarLoc(), Record);
299}
300void TypeLocWriter::VisitReferenceLoc(ReferenceLoc TyLoc) {
301 Writer.AddSourceLocation(TyLoc.getAmpLoc(), Record);
302}
303void TypeLocWriter::VisitFunctionLoc(FunctionLoc TyLoc) {
304 Writer.AddSourceLocation(TyLoc.getLParenLoc(), Record);
305 Writer.AddSourceLocation(TyLoc.getRParenLoc(), Record);
306 for (unsigned i = 0, e = TyLoc.getNumArgs(); i != e; ++i)
307 Writer.AddDeclRef(TyLoc.getArg(i), Record);
308}
309void TypeLocWriter::VisitArrayLoc(ArrayLoc TyLoc) {
310 Writer.AddSourceLocation(TyLoc.getLBracketLoc(), Record);
311 Writer.AddSourceLocation(TyLoc.getRBracketLoc(), Record);
312 Record.push_back(TyLoc.getSizeExpr() ? 1 : 0);
313 if (TyLoc.getSizeExpr())
314 Writer.AddStmt(TyLoc.getSizeExpr());
315}
316
Chris Lattner19cea4e2009-04-22 05:57:30 +0000317//===----------------------------------------------------------------------===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000318// PCHWriter Implementation
319//===----------------------------------------------------------------------===//
320
Chris Lattner28fa4e62009-04-26 22:26:21 +0000321static void EmitBlockID(unsigned ID, const char *Name,
322 llvm::BitstreamWriter &Stream,
323 PCHWriter::RecordData &Record) {
324 Record.clear();
325 Record.push_back(ID);
326 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
327
328 // Emit the block name if present.
329 if (Name == 0 || Name[0] == 0) return;
330 Record.clear();
331 while (*Name)
332 Record.push_back(*Name++);
333 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
334}
335
336static void EmitRecordID(unsigned ID, const char *Name,
337 llvm::BitstreamWriter &Stream,
338 PCHWriter::RecordData &Record) {
339 Record.clear();
340 Record.push_back(ID);
341 while (*Name)
342 Record.push_back(*Name++);
343 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000344}
345
346static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
347 PCHWriter::RecordData &Record) {
348#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
349 RECORD(STMT_STOP);
350 RECORD(STMT_NULL_PTR);
351 RECORD(STMT_NULL);
352 RECORD(STMT_COMPOUND);
353 RECORD(STMT_CASE);
354 RECORD(STMT_DEFAULT);
355 RECORD(STMT_LABEL);
356 RECORD(STMT_IF);
357 RECORD(STMT_SWITCH);
358 RECORD(STMT_WHILE);
359 RECORD(STMT_DO);
360 RECORD(STMT_FOR);
361 RECORD(STMT_GOTO);
362 RECORD(STMT_INDIRECT_GOTO);
363 RECORD(STMT_CONTINUE);
364 RECORD(STMT_BREAK);
365 RECORD(STMT_RETURN);
366 RECORD(STMT_DECL);
367 RECORD(STMT_ASM);
368 RECORD(EXPR_PREDEFINED);
369 RECORD(EXPR_DECL_REF);
370 RECORD(EXPR_INTEGER_LITERAL);
371 RECORD(EXPR_FLOATING_LITERAL);
372 RECORD(EXPR_IMAGINARY_LITERAL);
373 RECORD(EXPR_STRING_LITERAL);
374 RECORD(EXPR_CHARACTER_LITERAL);
375 RECORD(EXPR_PAREN);
376 RECORD(EXPR_UNARY_OPERATOR);
377 RECORD(EXPR_SIZEOF_ALIGN_OF);
378 RECORD(EXPR_ARRAY_SUBSCRIPT);
379 RECORD(EXPR_CALL);
380 RECORD(EXPR_MEMBER);
381 RECORD(EXPR_BINARY_OPERATOR);
382 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
383 RECORD(EXPR_CONDITIONAL_OPERATOR);
384 RECORD(EXPR_IMPLICIT_CAST);
385 RECORD(EXPR_CSTYLE_CAST);
386 RECORD(EXPR_COMPOUND_LITERAL);
387 RECORD(EXPR_EXT_VECTOR_ELEMENT);
388 RECORD(EXPR_INIT_LIST);
389 RECORD(EXPR_DESIGNATED_INIT);
390 RECORD(EXPR_IMPLICIT_VALUE_INIT);
391 RECORD(EXPR_VA_ARG);
392 RECORD(EXPR_ADDR_LABEL);
393 RECORD(EXPR_STMT);
394 RECORD(EXPR_TYPES_COMPATIBLE);
395 RECORD(EXPR_CHOOSE);
396 RECORD(EXPR_GNU_NULL);
397 RECORD(EXPR_SHUFFLE_VECTOR);
398 RECORD(EXPR_BLOCK);
399 RECORD(EXPR_BLOCK_DECL_REF);
400 RECORD(EXPR_OBJC_STRING_LITERAL);
401 RECORD(EXPR_OBJC_ENCODE);
402 RECORD(EXPR_OBJC_SELECTOR_EXPR);
403 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
404 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
405 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
406 RECORD(EXPR_OBJC_KVC_REF_EXPR);
407 RECORD(EXPR_OBJC_MESSAGE_EXPR);
408 RECORD(EXPR_OBJC_SUPER_EXPR);
409 RECORD(STMT_OBJC_FOR_COLLECTION);
410 RECORD(STMT_OBJC_CATCH);
411 RECORD(STMT_OBJC_FINALLY);
412 RECORD(STMT_OBJC_AT_TRY);
413 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
414 RECORD(STMT_OBJC_AT_THROW);
415#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000416}
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner28fa4e62009-04-26 22:26:21 +0000418void PCHWriter::WriteBlockInfoBlock() {
419 RecordData Record;
420 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner64031982009-04-27 00:40:25 +0000422#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattner28fa4e62009-04-26 22:26:21 +0000423#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner28fa4e62009-04-26 22:26:21 +0000425 // PCH Top-Level Block.
Chris Lattner64031982009-04-27 00:40:25 +0000426 BLOCK(PCH_BLOCK);
Zhongxing Xub027cdf2009-06-03 09:23:28 +0000427 RECORD(ORIGINAL_FILE_NAME);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000428 RECORD(TYPE_OFFSET);
429 RECORD(DECL_OFFSET);
430 RECORD(LANGUAGE_OPTIONS);
Douglas Gregor7b71e632009-04-27 22:23:34 +0000431 RECORD(METADATA);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000432 RECORD(IDENTIFIER_OFFSET);
433 RECORD(IDENTIFIER_TABLE);
434 RECORD(EXTERNAL_DEFINITIONS);
435 RECORD(SPECIAL_TYPES);
436 RECORD(STATISTICS);
437 RECORD(TENTATIVE_DEFINITIONS);
438 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
439 RECORD(SELECTOR_OFFSETS);
440 RECORD(METHOD_POOL);
441 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000442 RECORD(SOURCE_LOCATION_OFFSETS);
443 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregorc5046832009-04-27 18:38:38 +0000444 RECORD(STAT_CACHE);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000445 RECORD(EXT_VECTOR_DECLS);
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000446 RECORD(COMMENT_RANGES);
Douglas Gregord54f3a12009-10-05 21:07:28 +0000447 RECORD(SVN_BRANCH_REVISION);
448
Chris Lattner28fa4e62009-04-26 22:26:21 +0000449 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000450 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000451 RECORD(SM_SLOC_FILE_ENTRY);
452 RECORD(SM_SLOC_BUFFER_ENTRY);
453 RECORD(SM_SLOC_BUFFER_BLOB);
454 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
455 RECORD(SM_LINE_TABLE);
456 RECORD(SM_HEADER_FILE_INFO);
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattner28fa4e62009-04-26 22:26:21 +0000458 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000459 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000460 RECORD(PP_MACRO_OBJECT_LIKE);
461 RECORD(PP_MACRO_FUNCTION_LIKE);
462 RECORD(PP_TOKEN);
463
464 // Types block.
Chris Lattner64031982009-04-27 00:40:25 +0000465 BLOCK(TYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000466 RECORD(TYPE_EXT_QUAL);
467 RECORD(TYPE_FIXED_WIDTH_INT);
468 RECORD(TYPE_COMPLEX);
469 RECORD(TYPE_POINTER);
470 RECORD(TYPE_BLOCK_POINTER);
471 RECORD(TYPE_LVALUE_REFERENCE);
472 RECORD(TYPE_RVALUE_REFERENCE);
473 RECORD(TYPE_MEMBER_POINTER);
474 RECORD(TYPE_CONSTANT_ARRAY);
475 RECORD(TYPE_INCOMPLETE_ARRAY);
476 RECORD(TYPE_VARIABLE_ARRAY);
477 RECORD(TYPE_VECTOR);
478 RECORD(TYPE_EXT_VECTOR);
479 RECORD(TYPE_FUNCTION_PROTO);
480 RECORD(TYPE_FUNCTION_NO_PROTO);
481 RECORD(TYPE_TYPEDEF);
482 RECORD(TYPE_TYPEOF_EXPR);
483 RECORD(TYPE_TYPEOF);
484 RECORD(TYPE_RECORD);
485 RECORD(TYPE_ENUM);
486 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000487 RECORD(TYPE_OBJC_OBJECT_POINTER);
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +0000488 RECORD(TYPE_OBJC_PROTOCOL_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000489 // Statements and Exprs can occur in the Types block.
490 AddStmtsExprs(Stream, Record);
491
Chris Lattner28fa4e62009-04-26 22:26:21 +0000492 // Decls block.
Chris Lattner64031982009-04-27 00:40:25 +0000493 BLOCK(DECLS_BLOCK);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000494 RECORD(DECL_ATTR);
495 RECORD(DECL_TRANSLATION_UNIT);
496 RECORD(DECL_TYPEDEF);
497 RECORD(DECL_ENUM);
498 RECORD(DECL_RECORD);
499 RECORD(DECL_ENUM_CONSTANT);
500 RECORD(DECL_FUNCTION);
501 RECORD(DECL_OBJC_METHOD);
502 RECORD(DECL_OBJC_INTERFACE);
503 RECORD(DECL_OBJC_PROTOCOL);
504 RECORD(DECL_OBJC_IVAR);
505 RECORD(DECL_OBJC_AT_DEFS_FIELD);
506 RECORD(DECL_OBJC_CLASS);
507 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
508 RECORD(DECL_OBJC_CATEGORY);
509 RECORD(DECL_OBJC_CATEGORY_IMPL);
510 RECORD(DECL_OBJC_IMPLEMENTATION);
511 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
512 RECORD(DECL_OBJC_PROPERTY);
513 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000514 RECORD(DECL_FIELD);
515 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000516 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000517 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000518 RECORD(DECL_ORIGINAL_PARM_VAR);
519 RECORD(DECL_FILE_SCOPE_ASM);
520 RECORD(DECL_BLOCK);
521 RECORD(DECL_CONTEXT_LEXICAL);
522 RECORD(DECL_CONTEXT_VISIBLE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000523 // Statements and Exprs can occur in the Decls block.
524 AddStmtsExprs(Stream, Record);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000525#undef RECORD
526#undef BLOCK
527 Stream.ExitBlock();
528}
529
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000530/// \brief Adjusts the given filename to only write out the portion of the
531/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000532///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000533/// \param Filename the file name to adjust.
534///
535/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
536/// the returned filename will be adjusted by this system root.
537///
538/// \returns either the original filename (if it needs no adjustment) or the
539/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000540static const char *
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000541adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
542 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000543
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000544 if (!isysroot)
545 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000547 // Verify that the filename and the system root have the same prefix.
548 unsigned Pos = 0;
549 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
550 if (Filename[Pos] != isysroot[Pos])
551 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000553 // We hit the end of the filename before we hit the end of the system root.
554 if (!Filename[Pos])
555 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000556
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000557 // If the file name has a '/' at the current position, skip over the '/'.
558 // We distinguish sysroot-based includes from absolute includes by the
559 // absence of '/' at the beginning of sysroot-based includes.
560 if (Filename[Pos] == '/')
561 ++Pos;
Mike Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000563 return Filename + Pos;
564}
Chris Lattner28fa4e62009-04-26 22:26:21 +0000565
Douglas Gregor7b71e632009-04-27 22:23:34 +0000566/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000567void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregorbfbde532009-04-10 21:16:55 +0000568 using namespace llvm;
Douglas Gregor45fe0362009-05-12 01:31:05 +0000569
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000570 // Metadata
571 const TargetInfo &Target = Context.Target;
572 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
573 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
574 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
575 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
576 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
577 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
578 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
579 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
580 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Mike Stump11289f42009-09-09 15:08:12 +0000581
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000582 RecordData Record;
583 Record.push_back(pch::METADATA);
584 Record.push_back(pch::VERSION_MAJOR);
585 Record.push_back(pch::VERSION_MINOR);
586 Record.push_back(CLANG_VERSION_MAJOR);
587 Record.push_back(CLANG_VERSION_MINOR);
588 Record.push_back(isysroot != 0);
Daniel Dunbar40165182009-08-24 09:10:05 +0000589 const std::string &TripleStr = Target.getTriple().getTriple();
Daniel Dunbar8100d012009-08-24 09:31:37 +0000590 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
Mike Stump11289f42009-09-09 15:08:12 +0000591
Douglas Gregor45fe0362009-05-12 01:31:05 +0000592 // Original file name
593 SourceManager &SM = Context.getSourceManager();
594 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
595 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
596 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
597 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
598 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
599
600 llvm::sys::Path MainFilePath(MainFile->getName());
601 std::string MainFileName;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregor45fe0362009-05-12 01:31:05 +0000603 if (!MainFilePath.isAbsolute()) {
604 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattner3441b4f2009-08-23 22:45:33 +0000605 P.appendComponent(MainFilePath.str());
606 MainFileName = P.str();
Douglas Gregor45fe0362009-05-12 01:31:05 +0000607 } else {
Chris Lattner3441b4f2009-08-23 22:45:33 +0000608 MainFileName = MainFilePath.str();
Douglas Gregor45fe0362009-05-12 01:31:05 +0000609 }
610
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000611 const char *MainFileNameStr = MainFileName.c_str();
Mike Stump11289f42009-09-09 15:08:12 +0000612 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000613 isysroot);
Douglas Gregor45fe0362009-05-12 01:31:05 +0000614 RecordData Record;
615 Record.push_back(pch::ORIGINAL_FILE_NAME);
Daniel Dunbar8100d012009-08-24 09:31:37 +0000616 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregor45fe0362009-05-12 01:31:05 +0000617 }
Douglas Gregord54f3a12009-10-05 21:07:28 +0000618
619 // Subversion branch/version information.
620 BitCodeAbbrev *SvnAbbrev = new BitCodeAbbrev();
621 SvnAbbrev->Add(BitCodeAbbrevOp(pch::SVN_BRANCH_REVISION));
622 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // SVN revision
623 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
624 unsigned SvnAbbrevCode = Stream.EmitAbbrev(SvnAbbrev);
625 Record.clear();
626 Record.push_back(pch::SVN_BRANCH_REVISION);
627 Record.push_back(getClangSubversionRevision());
628 Stream.EmitRecordWithBlob(SvnAbbrevCode, Record, getClangSubversionPath());
Douglas Gregorbfbde532009-04-10 21:16:55 +0000629}
630
631/// \brief Write the LangOptions structure.
Douglas Gregor55abb232009-04-10 20:39:37 +0000632void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
633 RecordData Record;
634 Record.push_back(LangOpts.Trigraphs);
635 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
636 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
637 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
638 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
639 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
640 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
641 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
642 Record.push_back(LangOpts.C99); // C99 Support
643 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
644 Record.push_back(LangOpts.CPlusPlus); // C++ Support
645 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor55abb232009-04-10 20:39:37 +0000646 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregor55abb232009-04-10 20:39:37 +0000648 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
649 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
650 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
Mike Stump11289f42009-09-09 15:08:12 +0000651
Douglas Gregor55abb232009-04-10 20:39:37 +0000652 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor55abb232009-04-10 20:39:37 +0000653 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
654 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +0000655 Record.push_back(LangOpts.AltiVec);
Douglas Gregor55abb232009-04-10 20:39:37 +0000656 Record.push_back(LangOpts.Exceptions); // Support exception handling.
657
658 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
659 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
660 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
661
Chris Lattner258172e2009-04-27 07:35:58 +0000662 // Whether static initializers are protected by locks.
663 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +0000664 Record.push_back(LangOpts.POSIXThreads);
Douglas Gregor55abb232009-04-10 20:39:37 +0000665 Record.push_back(LangOpts.Blocks); // block extension to C
666 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
667 // they are unused.
668 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
669 // (modulo the platform support).
670
671 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
672 // signed integer arithmetic overflows.
673
674 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
675 // may be ripped out at any time.
676
677 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
Mike Stump11289f42009-09-09 15:08:12 +0000678 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
Douglas Gregor55abb232009-04-10 20:39:37 +0000679 // defined.
680 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
681 // opposed to __DYNAMIC__).
682 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
683
684 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
685 // used (instead of C99 semantics).
686 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlsson5879fbd2009-05-13 19:49:53 +0000687 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
688 // be enabled.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000689 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
690 // unsigned type
Douglas Gregor55abb232009-04-10 20:39:37 +0000691 Record.push_back(LangOpts.getGCMode());
692 Record.push_back(LangOpts.getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000693 Record.push_back(LangOpts.getStackProtectorMode());
Douglas Gregor55abb232009-04-10 20:39:37 +0000694 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +0000695 Record.push_back(LangOpts.OpenCL);
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000696 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregor8f45df52009-04-16 22:23:12 +0000697 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor55abb232009-04-10 20:39:37 +0000698}
699
Douglas Gregora7f71a92009-04-10 03:52:48 +0000700//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +0000701// stat cache Serialization
702//===----------------------------------------------------------------------===//
703
704namespace {
705// Trait used for the on-disk hash table of stat cache results.
706class VISIBILITY_HIDDEN PCHStatCacheTrait {
707public:
708 typedef const char * key_type;
709 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +0000710
Douglas Gregorc5046832009-04-27 18:38:38 +0000711 typedef std::pair<int, struct stat> data_type;
712 typedef const data_type& data_type_ref;
713
714 static unsigned ComputeHash(const char *path) {
715 return BernsteinHash(path);
716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
718 std::pair<unsigned,unsigned>
Douglas Gregorc5046832009-04-27 18:38:38 +0000719 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
720 data_type_ref Data) {
721 unsigned StrLen = strlen(path);
722 clang::io::Emit16(Out, StrLen);
723 unsigned DataLen = 1; // result value
724 if (Data.first == 0)
725 DataLen += 4 + 4 + 2 + 8 + 8;
726 clang::io::Emit8(Out, DataLen);
727 return std::make_pair(StrLen + 1, DataLen);
728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
Douglas Gregorc5046832009-04-27 18:38:38 +0000730 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
731 Out.write(path, KeyLen);
732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Douglas Gregorc5046832009-04-27 18:38:38 +0000734 void EmitData(llvm::raw_ostream& Out, key_type_ref,
735 data_type_ref Data, unsigned DataLen) {
736 using namespace clang::io;
737 uint64_t Start = Out.tell(); (void)Start;
Mike Stump11289f42009-09-09 15:08:12 +0000738
Douglas Gregorc5046832009-04-27 18:38:38 +0000739 // Result of stat()
740 Emit8(Out, Data.first? 1 : 0);
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregorc5046832009-04-27 18:38:38 +0000742 if (Data.first == 0) {
743 Emit32(Out, (uint32_t) Data.second.st_ino);
744 Emit32(Out, (uint32_t) Data.second.st_dev);
745 Emit16(Out, (uint16_t) Data.second.st_mode);
746 Emit64(Out, (uint64_t) Data.second.st_mtime);
747 Emit64(Out, (uint64_t) Data.second.st_size);
748 }
749
750 assert(Out.tell() - Start == DataLen && "Wrong data length");
751 }
752};
753} // end anonymous namespace
754
755/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000756void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
757 const char *isysroot) {
Douglas Gregorc5046832009-04-27 18:38:38 +0000758 // Build the on-disk hash table containing information about every
759 // stat() call.
760 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
761 unsigned NumStatEntries = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000762 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
Douglas Gregorc5046832009-04-27 18:38:38 +0000763 StatEnd = StatCalls.end();
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000764 Stat != StatEnd; ++Stat, ++NumStatEntries) {
765 const char *Filename = Stat->first();
766 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
767 Generator.insert(Filename, Stat->second);
768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregorc5046832009-04-27 18:38:38 +0000770 // Create the on-disk hash table in a buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000771 llvm::SmallString<4096> StatCacheData;
Douglas Gregorc5046832009-04-27 18:38:38 +0000772 uint32_t BucketOffset;
773 {
774 llvm::raw_svector_ostream Out(StatCacheData);
775 // Make sure that no bucket is at offset 0
776 clang::io::Emit32(Out, 0);
777 BucketOffset = Generator.Emit(Out);
778 }
779
780 // Create a blob abbreviation
781 using namespace llvm;
782 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
783 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
787 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
788
789 // Write the stat cache
790 RecordData Record;
791 Record.push_back(pch::STAT_CACHE);
792 Record.push_back(BucketOffset);
793 Record.push_back(NumStatEntries);
Daniel Dunbar8100d012009-08-24 09:31:37 +0000794 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
Douglas Gregorc5046832009-04-27 18:38:38 +0000795}
796
797//===----------------------------------------------------------------------===//
Douglas Gregora7f71a92009-04-10 03:52:48 +0000798// Source Manager Serialization
799//===----------------------------------------------------------------------===//
800
801/// \brief Create an abbreviation for the SLocEntry that refers to a
802/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +0000803static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000804 using namespace llvm;
805 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
806 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
807 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
808 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
810 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregora7f71a92009-04-10 03:52:48 +0000811 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregor8f45df52009-04-16 22:23:12 +0000812 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000813}
814
815/// \brief Create an abbreviation for the SLocEntry that refers to a
816/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +0000817static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000818 using namespace llvm;
819 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
820 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
822 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
823 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
824 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +0000826 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000827}
828
829/// \brief Create an abbreviation for the SLocEntry that refers to a
830/// buffer's blob.
Douglas Gregor8f45df52009-04-16 22:23:12 +0000831static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000832 using namespace llvm;
833 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
834 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +0000836 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000837}
838
839/// \brief Create an abbreviation for the SLocEntry that refers to an
840/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +0000841static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000842 using namespace llvm;
843 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
844 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
845 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
847 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
848 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +0000849 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +0000850 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000851}
852
853/// \brief Writes the block containing the serialized form of the
854/// source manager.
855///
856/// TODO: We should probably use an on-disk hash table (stored in a
857/// blob), indexed based on the file name, so that we only create
858/// entries for files that we actually need. In the common case (no
859/// errors), we probably won't have to create file entries for any of
860/// the files in the AST.
Douglas Gregoreda6a892009-04-26 00:07:37 +0000861void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000862 const Preprocessor &PP,
863 const char *isysroot) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000864 RecordData Record;
865
Chris Lattner0910e3b2009-04-10 17:16:57 +0000866 // Enter the source manager block.
Douglas Gregor8f45df52009-04-16 22:23:12 +0000867 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000868
869 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +0000870 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
871 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
872 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
873 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +0000874
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000875 // Write the line table.
876 if (SourceMgr.hasLineTable()) {
877 LineTableInfo &LineTable = SourceMgr.getLineTable();
878
879 // Emit the file names
880 Record.push_back(LineTable.getNumFilenames());
881 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
882 // Emit the file name
883 const char *Filename = LineTable.getFilename(I);
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000884 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000885 unsigned FilenameLen = Filename? strlen(Filename) : 0;
886 Record.push_back(FilenameLen);
887 if (FilenameLen)
888 Record.insert(Record.end(), Filename, Filename + FilenameLen);
889 }
Mike Stump11289f42009-09-09 15:08:12 +0000890
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000891 // Emit the line entries
892 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
893 L != LEnd; ++L) {
894 // Emit the file ID
895 Record.push_back(L->first);
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000897 // Emit the line entries
898 Record.push_back(L->second.size());
Mike Stump11289f42009-09-09 15:08:12 +0000899 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000900 LEEnd = L->second.end();
901 LE != LEEnd; ++LE) {
902 Record.push_back(LE->FileOffset);
903 Record.push_back(LE->LineNo);
904 Record.push_back(LE->FilenameID);
905 Record.push_back((unsigned)LE->FileKind);
906 Record.push_back(LE->IncludeOffset);
907 }
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000908 }
Zhongxing Xu5a187dd2009-05-22 08:38:27 +0000909 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000910 }
911
Douglas Gregor258ae542009-04-27 06:38:32 +0000912 // Write out entries for all of the header files we know about.
Mike Stump11289f42009-09-09 15:08:12 +0000913 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor258ae542009-04-27 06:38:32 +0000914 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000915 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
Douglas Gregoreda6a892009-04-26 00:07:37 +0000916 E = HS.header_file_end();
917 I != E; ++I) {
918 Record.push_back(I->isImport);
919 Record.push_back(I->DirInfo);
920 Record.push_back(I->NumIncludes);
Douglas Gregor258ae542009-04-27 06:38:32 +0000921 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000922 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
923 Record.clear();
924 }
925
Douglas Gregor258ae542009-04-27 06:38:32 +0000926 // Write out the source location entry table. We skip the first
927 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +0000928 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +0000929 RecordData PreloadSLocs;
930 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
Mike Stump11289f42009-09-09 15:08:12 +0000931 for (SourceManager::sloc_entry_iterator
Douglas Gregor258ae542009-04-27 06:38:32 +0000932 SLoc = SourceMgr.sloc_entry_begin() + 1,
933 SLocEnd = SourceMgr.sloc_entry_end();
934 SLoc != SLocEnd; ++SLoc) {
935 // Record the offset of this source-location entry.
936 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
937
938 // Figure out which record code to use.
939 unsigned Code;
940 if (SLoc->isFile()) {
941 if (SLoc->getFile().getContentCache()->Entry)
942 Code = pch::SM_SLOC_FILE_ENTRY;
943 else
944 Code = pch::SM_SLOC_BUFFER_ENTRY;
945 } else
946 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
947 Record.clear();
948 Record.push_back(Code);
949
950 Record.push_back(SLoc->getOffset());
951 if (SLoc->isFile()) {
952 const SrcMgr::FileInfo &File = SLoc->getFile();
953 Record.push_back(File.getIncludeLoc().getRawEncoding());
954 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
955 Record.push_back(File.hasLineDirectives());
956
957 const SrcMgr::ContentCache *Content = File.getContentCache();
958 if (Content->Entry) {
959 // The source location entry is a file. The blob associated
960 // with this entry is the file name.
Mike Stump11289f42009-09-09 15:08:12 +0000961
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000962 // Turn the file name into an absolute path, if it isn't already.
963 const char *Filename = Content->Entry->getName();
964 llvm::sys::Path FilePath(Filename, strlen(Filename));
965 std::string FilenameStr;
966 if (!FilePath.isAbsolute()) {
967 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattner3441b4f2009-08-23 22:45:33 +0000968 P.appendComponent(FilePath.str());
969 FilenameStr = P.str();
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000970 Filename = FilenameStr.c_str();
971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000973 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Daniel Dunbar8100d012009-08-24 09:31:37 +0000974 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
Douglas Gregor258ae542009-04-27 06:38:32 +0000975
976 // FIXME: For now, preload all file source locations, so that
977 // we get the appropriate File entries in the reader. This is
978 // a temporary measure.
979 PreloadSLocs.push_back(SLocEntryOffsets.size());
980 } else {
981 // The source location entry is a buffer. The blob associated
982 // with this entry contains the contents of the buffer.
983
984 // We add one to the size so that we capture the trailing NULL
985 // that is required by llvm::MemoryBuffer::getMemBuffer (on
986 // the reader side).
987 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
988 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbar8100d012009-08-24 09:31:37 +0000989 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
990 llvm::StringRef(Name, strlen(Name) + 1));
Douglas Gregor258ae542009-04-27 06:38:32 +0000991 Record.clear();
992 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
993 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Daniel Dunbar8100d012009-08-24 09:31:37 +0000994 llvm::StringRef(Buffer->getBufferStart(),
995 Buffer->getBufferSize() + 1));
Douglas Gregor258ae542009-04-27 06:38:32 +0000996
997 if (strcmp(Name, "<built-in>") == 0)
998 PreloadSLocs.push_back(SLocEntryOffsets.size());
999 }
1000 } else {
1001 // The source location entry is an instantiation.
1002 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1003 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1004 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1005 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1006
1007 // Compute the token length for this macro expansion.
1008 unsigned NextOffset = SourceMgr.getNextOffset();
1009 SourceManager::sloc_entry_iterator NextSLoc = SLoc;
1010 if (++NextSLoc != SLocEnd)
1011 NextOffset = NextSLoc->getOffset();
1012 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1013 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1014 }
1015 }
1016
Douglas Gregor8f45df52009-04-16 22:23:12 +00001017 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001018
1019 if (SLocEntryOffsets.empty())
1020 return;
1021
1022 // Write the source-location offsets table into the PCH block. This
1023 // table is used for lazily loading source-location information.
1024 using namespace llvm;
1025 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1026 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
1027 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1028 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1029 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1030 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump11289f42009-09-09 15:08:12 +00001031
Douglas Gregor258ae542009-04-27 06:38:32 +00001032 Record.clear();
1033 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
1034 Record.push_back(SLocEntryOffsets.size());
1035 Record.push_back(SourceMgr.getNextOffset());
1036 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
Mike Stump11289f42009-09-09 15:08:12 +00001037 (const char *)&SLocEntryOffsets.front(),
Chris Lattner12d61d32009-04-27 19:01:47 +00001038 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor258ae542009-04-27 06:38:32 +00001039
1040 // Write the source location entry preloads array, telling the PCH
1041 // reader which source locations entries it should load eagerly.
1042 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001043}
1044
Douglas Gregorc5046832009-04-27 18:38:38 +00001045//===----------------------------------------------------------------------===//
1046// Preprocessor Serialization
1047//===----------------------------------------------------------------------===//
1048
Chris Lattnereeffaef2009-04-10 17:15:23 +00001049/// \brief Writes the block containing the serialized form of the
1050/// preprocessor.
1051///
Chris Lattner2199f5b2009-04-10 18:08:30 +00001052void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001053 RecordData Record;
Chris Lattner0910e3b2009-04-10 17:16:57 +00001054
Chris Lattner0af3ba12009-04-13 01:29:17 +00001055 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1056 if (PP.getCounterValue() != 0) {
1057 Record.push_back(PP.getCounterValue());
Douglas Gregor8f45df52009-04-16 22:23:12 +00001058 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattner0af3ba12009-04-13 01:29:17 +00001059 Record.clear();
Douglas Gregoreda6a892009-04-26 00:07:37 +00001060 }
1061
1062 // Enter the preprocessor block.
1063 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregoreda6a892009-04-26 00:07:37 +00001065 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1066 // FIXME: use diagnostics subsystem for localization etc.
1067 if (PP.SawDateOrTime())
1068 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001070 // Loop over all the macro definitions that are live at the end of the file,
1071 // emitting each to the PP section.
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001072 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1073 I != E; ++I) {
Chris Lattner34321bc2009-04-10 21:41:48 +00001074 // FIXME: This emits macros in hash table order, we should do it in a stable
1075 // order so that output is reproducible.
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001076 MacroInfo *MI = I->second;
1077
1078 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1079 // been redefined by the header (in which case they are not isBuiltinMacro).
1080 if (MI->isBuiltinMacro())
1081 continue;
1082
Douglas Gregorc3366a52009-04-21 23:56:24 +00001083 // FIXME: Remove this identifier reference?
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001084 AddIdentifierRef(I->first, Record);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001085 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001086 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1087 Record.push_back(MI->isUsed());
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001089 unsigned Code;
1090 if (MI->isObjectLike()) {
1091 Code = pch::PP_MACRO_OBJECT_LIKE;
1092 } else {
1093 Code = pch::PP_MACRO_FUNCTION_LIKE;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001095 Record.push_back(MI->isC99Varargs());
1096 Record.push_back(MI->isGNUVarargs());
1097 Record.push_back(MI->getNumArgs());
1098 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1099 I != E; ++I)
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001100 AddIdentifierRef(*I, Record);
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001101 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00001102 Stream.EmitRecord(Code, Record);
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001103 Record.clear();
1104
Chris Lattner2199f5b2009-04-10 18:08:30 +00001105 // Emit the tokens array.
1106 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1107 // Note that we know that the preprocessor does not have any annotation
1108 // tokens in it because they are created by the parser, and thus can't be
1109 // in a macro definition.
1110 const Token &Tok = MI->getReplacementToken(TokNo);
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattner2199f5b2009-04-10 18:08:30 +00001112 Record.push_back(Tok.getLocation().getRawEncoding());
1113 Record.push_back(Tok.getLength());
1114
Chris Lattner2199f5b2009-04-10 18:08:30 +00001115 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1116 // it is needed.
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001117 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner2199f5b2009-04-10 18:08:30 +00001119 // FIXME: Should translate token kind to a stable encoding.
1120 Record.push_back(Tok.getKind());
1121 // FIXME: Should translate token flags to a stable encoding.
1122 Record.push_back(Tok.getFlags());
Mike Stump11289f42009-09-09 15:08:12 +00001123
Douglas Gregor8f45df52009-04-16 22:23:12 +00001124 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattner2199f5b2009-04-10 18:08:30 +00001125 Record.clear();
1126 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001127 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00001128 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00001129 Stream.ExitBlock();
Chris Lattnereeffaef2009-04-10 17:15:23 +00001130}
1131
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001132void PCHWriter::WriteComments(ASTContext &Context) {
1133 using namespace llvm;
Mike Stump11289f42009-09-09 15:08:12 +00001134
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001135 if (Context.Comments.empty())
1136 return;
Mike Stump11289f42009-09-09 15:08:12 +00001137
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001138 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1139 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1140 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1141 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
Mike Stump11289f42009-09-09 15:08:12 +00001142
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001143 RecordData Record;
1144 Record.push_back(pch::COMMENT_RANGES);
Mike Stump11289f42009-09-09 15:08:12 +00001145 Stream.EmitRecordWithBlob(CommentCode, Record,
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001146 (const char*)&Context.Comments[0],
1147 Context.Comments.size() * sizeof(SourceRange));
1148}
1149
Douglas Gregorc5046832009-04-27 18:38:38 +00001150//===----------------------------------------------------------------------===//
1151// Type Serialization
1152//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00001153
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001154/// \brief Write the representation of a type to the PCH stream.
John McCall8ccfcb52009-09-24 19:53:00 +00001155void PCHWriter::WriteType(QualType T) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001156 pch::TypeID &ID = TypeIDs[T];
Chris Lattner0910e3b2009-04-10 17:16:57 +00001157 if (ID == 0) // we haven't seen this type before.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001158 ID = NextTypeID++;
Mike Stump11289f42009-09-09 15:08:12 +00001159
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001160 // Record the offset for this type.
1161 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregor8f45df52009-04-16 22:23:12 +00001162 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001163 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1164 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregor8f45df52009-04-16 22:23:12 +00001165 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001166 }
1167
1168 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001170 // Emit the type's representation.
1171 PCHTypeWriter W(*this, Record);
John McCall8ccfcb52009-09-24 19:53:00 +00001172
1173 if (T.hasNonFastQualifiers()) {
1174 Qualifiers Qs = T.getQualifiers();
1175 AddTypeRef(T.getUnqualifiedType(), Record);
1176 Record.push_back(Qs.getAsOpaqueValue());
1177 W.Code = pch::TYPE_EXT_QUAL;
1178 } else {
1179 switch (T->getTypeClass()) {
1180 // For all of the concrete, non-dependent types, call the
1181 // appropriate visitor function.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001182#define TYPE(Class, Base) \
John McCall8ccfcb52009-09-24 19:53:00 +00001183 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001184#define ABSTRACT_TYPE(Class, Base)
1185#define DEPENDENT_TYPE(Class, Base)
1186#include "clang/AST/TypeNodes.def"
1187
John McCall8ccfcb52009-09-24 19:53:00 +00001188 // For all of the dependent type nodes (which only occur in C++
1189 // templates), produce an error.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001190#define TYPE(Class, Base)
1191#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1192#include "clang/AST/TypeNodes.def"
John McCall8ccfcb52009-09-24 19:53:00 +00001193 assert(false && "Cannot serialize dependent type nodes");
1194 break;
1195 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001196 }
1197
1198 // Emit the serialized record.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001199 Stream.EmitRecord(W.Code, Record);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001200
1201 // Flush any expressions that were written as part of this type.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001202 FlushStmts();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001203}
1204
1205/// \brief Write a block containing all of the types.
1206void PCHWriter::WriteTypesBlock(ASTContext &Context) {
Chris Lattner0910e3b2009-04-10 17:16:57 +00001207 // Enter the types block.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001208 Stream.EnterSubblock(pch::TYPES_BLOCK_ID, 2);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001209
Douglas Gregor1970d882009-04-26 03:49:13 +00001210 // Emit all of the types that need to be emitted (so far).
1211 while (!TypesToEmit.empty()) {
John McCall8ccfcb52009-09-24 19:53:00 +00001212 QualType T = TypesToEmit.front();
Douglas Gregor1970d882009-04-26 03:49:13 +00001213 TypesToEmit.pop();
Douglas Gregor1970d882009-04-26 03:49:13 +00001214 WriteType(T);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001215 }
1216
1217 // Exit the types block
Douglas Gregor8f45df52009-04-16 22:23:12 +00001218 Stream.ExitBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001219}
1220
Douglas Gregorc5046832009-04-27 18:38:38 +00001221//===----------------------------------------------------------------------===//
1222// Declaration Serialization
1223//===----------------------------------------------------------------------===//
1224
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001225/// \brief Write the block containing all of the declaration IDs
1226/// lexically declared within the given DeclContext.
1227///
1228/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1229/// bistream, or 0 if no block was written.
Mike Stump11289f42009-09-09 15:08:12 +00001230uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001231 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001232 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001233 return 0;
1234
Douglas Gregor8f45df52009-04-16 22:23:12 +00001235 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001236 RecordData Record;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001237 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1238 D != DEnd; ++D)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001239 AddDeclRef(*D, Record);
1240
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001241 ++NumLexicalDeclContexts;
Douglas Gregor8f45df52009-04-16 22:23:12 +00001242 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001243 return Offset;
1244}
1245
1246/// \brief Write the block containing all of the declaration IDs
1247/// visible from the given DeclContext.
1248///
1249/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1250/// bistream, or 0 if no block was written.
1251uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1252 DeclContext *DC) {
1253 if (DC->getPrimaryContext() != DC)
1254 return 0;
1255
Douglas Gregorb475a5c2009-04-21 22:32:33 +00001256 // Since there is no name lookup into functions or methods, and we
1257 // perform name lookup for the translation unit via the
1258 // IdentifierInfo chains, don't bother to build a
1259 // visible-declarations table for these entities.
1260 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor13d190f2009-04-18 15:49:20 +00001261 return 0;
1262
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001263 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001264 DC->lookup(DeclarationName());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001265
1266 // Serialize the contents of the mapping used for lookup. Note that,
1267 // although we have two very different code paths, the serialized
1268 // representation is the same for both cases: a declaration name,
1269 // followed by a size, followed by references to the visible
1270 // declarations that have that name.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001271 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001272 RecordData Record;
1273 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor183671e2009-04-13 21:20:57 +00001274 if (!Map)
1275 return 0;
1276
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001277 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1278 D != DEnd; ++D) {
1279 AddDeclarationName(D->first, Record);
1280 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1281 Record.push_back(Result.second - Result.first);
Mike Stump11289f42009-09-09 15:08:12 +00001282 for (; Result.first != Result.second; ++Result.first)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001283 AddDeclRef(*Result.first, Record);
1284 }
1285
1286 if (Record.size() == 0)
1287 return 0;
1288
Douglas Gregor8f45df52009-04-16 22:23:12 +00001289 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001290 ++NumVisibleDeclContexts;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001291 return Offset;
1292}
1293
Douglas Gregorc5046832009-04-27 18:38:38 +00001294//===----------------------------------------------------------------------===//
1295// Global Method Pool and Selector Serialization
1296//===----------------------------------------------------------------------===//
1297
Douglas Gregore84a9da2009-04-20 20:36:09 +00001298namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00001299// Trait used for the on-disk hash table used in the method pool.
1300class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1301 PCHWriter &Writer;
1302
1303public:
1304 typedef Selector key_type;
1305 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Douglas Gregorc78d3462009-04-24 21:10:55 +00001307 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1308 typedef const data_type& data_type_ref;
1309
1310 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregorc78d3462009-04-24 21:10:55 +00001312 static unsigned ComputeHash(Selector Sel) {
1313 unsigned N = Sel.getNumArgs();
1314 if (N == 0)
1315 ++N;
1316 unsigned R = 5381;
1317 for (unsigned I = 0; I != N; ++I)
1318 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1319 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
1320 return R;
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
1323 std::pair<unsigned,unsigned>
Douglas Gregorc78d3462009-04-24 21:10:55 +00001324 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1325 data_type_ref Methods) {
1326 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1327 clang::io::Emit16(Out, KeyLen);
1328 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
Mike Stump11289f42009-09-09 15:08:12 +00001329 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001330 Method = Method->Next)
1331 if (Method->Method)
1332 DataLen += 4;
Mike Stump11289f42009-09-09 15:08:12 +00001333 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001334 Method = Method->Next)
1335 if (Method->Method)
1336 DataLen += 4;
1337 clang::io::Emit16(Out, DataLen);
1338 return std::make_pair(KeyLen, DataLen);
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregor95c13f52009-04-25 17:48:32 +00001341 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump11289f42009-09-09 15:08:12 +00001342 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00001343 assert((Start >> 32) == 0 && "Selector key offset too large");
1344 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00001345 unsigned N = Sel.getNumArgs();
1346 clang::io::Emit16(Out, N);
1347 if (N == 0)
1348 N = 1;
1349 for (unsigned I = 0; I != N; ++I)
Mike Stump11289f42009-09-09 15:08:12 +00001350 clang::io::Emit32(Out,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001351 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Douglas Gregorc78d3462009-04-24 21:10:55 +00001354 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00001355 data_type_ref Methods, unsigned DataLen) {
1356 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001357 unsigned NumInstanceMethods = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001358 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001359 Method = Method->Next)
1360 if (Method->Method)
1361 ++NumInstanceMethods;
1362
1363 unsigned NumFactoryMethods = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001365 Method = Method->Next)
1366 if (Method->Method)
1367 ++NumFactoryMethods;
1368
1369 clang::io::Emit16(Out, NumInstanceMethods);
1370 clang::io::Emit16(Out, NumFactoryMethods);
Mike Stump11289f42009-09-09 15:08:12 +00001371 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001372 Method = Method->Next)
1373 if (Method->Method)
1374 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Mike Stump11289f42009-09-09 15:08:12 +00001375 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001376 Method = Method->Next)
1377 if (Method->Method)
1378 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00001379
1380 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00001381 }
1382};
1383} // end anonymous namespace
1384
1385/// \brief Write the method pool into the PCH file.
1386///
1387/// The method pool contains both instance and factory methods, stored
1388/// in an on-disk hash table indexed by the selector.
1389void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1390 using namespace llvm;
1391
1392 // Create and write out the blob that contains the instance and
1393 // factor method pools.
1394 bool Empty = true;
1395 {
1396 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregorc78d3462009-04-24 21:10:55 +00001398 // Create the on-disk hash table representation. Start by
1399 // iterating through the instance method pool.
1400 PCHMethodPoolTrait::key_type Key;
Douglas Gregor95c13f52009-04-25 17:48:32 +00001401 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001402 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump11289f42009-09-09 15:08:12 +00001403 Instance = SemaRef.InstanceMethodPool.begin(),
Douglas Gregorc78d3462009-04-24 21:10:55 +00001404 InstanceEnd = SemaRef.InstanceMethodPool.end();
1405 Instance != InstanceEnd; ++Instance) {
1406 // Check whether there is a factory method with the same
1407 // selector.
1408 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1409 = SemaRef.FactoryMethodPool.find(Instance->first);
1410
1411 if (Factory == SemaRef.FactoryMethodPool.end())
1412 Generator.insert(Instance->first,
Mike Stump11289f42009-09-09 15:08:12 +00001413 std::make_pair(Instance->second,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001414 ObjCMethodList()));
1415 else
1416 Generator.insert(Instance->first,
1417 std::make_pair(Instance->second, Factory->second));
1418
Douglas Gregor95c13f52009-04-25 17:48:32 +00001419 ++NumSelectorsInMethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001420 Empty = false;
1421 }
1422
1423 // Now iterate through the factory method pool, to pick up any
1424 // selectors that weren't already in the instance method pool.
1425 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump11289f42009-09-09 15:08:12 +00001426 Factory = SemaRef.FactoryMethodPool.begin(),
Douglas Gregorc78d3462009-04-24 21:10:55 +00001427 FactoryEnd = SemaRef.FactoryMethodPool.end();
1428 Factory != FactoryEnd; ++Factory) {
1429 // Check whether there is an instance method with the same
1430 // selector. If so, there is no work to do here.
1431 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1432 = SemaRef.InstanceMethodPool.find(Factory->first);
1433
Douglas Gregor95c13f52009-04-25 17:48:32 +00001434 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00001435 Generator.insert(Factory->first,
1436 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001437 ++NumSelectorsInMethodPool;
1438 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00001439
1440 Empty = false;
1441 }
1442
Douglas Gregor95c13f52009-04-25 17:48:32 +00001443 if (Empty && SelectorOffsets.empty())
Douglas Gregorc78d3462009-04-24 21:10:55 +00001444 return;
1445
1446 // Create the on-disk hash table in a buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001447 llvm::SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001448 uint32_t BucketOffset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00001449 SelectorOffsets.resize(SelVector.size());
Douglas Gregorc78d3462009-04-24 21:10:55 +00001450 {
1451 PCHMethodPoolTrait Trait(*this);
1452 llvm::raw_svector_ostream Out(MethodPool);
1453 // Make sure that no bucket is at offset 0
Douglas Gregor4647cfa2009-04-24 21:49:02 +00001454 clang::io::Emit32(Out, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00001455 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor95c13f52009-04-25 17:48:32 +00001456
1457 // For every selector that we have seen but which was not
1458 // written into the hash table, write the selector itself and
1459 // record it's offset.
1460 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1461 if (SelectorOffsets[I] == 0)
1462 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00001463 }
1464
1465 // Create a blob abbreviation
1466 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1467 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00001470 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1471 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1472
Douglas Gregor95c13f52009-04-25 17:48:32 +00001473 // Write the method pool
Douglas Gregorc78d3462009-04-24 21:10:55 +00001474 RecordData Record;
1475 Record.push_back(pch::METHOD_POOL);
1476 Record.push_back(BucketOffset);
Douglas Gregor95c13f52009-04-25 17:48:32 +00001477 Record.push_back(NumSelectorsInMethodPool);
Daniel Dunbar8100d012009-08-24 09:31:37 +00001478 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor95c13f52009-04-25 17:48:32 +00001479
1480 // Create a blob abbreviation for the selector table offsets.
1481 Abbrev = new BitCodeAbbrev();
1482 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1485 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1486
1487 // Write the selector offsets table.
1488 Record.clear();
1489 Record.push_back(pch::SELECTOR_OFFSETS);
1490 Record.push_back(SelectorOffsets.size());
1491 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1492 (const char *)&SelectorOffsets.front(),
1493 SelectorOffsets.size() * 4);
Douglas Gregorc78d3462009-04-24 21:10:55 +00001494 }
1495}
1496
Douglas Gregorc5046832009-04-27 18:38:38 +00001497//===----------------------------------------------------------------------===//
1498// Identifier Table Serialization
1499//===----------------------------------------------------------------------===//
1500
Douglas Gregorc78d3462009-04-24 21:10:55 +00001501namespace {
Douglas Gregore84a9da2009-04-20 20:36:09 +00001502class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1503 PCHWriter &Writer;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001504 Preprocessor &PP;
Douglas Gregore84a9da2009-04-20 20:36:09 +00001505
Douglas Gregor1d583f22009-04-28 21:18:29 +00001506 /// \brief Determines whether this is an "interesting" identifier
1507 /// that needs a full IdentifierInfo structure written into the hash
1508 /// table.
1509 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1510 return II->isPoisoned() ||
1511 II->isExtensionToken() ||
1512 II->hasMacroDefinition() ||
1513 II->getObjCOrBuiltinID() ||
1514 II->getFETokenInfo<void>();
1515 }
1516
Douglas Gregore84a9da2009-04-20 20:36:09 +00001517public:
1518 typedef const IdentifierInfo* key_type;
1519 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregore84a9da2009-04-20 20:36:09 +00001521 typedef pch::IdentID data_type;
1522 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00001523
1524 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
Douglas Gregorc3366a52009-04-21 23:56:24 +00001525 : Writer(Writer), PP(PP) { }
Douglas Gregore84a9da2009-04-20 20:36:09 +00001526
1527 static unsigned ComputeHash(const IdentifierInfo* II) {
1528 return clang::BernsteinHash(II->getName());
1529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
1531 std::pair<unsigned,unsigned>
1532 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00001533 pch::IdentID ID) {
1534 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00001535 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1536 if (isInterestingIdentifier(II)) {
Douglas Gregorb9256522009-04-28 21:32:13 +00001537 DataLen += 2; // 2 bytes for builtin ID, flags
Mike Stump11289f42009-09-09 15:08:12 +00001538 if (II->hasMacroDefinition() &&
Douglas Gregor1d583f22009-04-28 21:18:29 +00001539 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregorb9256522009-04-28 21:32:13 +00001540 DataLen += 4;
Douglas Gregor1d583f22009-04-28 21:18:29 +00001541 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1542 DEnd = IdentifierResolver::end();
1543 D != DEnd; ++D)
1544 DataLen += sizeof(pch::DeclID);
1545 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001546 clang::io::Emit16(Out, DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00001547 // We emit the key length after the data length so that every
1548 // string is preceded by a 16-bit length. This matches the PTH
1549 // format for storing identifiers.
Douglas Gregor5287b4e2009-04-25 21:04:17 +00001550 clang::io::Emit16(Out, KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00001551 return std::make_pair(KeyLen, DataLen);
1552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
1554 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00001555 unsigned KeyLen) {
1556 // Record the location of the key data. This is used when generating
1557 // the mapping from persistent IDs to strings.
1558 Writer.SetIdentifierOffset(II, Out.tell());
1559 Out.write(II->getName(), KeyLen);
1560 }
Mike Stump11289f42009-09-09 15:08:12 +00001561
1562 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00001563 pch::IdentID ID, unsigned) {
Douglas Gregor1d583f22009-04-28 21:18:29 +00001564 if (!isInterestingIdentifier(II)) {
1565 clang::io::Emit32(Out, ID << 1);
1566 return;
1567 }
Douglas Gregorb9256522009-04-28 21:32:13 +00001568
Douglas Gregor1d583f22009-04-28 21:18:29 +00001569 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregore84a9da2009-04-20 20:36:09 +00001570 uint32_t Bits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001571 bool hasMacroDefinition =
1572 II->hasMacroDefinition() &&
Douglas Gregorc3366a52009-04-21 23:56:24 +00001573 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregorb9256522009-04-28 21:32:13 +00001574 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor4621c6a2009-04-22 18:49:13 +00001575 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregore84a9da2009-04-20 20:36:09 +00001576 Bits = (Bits << 1) | II->isExtensionToken();
1577 Bits = (Bits << 1) | II->isPoisoned();
1578 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregorb9256522009-04-28 21:32:13 +00001579 clang::io::Emit16(Out, Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00001580
Douglas Gregorc3366a52009-04-21 23:56:24 +00001581 if (hasMacroDefinition)
Douglas Gregorb9256522009-04-28 21:32:13 +00001582 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregorc3366a52009-04-21 23:56:24 +00001583
Douglas Gregora868bbd2009-04-21 22:25:48 +00001584 // Emit the declaration IDs in reverse order, because the
1585 // IdentifierResolver provides the declarations as they would be
1586 // visible (e.g., the function "stat" would come before the struct
1587 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1588 // adds declarations to the end of the list (so we need to see the
1589 // struct "status" before the function "status").
Mike Stump11289f42009-09-09 15:08:12 +00001590 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
Douglas Gregora868bbd2009-04-21 22:25:48 +00001591 IdentifierResolver::end());
1592 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1593 DEnd = Decls.rend();
Douglas Gregore84a9da2009-04-20 20:36:09 +00001594 D != DEnd; ++D)
Douglas Gregora868bbd2009-04-21 22:25:48 +00001595 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregore84a9da2009-04-20 20:36:09 +00001596 }
1597};
1598} // end anonymous namespace
1599
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001600/// \brief Write the identifier table into the PCH file.
1601///
1602/// The identifier table consists of a blob containing string data
1603/// (the actual identifiers themselves) and a separate "offsets" index
1604/// that maps identifier IDs to locations within the blob.
Douglas Gregorc3366a52009-04-21 23:56:24 +00001605void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001606 using namespace llvm;
1607
1608 // Create and write out the blob that contains the identifier
1609 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001610 {
Douglas Gregore84a9da2009-04-20 20:36:09 +00001611 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
Mike Stump11289f42009-09-09 15:08:12 +00001612
Douglas Gregore6648fb2009-04-28 20:33:11 +00001613 // Look for any identifiers that were named while processing the
1614 // headers, but are otherwise not needed. We add these to the hash
1615 // table to enable checking of the predefines buffer in the case
1616 // where the user adds new macro definitions when building the PCH
1617 // file.
1618 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1619 IDEnd = PP.getIdentifierTable().end();
1620 ID != IDEnd; ++ID)
1621 getIdentifierRef(ID->second);
1622
Douglas Gregore84a9da2009-04-20 20:36:09 +00001623 // Create the on-disk hash table representation.
Douglas Gregore6648fb2009-04-28 20:33:11 +00001624 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001625 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1626 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1627 ID != IDEnd; ++ID) {
1628 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregorab4df582009-04-28 20:01:51 +00001629 Generator.insert(ID->first, ID->second);
Douglas Gregore84a9da2009-04-20 20:36:09 +00001630 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001631
Douglas Gregore84a9da2009-04-20 20:36:09 +00001632 // Create the on-disk hash table in a buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001633 llvm::SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00001634 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00001635 {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001636 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregore84a9da2009-04-20 20:36:09 +00001637 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00001638 // Make sure that no bucket is at offset 0
Douglas Gregor4647cfa2009-04-24 21:49:02 +00001639 clang::io::Emit32(Out, 0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00001640 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001641 }
1642
1643 // Create a blob abbreviation
1644 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1645 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00001646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00001647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00001648 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001649
1650 // Write the identifier table
1651 RecordData Record;
1652 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregora868bbd2009-04-21 22:25:48 +00001653 Record.push_back(BucketOffset);
Daniel Dunbar8100d012009-08-24 09:31:37 +00001654 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001655 }
1656
1657 // Write the offsets table for identifier IDs.
Douglas Gregor0e149972009-04-25 19:10:14 +00001658 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1659 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1660 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1661 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1662 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1663
1664 RecordData Record;
1665 Record.push_back(pch::IDENTIFIER_OFFSET);
1666 Record.push_back(IdentifierOffsets.size());
1667 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1668 (const char *)&IdentifierOffsets.front(),
1669 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001670}
1671
Douglas Gregorc5046832009-04-27 18:38:38 +00001672//===----------------------------------------------------------------------===//
1673// General Serialization Routines
1674//===----------------------------------------------------------------------===//
1675
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001676/// \brief Write a record containing the given attributes.
1677void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1678 RecordData Record;
1679 for (; Attr; Attr = Attr->getNext()) {
1680 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1681 Record.push_back(Attr->isInherited());
1682 switch (Attr->getKind()) {
1683 case Attr::Alias:
1684 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1685 break;
1686
1687 case Attr::Aligned:
1688 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1689 break;
1690
1691 case Attr::AlwaysInline:
1692 break;
Mike Stump11289f42009-09-09 15:08:12 +00001693
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001694 case Attr::AnalyzerNoReturn:
1695 break;
1696
1697 case Attr::Annotate:
1698 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1699 break;
1700
1701 case Attr::AsmLabel:
1702 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1703 break;
1704
1705 case Attr::Blocks:
1706 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1707 break;
1708
1709 case Attr::Cleanup:
1710 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1711 break;
1712
1713 case Attr::Const:
1714 break;
1715
1716 case Attr::Constructor:
1717 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1718 break;
1719
1720 case Attr::DLLExport:
1721 case Attr::DLLImport:
1722 case Attr::Deprecated:
1723 break;
1724
1725 case Attr::Destructor:
1726 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1727 break;
1728
1729 case Attr::FastCall:
1730 break;
1731
1732 case Attr::Format: {
1733 const FormatAttr *Format = cast<FormatAttr>(Attr);
1734 AddString(Format->getType(), Record);
1735 Record.push_back(Format->getFormatIdx());
1736 Record.push_back(Format->getFirstArg());
1737 break;
1738 }
1739
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00001740 case Attr::FormatArg: {
1741 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1742 Record.push_back(Format->getFormatIdx());
1743 break;
1744 }
1745
Fariborz Jahanian027b8862009-05-13 18:09:35 +00001746 case Attr::Sentinel : {
1747 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1748 Record.push_back(Sentinel->getSentinel());
1749 Record.push_back(Sentinel->getNullPos());
1750 break;
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Chris Lattnerddf6ca02009-04-20 19:12:28 +00001753 case Attr::GNUInline:
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001754 case Attr::IBOutletKind:
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001755 case Attr::Malloc:
Mike Stump3722f582009-08-26 22:31:08 +00001756 case Attr::NoDebug:
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001757 case Attr::NoReturn:
1758 case Attr::NoThrow:
Mike Stump3722f582009-08-26 22:31:08 +00001759 case Attr::NoInline:
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001760 break;
1761
1762 case Attr::NonNull: {
1763 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1764 Record.push_back(NonNull->size());
1765 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1766 break;
1767 }
1768
1769 case Attr::ObjCException:
1770 case Attr::ObjCNSObject:
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00001771 case Attr::CFReturnsRetained:
1772 case Attr::NSReturnsRetained:
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001773 case Attr::Overloadable:
1774 break;
1775
Anders Carlsson68e0b682009-08-08 18:23:56 +00001776 case Attr::PragmaPack:
1777 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001778 break;
1779
Anders Carlsson68e0b682009-08-08 18:23:56 +00001780 case Attr::Packed:
1781 break;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001783 case Attr::Pure:
1784 break;
1785
1786 case Attr::Regparm:
1787 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1788 break;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Nate Begemanf2758702009-06-26 06:32:41 +00001790 case Attr::ReqdWorkGroupSize:
1791 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1792 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1793 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1794 break;
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001795
1796 case Attr::Section:
1797 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1798 break;
1799
1800 case Attr::StdCall:
1801 case Attr::TransparentUnion:
1802 case Attr::Unavailable:
1803 case Attr::Unused:
1804 case Attr::Used:
1805 break;
1806
1807 case Attr::Visibility:
1808 // FIXME: stable encoding
Mike Stump11289f42009-09-09 15:08:12 +00001809 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001810 break;
1811
1812 case Attr::WarnUnusedResult:
1813 case Attr::Weak:
1814 case Attr::WeakImport:
1815 break;
1816 }
1817 }
1818
Douglas Gregor8f45df52009-04-16 22:23:12 +00001819 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00001820}
1821
1822void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1823 Record.push_back(Str.size());
1824 Record.insert(Record.end(), Str.begin(), Str.end());
1825}
1826
Douglas Gregore84a9da2009-04-20 20:36:09 +00001827/// \brief Note that the identifier II occurs at the given offset
1828/// within the identifier table.
1829void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor0e149972009-04-25 19:10:14 +00001830 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00001831}
1832
Douglas Gregor95c13f52009-04-25 17:48:32 +00001833/// \brief Note that the selector Sel occurs at the given offset
1834/// within the method pool/selector table.
1835void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1836 unsigned ID = SelectorIDs[Sel];
1837 assert(ID && "Unknown selector");
1838 SelectorOffsets[ID - 1] = Offset;
1839}
1840
Mike Stump11289f42009-09-09 15:08:12 +00001841PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1842 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001843 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1844 NumVisibleDeclContexts(0) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001845
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001846void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1847 const char *isysroot) {
Douglas Gregor745ed142009-04-25 18:35:21 +00001848 using namespace llvm;
1849
Douglas Gregor162dd022009-04-20 15:53:59 +00001850 ASTContext &Context = SemaRef.Context;
1851 Preprocessor &PP = SemaRef.PP;
1852
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001853 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001854 Stream.Emit((unsigned)'C', 8);
1855 Stream.Emit((unsigned)'P', 8);
1856 Stream.Emit((unsigned)'C', 8);
1857 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattner28fa4e62009-04-26 22:26:21 +00001859 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001860
1861 // The translation unit is the first declaration we'll emit.
1862 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1863 DeclsToEmit.push(Context.getTranslationUnitDecl());
1864
Douglas Gregor4621c6a2009-04-22 18:49:13 +00001865 // Make sure that we emit IdentifierInfos (and any attached
1866 // declarations) for builtins.
1867 {
1868 IdentifierTable &Table = PP.getIdentifierTable();
1869 llvm::SmallVector<const char *, 32> BuiltinNames;
1870 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1871 Context.getLangOptions().NoBuiltin);
1872 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1873 getIdentifierRef(&Table.get(BuiltinNames[I]));
1874 }
1875
Chris Lattner0c797362009-09-08 18:19:27 +00001876 // Build a record containing all of the tentative definitions in this file, in
1877 // TentativeDefinitionList order. Generally, this record will be empty for
1878 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00001879 RecordData TentativeDefinitions;
Chris Lattner0c797362009-09-08 18:19:27 +00001880 for (unsigned i = 0, e = SemaRef.TentativeDefinitionList.size(); i != e; ++i){
1881 VarDecl *VD =
1882 SemaRef.TentativeDefinitions.lookup(SemaRef.TentativeDefinitionList[i]);
1883 if (VD) AddDeclRef(VD, TentativeDefinitions);
1884 }
Douglas Gregord4df8652009-04-22 22:02:47 +00001885
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001886 // Build a record containing all of the locally-scoped external
1887 // declarations in this header file. Generally, this record will be
1888 // empty.
1889 RecordData LocallyScopedExternalDecls;
Chris Lattner0c797362009-09-08 18:19:27 +00001890 // FIXME: This is filling in the PCH file in densemap order which is
1891 // nondeterminstic!
Mike Stump11289f42009-09-09 15:08:12 +00001892 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001893 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1894 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1895 TD != TDEnd; ++TD)
1896 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1897
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001898 // Build a record containing all of the ext_vector declarations.
1899 RecordData ExtVectorDecls;
1900 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1901 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1902
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001903 // Write the remaining PCH contents.
Douglas Gregor652d82a2009-04-18 05:55:16 +00001904 RecordData Record;
Douglas Gregor745ed142009-04-25 18:35:21 +00001905 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001906 WriteMetadata(Context, isysroot);
Douglas Gregor55abb232009-04-10 20:39:37 +00001907 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001908 if (StatCalls && !isysroot)
1909 WriteStatCache(*StatCalls, isysroot);
1910 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Chris Lattnereeffaef2009-04-10 17:15:23 +00001911 WritePreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +00001912 WriteComments(Context);
Steve Naroffc277ad12009-07-18 15:33:26 +00001913 // Write the record of special types.
1914 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001915
Steve Naroffc277ad12009-07-18 15:33:26 +00001916 AddTypeRef(Context.getBuiltinVaListType(), Record);
1917 AddTypeRef(Context.getObjCIdType(), Record);
1918 AddTypeRef(Context.getObjCSelType(), Record);
1919 AddTypeRef(Context.getObjCProtoType(), Record);
1920 AddTypeRef(Context.getObjCClassType(), Record);
1921 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1922 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1923 AddTypeRef(Context.getFILEType(), Record);
Mike Stumpa4de80b2009-07-28 02:25:19 +00001924 AddTypeRef(Context.getjmp_bufType(), Record);
1925 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001926 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1927 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc277ad12009-07-18 15:33:26 +00001928 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregor1970d882009-04-26 03:49:13 +00001930 // Keep writing types and declarations until all types and
1931 // declarations have been written.
1932 do {
1933 if (!DeclsToEmit.empty())
1934 WriteDeclsBlock(Context);
1935 if (!TypesToEmit.empty())
1936 WriteTypesBlock(Context);
1937 } while (!(DeclsToEmit.empty() && TypesToEmit.empty()));
1938
Douglas Gregorc78d3462009-04-24 21:10:55 +00001939 WriteMethodPool(SemaRef);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001940 WriteIdentifierTable(PP);
Douglas Gregor745ed142009-04-25 18:35:21 +00001941
1942 // Write the type offsets array
1943 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1944 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1945 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1946 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1947 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1948 Record.clear();
1949 Record.push_back(pch::TYPE_OFFSET);
1950 Record.push_back(TypeOffsets.size());
1951 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
Mike Stump11289f42009-09-09 15:08:12 +00001952 (const char *)&TypeOffsets.front(),
Chris Lattnereeb05692009-04-27 18:24:17 +00001953 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregor745ed142009-04-25 18:35:21 +00001955 // Write the declaration offsets array
1956 Abbrev = new BitCodeAbbrev();
1957 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1958 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1959 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1960 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1961 Record.clear();
1962 Record.push_back(pch::DECL_OFFSET);
1963 Record.push_back(DeclOffsets.size());
1964 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
Mike Stump11289f42009-09-09 15:08:12 +00001965 (const char *)&DeclOffsets.front(),
Chris Lattnereeb05692009-04-27 18:24:17 +00001966 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregor652d82a2009-04-18 05:55:16 +00001967
Douglas Gregord4df8652009-04-22 22:02:47 +00001968 // Write the record containing external, unnamed definitions.
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001969 if (!ExternalDefinitions.empty())
Douglas Gregor8f45df52009-04-16 22:23:12 +00001970 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregord4df8652009-04-22 22:02:47 +00001971
1972 // Write the record containing tentative definitions.
1973 if (!TentativeDefinitions.empty())
1974 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001975
1976 // Write the record containing locally-scoped external definitions.
1977 if (!LocallyScopedExternalDecls.empty())
Mike Stump11289f42009-09-09 15:08:12 +00001978 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001979 LocallyScopedExternalDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001980
1981 // Write the record containing ext_vector type names.
1982 if (!ExtVectorDecls.empty())
1983 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00001984
Douglas Gregor08f01292009-04-17 22:13:46 +00001985 // Some simple statistics
Douglas Gregor652d82a2009-04-18 05:55:16 +00001986 Record.clear();
Douglas Gregor08f01292009-04-17 22:13:46 +00001987 Record.push_back(NumStatements);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001988 Record.push_back(NumMacros);
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001989 Record.push_back(NumLexicalDeclContexts);
1990 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor08f01292009-04-17 22:13:46 +00001991 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00001992 Stream.ExitBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001993}
1994
1995void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1996 Record.push_back(Loc.getRawEncoding());
1997}
1998
1999void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
2000 Record.push_back(Value.getBitWidth());
2001 unsigned N = Value.getNumWords();
2002 const uint64_t* Words = Value.getRawData();
2003 for (unsigned I = 0; I != N; ++I)
2004 Record.push_back(Words[I]);
2005}
2006
Douglas Gregor1daeb692009-04-13 18:14:40 +00002007void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
2008 Record.push_back(Value.isUnsigned());
2009 AddAPInt(Value, Record);
2010}
2011
Douglas Gregore0a3a512009-04-14 21:55:33 +00002012void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
2013 AddAPInt(Value.bitcastToAPInt(), Record);
2014}
2015
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002016void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00002017 Record.push_back(getIdentifierRef(II));
2018}
2019
2020pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
2021 if (II == 0)
2022 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002023
2024 pch::IdentID &ID = IdentifierIDs[II];
2025 if (ID == 0)
2026 ID = IdentifierIDs.size();
Douglas Gregor4621c6a2009-04-22 18:49:13 +00002027 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002028}
2029
Steve Naroff2ddea052009-04-23 10:39:46 +00002030void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
2031 if (SelRef.getAsOpaquePtr() == 0) {
2032 Record.push_back(0);
2033 return;
2034 }
2035
2036 pch::SelectorID &SID = SelectorIDs[SelRef];
2037 if (SID == 0) {
2038 SID = SelectorIDs.size();
2039 SelVector.push_back(SelRef);
2040 }
2041 Record.push_back(SID);
2042}
2043
John McCall8f115c62009-10-16 21:56:05 +00002044void PCHWriter::AddDeclaratorInfo(DeclaratorInfo *DInfo, RecordData &Record) {
2045 if (DInfo == 0) {
2046 AddTypeRef(QualType(), Record);
2047 return;
2048 }
2049
2050 AddTypeRef(DInfo->getTypeLoc().getSourceType(), Record);
2051 TypeLocWriter TLW(*this, Record);
2052 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2053 TLW.Visit(TL);
2054}
2055
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002056void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
2057 if (T.isNull()) {
2058 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
2059 return;
2060 }
2061
John McCall8ccfcb52009-09-24 19:53:00 +00002062 unsigned FastQuals = T.getFastQualifiers();
2063 T.removeFastQualifiers();
2064
2065 if (T.hasNonFastQualifiers()) {
2066 pch::TypeID &ID = TypeIDs[T];
2067 if (ID == 0) {
2068 // We haven't seen these qualifiers applied to this type before.
2069 // Assign it a new ID. This is the only time we enqueue a
2070 // qualified type, and it has no CV qualifiers.
2071 ID = NextTypeID++;
2072 TypesToEmit.push(T);
2073 }
2074
2075 // Encode the type qualifiers in the type reference.
2076 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2077 return;
2078 }
2079
2080 assert(!T.hasQualifiers());
2081
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002082 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002083 pch::TypeID ID = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002084 switch (BT->getKind()) {
2085 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2086 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2087 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2088 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2089 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2090 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2091 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2092 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002093 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002094 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2095 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2096 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2097 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2098 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2099 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2100 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002101 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002102 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2103 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2104 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002105 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002106 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2107 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002108 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2109 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002110 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2111 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlsson082acde2009-06-26 18:41:36 +00002112 case BuiltinType::UndeducedAuto:
2113 assert(0 && "Should not see undeduced auto here");
2114 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002115 }
2116
John McCall8ccfcb52009-09-24 19:53:00 +00002117 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002118 return;
2119 }
2120
John McCall8ccfcb52009-09-24 19:53:00 +00002121 pch::TypeID &ID = TypeIDs[T];
Douglas Gregor1970d882009-04-26 03:49:13 +00002122 if (ID == 0) {
2123 // We haven't seen this type before. Assign it a new ID and put it
John McCall8ccfcb52009-09-24 19:53:00 +00002124 // into the queue of types to emit.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002125 ID = NextTypeID++;
John McCall8ccfcb52009-09-24 19:53:00 +00002126 TypesToEmit.push(T);
Douglas Gregor1970d882009-04-26 03:49:13 +00002127 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002128
2129 // Encode the type qualifiers in the type reference.
John McCall8ccfcb52009-09-24 19:53:00 +00002130 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002131}
2132
2133void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2134 if (D == 0) {
2135 Record.push_back(0);
2136 return;
2137 }
2138
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002139 pch::DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00002140 if (ID == 0) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002141 // We haven't seen this declaration before. Give it a new ID and
2142 // enqueue it in the list of declarations to emit.
2143 ID = DeclIDs.size();
2144 DeclsToEmit.push(const_cast<Decl *>(D));
2145 }
2146
2147 Record.push_back(ID);
2148}
2149
Douglas Gregore84a9da2009-04-20 20:36:09 +00002150pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2151 if (D == 0)
2152 return 0;
2153
2154 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2155 return DeclIDs[D];
2156}
2157
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002158void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00002159 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002160 Record.push_back(Name.getNameKind());
2161 switch (Name.getNameKind()) {
2162 case DeclarationName::Identifier:
2163 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2164 break;
2165
2166 case DeclarationName::ObjCZeroArgSelector:
2167 case DeclarationName::ObjCOneArgSelector:
2168 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00002169 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002170 break;
2171
2172 case DeclarationName::CXXConstructorName:
2173 case DeclarationName::CXXDestructorName:
2174 case DeclarationName::CXXConversionFunctionName:
2175 AddTypeRef(Name.getCXXNameType(), Record);
2176 break;
2177
2178 case DeclarationName::CXXOperatorName:
2179 Record.push_back(Name.getCXXOverloadedOperator());
2180 break;
2181
2182 case DeclarationName::CXXUsingDirective:
2183 // No extra data to emit
2184 break;
2185 }
2186}
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002187