blob: 40c9e1f085c397b7ed52f823be6ab0f2415cfff2 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHWriter.h - Precompiled Headers Writer ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHWriter class, which writes a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/PCHWriter.h"
Douglas Gregore7785042009-04-20 15:53:59 +000015#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "../Sema/IdentifierResolver.h" // FIXME: move header
Douglas Gregor2cf26342009-04-09 22:27:44 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner7c5d24e2009-04-10 18:00:12 +000023#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Basic/FileManager.h"
Douglas Gregor3251ceb2009-04-20 20:36:09 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregorab41e632009-04-27 22:23:34 +000031#include "clang/Basic/Version.h"
Douglas Gregor17fc2232009-04-14 21:55:33 +000032#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamWriter.h"
36#include "llvm/Support/Compiler.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000037#include "llvm/Support/MemoryBuffer.h"
Douglas Gregorb64c1932009-05-12 01:31:05 +000038#include "llvm/System/Path.h"
Chris Lattner3c304bd2009-04-11 18:40:46 +000039#include <cstdio>
Douglas Gregor2cf26342009-04-09 22:27:44 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// Type serialization
44//===----------------------------------------------------------------------===//
Chris Lattner12b1c762009-04-27 06:16:06 +000045
Douglas Gregor2cf26342009-04-09 22:27:44 +000046namespace {
47 class VISIBILITY_HIDDEN PCHTypeWriter {
48 PCHWriter &Writer;
49 PCHWriter::RecordData &Record;
50
51 public:
52 /// \brief Type code that corresponds to the record generated.
53 pch::TypeCode Code;
54
Mike Stump1eb44332009-09-09 15:08:12 +000055 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
Douglas Gregor4fed3f42009-04-27 18:38:38 +000056 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +000057
58 void VisitArrayType(const ArrayType *T);
59 void VisitFunctionType(const FunctionType *T);
60 void VisitTagType(const TagType *T);
61
62#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
63#define ABSTRACT_TYPE(Class, Base)
64#define DEPENDENT_TYPE(Class, Base)
65#include "clang/AST/TypeNodes.def"
66 };
67}
68
Douglas Gregor2cf26342009-04-09 22:27:44 +000069void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
70 assert(false && "Built-in types are never serialized");
71}
72
73void PCHTypeWriter::VisitFixedWidthIntType(const FixedWidthIntType *T) {
74 Record.push_back(T->getWidth());
75 Record.push_back(T->isSigned());
76 Code = pch::TYPE_FIXED_WIDTH_INT;
77}
78
79void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
80 Writer.AddTypeRef(T->getElementType(), Record);
81 Code = pch::TYPE_COMPLEX;
82}
83
84void PCHTypeWriter::VisitPointerType(const PointerType *T) {
85 Writer.AddTypeRef(T->getPointeeType(), Record);
86 Code = pch::TYPE_POINTER;
87}
88
89void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +000090 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +000091 Code = pch::TYPE_BLOCK_POINTER;
92}
93
94void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
95 Writer.AddTypeRef(T->getPointeeType(), Record);
96 Code = pch::TYPE_LVALUE_REFERENCE;
97}
98
99void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
100 Writer.AddTypeRef(T->getPointeeType(), Record);
101 Code = pch::TYPE_RVALUE_REFERENCE;
102}
103
104void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000105 Writer.AddTypeRef(T->getPointeeType(), Record);
106 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000107 Code = pch::TYPE_MEMBER_POINTER;
108}
109
110void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
111 Writer.AddTypeRef(T->getElementType(), Record);
112 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall0953e762009-09-24 19:53:00 +0000113 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregor2cf26342009-04-09 22:27:44 +0000114}
115
116void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
117 VisitArrayType(T);
118 Writer.AddAPInt(T->getSize(), Record);
119 Code = pch::TYPE_CONSTANT_ARRAY;
120}
121
122void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
123 VisitArrayType(T);
124 Code = pch::TYPE_INCOMPLETE_ARRAY;
125}
126
127void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
128 VisitArrayType(T);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000129 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
130 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000131 Writer.AddStmt(T->getSizeExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000132 Code = pch::TYPE_VARIABLE_ARRAY;
133}
134
135void PCHTypeWriter::VisitVectorType(const VectorType *T) {
136 Writer.AddTypeRef(T->getElementType(), Record);
137 Record.push_back(T->getNumElements());
138 Code = pch::TYPE_VECTOR;
139}
140
141void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
142 VisitVectorType(T);
143 Code = pch::TYPE_EXT_VECTOR;
144}
145
146void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
147 Writer.AddTypeRef(T->getResultType(), Record);
148}
149
150void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
151 VisitFunctionType(T);
152 Code = pch::TYPE_FUNCTION_NO_PROTO;
153}
154
155void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
156 VisitFunctionType(T);
157 Record.push_back(T->getNumArgs());
158 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
159 Writer.AddTypeRef(T->getArgType(I), Record);
160 Record.push_back(T->isVariadic());
161 Record.push_back(T->getTypeQuals());
Sebastian Redl465226e2009-05-27 22:11:52 +0000162 Record.push_back(T->hasExceptionSpec());
163 Record.push_back(T->hasAnyExceptionSpec());
164 Record.push_back(T->getNumExceptions());
165 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
166 Writer.AddTypeRef(T->getExceptionType(I), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000167 Code = pch::TYPE_FUNCTION_PROTO;
168}
169
170void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
171 Writer.AddDeclRef(T->getDecl(), Record);
172 Code = pch::TYPE_TYPEDEF;
173}
174
175void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregorc9490c02009-04-16 22:23:12 +0000176 Writer.AddStmt(T->getUnderlyingExpr());
Douglas Gregor2cf26342009-04-09 22:27:44 +0000177 Code = pch::TYPE_TYPEOF_EXPR;
178}
179
180void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
181 Writer.AddTypeRef(T->getUnderlyingType(), Record);
182 Code = pch::TYPE_TYPEOF;
183}
184
Anders Carlsson395b4752009-06-24 19:06:50 +0000185void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
186 Writer.AddStmt(T->getUnderlyingExpr());
187 Code = pch::TYPE_DECLTYPE;
188}
189
Douglas Gregor2cf26342009-04-09 22:27:44 +0000190void PCHTypeWriter::VisitTagType(const TagType *T) {
191 Writer.AddDeclRef(T->getDecl(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +0000192 assert(!T->isBeingDefined() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +0000193 "Cannot serialize in the middle of a type definition");
194}
195
196void PCHTypeWriter::VisitRecordType(const RecordType *T) {
197 VisitTagType(T);
198 Code = pch::TYPE_RECORD;
199}
200
201void PCHTypeWriter::VisitEnumType(const EnumType *T) {
202 VisitTagType(T);
203 Code = pch::TYPE_ENUM;
204}
205
John McCall7da24312009-09-05 00:15:47 +0000206void PCHTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
207 Writer.AddTypeRef(T->getUnderlyingType(), Record);
208 Record.push_back(T->getTagKind());
209 Code = pch::TYPE_ELABORATED;
210}
211
Mike Stump1eb44332009-09-09 15:08:12 +0000212void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000213PCHTypeWriter::VisitTemplateSpecializationType(
214 const TemplateSpecializationType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000215 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000216 assert(false && "Cannot serialize template specialization types");
217}
218
219void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
Douglas Gregor6a2bfb22009-04-15 18:43:11 +0000220 // FIXME: Serialize this type (C++ only)
Douglas Gregor2cf26342009-04-09 22:27:44 +0000221 assert(false && "Cannot serialize qualified name types");
222}
223
224void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
225 Writer.AddDeclRef(T->getDecl(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000226 Record.push_back(T->getNumProtocols());
Steve Naroff446ee4e2009-05-27 16:21:00 +0000227 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
228 E = T->qual_end(); I != E; ++I)
229 Writer.AddDeclRef(*I, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +0000230 Code = pch::TYPE_OBJC_INTERFACE;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000231}
232
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000233void
234PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump1eb44332009-09-09 15:08:12 +0000235 Writer.AddTypeRef(T->getPointeeType(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000236 Record.push_back(T->getNumProtocols());
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000237 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +0000238 E = T->qual_end(); I != E; ++I)
239 Writer.AddDeclRef(*I, Record);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000240 Code = pch::TYPE_OBJC_OBJECT_POINTER;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000241}
242
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000243void PCHTypeWriter::VisitObjCProtocolListType(const ObjCProtocolListType *T) {
244 Writer.AddTypeRef(T->getBaseType(), Record);
245 Record.push_back(T->getNumProtocols());
246 for (ObjCProtocolListType::qual_iterator I = T->qual_begin(),
247 E = T->qual_end(); I != E; ++I)
248 Writer.AddDeclRef(*I, Record);
249 Code = pch::TYPE_OBJC_PROTOCOL_LIST;
250}
251
John McCalla1ee0c52009-10-16 21:56:05 +0000252namespace {
253
254class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
255 PCHWriter &Writer;
256 PCHWriter::RecordData &Record;
257
258public:
259 TypeLocWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
260 : Writer(Writer), Record(Record) { }
261
262#define ABSTRACT_TYPELOC(CLASS)
263#define TYPELOC(CLASS, PARENT) \
264 void Visit##CLASS(CLASS TyLoc);
265#include "clang/AST/TypeLocNodes.def"
266
267 void VisitTypeLoc(TypeLoc TyLoc) {
268 assert(0 && "A type loc wrapper was not handled!");
269 }
270};
271
272}
273
274void TypeLocWriter::VisitQualifiedLoc(QualifiedLoc TyLoc) {
275 // nothing to do here
276}
277void TypeLocWriter::VisitDefaultTypeSpecLoc(DefaultTypeSpecLoc TyLoc) {
278 Writer.AddSourceLocation(TyLoc.getStartLoc(), Record);
279}
280void TypeLocWriter::VisitTypedefLoc(TypedefLoc TyLoc) {
281 Writer.AddSourceLocation(TyLoc.getNameLoc(), Record);
282}
283void TypeLocWriter::VisitObjCInterfaceLoc(ObjCInterfaceLoc TyLoc) {
284 Writer.AddSourceLocation(TyLoc.getNameLoc(), Record);
285}
286void TypeLocWriter::VisitObjCProtocolListLoc(ObjCProtocolListLoc TyLoc) {
287 Writer.AddSourceLocation(TyLoc.getLAngleLoc(), Record);
288 Writer.AddSourceLocation(TyLoc.getRAngleLoc(), Record);
289 for (unsigned i = 0, e = TyLoc.getNumProtocols(); i != e; ++i)
290 Writer.AddSourceLocation(TyLoc.getProtocolLoc(i), Record);
291}
292void TypeLocWriter::VisitPointerLoc(PointerLoc TyLoc) {
293 Writer.AddSourceLocation(TyLoc.getStarLoc(), Record);
294}
295void TypeLocWriter::VisitBlockPointerLoc(BlockPointerLoc TyLoc) {
296 Writer.AddSourceLocation(TyLoc.getCaretLoc(), Record);
297}
298void TypeLocWriter::VisitMemberPointerLoc(MemberPointerLoc TyLoc) {
299 Writer.AddSourceLocation(TyLoc.getStarLoc(), Record);
300}
301void TypeLocWriter::VisitReferenceLoc(ReferenceLoc TyLoc) {
302 Writer.AddSourceLocation(TyLoc.getAmpLoc(), Record);
303}
304void TypeLocWriter::VisitFunctionLoc(FunctionLoc TyLoc) {
305 Writer.AddSourceLocation(TyLoc.getLParenLoc(), Record);
306 Writer.AddSourceLocation(TyLoc.getRParenLoc(), Record);
307 for (unsigned i = 0, e = TyLoc.getNumArgs(); i != e; ++i)
308 Writer.AddDeclRef(TyLoc.getArg(i), Record);
309}
310void TypeLocWriter::VisitArrayLoc(ArrayLoc TyLoc) {
311 Writer.AddSourceLocation(TyLoc.getLBracketLoc(), Record);
312 Writer.AddSourceLocation(TyLoc.getRBracketLoc(), Record);
313 Record.push_back(TyLoc.getSizeExpr() ? 1 : 0);
314 if (TyLoc.getSizeExpr())
315 Writer.AddStmt(TyLoc.getSizeExpr());
316}
317
Chris Lattner4dcf151a2009-04-22 05:57:30 +0000318//===----------------------------------------------------------------------===//
Douglas Gregor2cf26342009-04-09 22:27:44 +0000319// PCHWriter Implementation
320//===----------------------------------------------------------------------===//
321
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000322static void EmitBlockID(unsigned ID, const char *Name,
323 llvm::BitstreamWriter &Stream,
324 PCHWriter::RecordData &Record) {
325 Record.clear();
326 Record.push_back(ID);
327 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
328
329 // Emit the block name if present.
330 if (Name == 0 || Name[0] == 0) return;
331 Record.clear();
332 while (*Name)
333 Record.push_back(*Name++);
334 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
335}
336
337static void EmitRecordID(unsigned ID, const char *Name,
338 llvm::BitstreamWriter &Stream,
339 PCHWriter::RecordData &Record) {
340 Record.clear();
341 Record.push_back(ID);
342 while (*Name)
343 Record.push_back(*Name++);
344 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattner0558df22009-04-27 00:49:53 +0000345}
346
347static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
348 PCHWriter::RecordData &Record) {
349#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
350 RECORD(STMT_STOP);
351 RECORD(STMT_NULL_PTR);
352 RECORD(STMT_NULL);
353 RECORD(STMT_COMPOUND);
354 RECORD(STMT_CASE);
355 RECORD(STMT_DEFAULT);
356 RECORD(STMT_LABEL);
357 RECORD(STMT_IF);
358 RECORD(STMT_SWITCH);
359 RECORD(STMT_WHILE);
360 RECORD(STMT_DO);
361 RECORD(STMT_FOR);
362 RECORD(STMT_GOTO);
363 RECORD(STMT_INDIRECT_GOTO);
364 RECORD(STMT_CONTINUE);
365 RECORD(STMT_BREAK);
366 RECORD(STMT_RETURN);
367 RECORD(STMT_DECL);
368 RECORD(STMT_ASM);
369 RECORD(EXPR_PREDEFINED);
370 RECORD(EXPR_DECL_REF);
371 RECORD(EXPR_INTEGER_LITERAL);
372 RECORD(EXPR_FLOATING_LITERAL);
373 RECORD(EXPR_IMAGINARY_LITERAL);
374 RECORD(EXPR_STRING_LITERAL);
375 RECORD(EXPR_CHARACTER_LITERAL);
376 RECORD(EXPR_PAREN);
377 RECORD(EXPR_UNARY_OPERATOR);
378 RECORD(EXPR_SIZEOF_ALIGN_OF);
379 RECORD(EXPR_ARRAY_SUBSCRIPT);
380 RECORD(EXPR_CALL);
381 RECORD(EXPR_MEMBER);
382 RECORD(EXPR_BINARY_OPERATOR);
383 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
384 RECORD(EXPR_CONDITIONAL_OPERATOR);
385 RECORD(EXPR_IMPLICIT_CAST);
386 RECORD(EXPR_CSTYLE_CAST);
387 RECORD(EXPR_COMPOUND_LITERAL);
388 RECORD(EXPR_EXT_VECTOR_ELEMENT);
389 RECORD(EXPR_INIT_LIST);
390 RECORD(EXPR_DESIGNATED_INIT);
391 RECORD(EXPR_IMPLICIT_VALUE_INIT);
392 RECORD(EXPR_VA_ARG);
393 RECORD(EXPR_ADDR_LABEL);
394 RECORD(EXPR_STMT);
395 RECORD(EXPR_TYPES_COMPATIBLE);
396 RECORD(EXPR_CHOOSE);
397 RECORD(EXPR_GNU_NULL);
398 RECORD(EXPR_SHUFFLE_VECTOR);
399 RECORD(EXPR_BLOCK);
400 RECORD(EXPR_BLOCK_DECL_REF);
401 RECORD(EXPR_OBJC_STRING_LITERAL);
402 RECORD(EXPR_OBJC_ENCODE);
403 RECORD(EXPR_OBJC_SELECTOR_EXPR);
404 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
405 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
406 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
407 RECORD(EXPR_OBJC_KVC_REF_EXPR);
408 RECORD(EXPR_OBJC_MESSAGE_EXPR);
409 RECORD(EXPR_OBJC_SUPER_EXPR);
410 RECORD(STMT_OBJC_FOR_COLLECTION);
411 RECORD(STMT_OBJC_CATCH);
412 RECORD(STMT_OBJC_FINALLY);
413 RECORD(STMT_OBJC_AT_TRY);
414 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
415 RECORD(STMT_OBJC_AT_THROW);
416#undef RECORD
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000417}
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000419void PCHWriter::WriteBlockInfoBlock() {
420 RecordData Record;
421 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner2f4efd12009-04-27 00:40:25 +0000423#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000424#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000426 // PCH Top-Level Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000427 BLOCK(PCH_BLOCK);
Zhongxing Xu51e774d2009-06-03 09:23:28 +0000428 RECORD(ORIGINAL_FILE_NAME);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000429 RECORD(TYPE_OFFSET);
430 RECORD(DECL_OFFSET);
431 RECORD(LANGUAGE_OPTIONS);
Douglas Gregorab41e632009-04-27 22:23:34 +0000432 RECORD(METADATA);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000433 RECORD(IDENTIFIER_OFFSET);
434 RECORD(IDENTIFIER_TABLE);
435 RECORD(EXTERNAL_DEFINITIONS);
436 RECORD(SPECIAL_TYPES);
437 RECORD(STATISTICS);
438 RECORD(TENTATIVE_DEFINITIONS);
439 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
440 RECORD(SELECTOR_OFFSETS);
441 RECORD(METHOD_POOL);
442 RECORD(PP_COUNTER_VALUE);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000443 RECORD(SOURCE_LOCATION_OFFSETS);
444 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000445 RECORD(STAT_CACHE);
Douglas Gregorb81c1702009-04-27 20:06:05 +0000446 RECORD(EXT_VECTOR_DECLS);
Douglas Gregor2e222532009-07-02 17:08:52 +0000447 RECORD(COMMENT_RANGES);
Douglas Gregor445e23e2009-10-05 21:07:28 +0000448 RECORD(SVN_BRANCH_REVISION);
449
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000450 // SourceManager Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000451 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000452 RECORD(SM_SLOC_FILE_ENTRY);
453 RECORD(SM_SLOC_BUFFER_ENTRY);
454 RECORD(SM_SLOC_BUFFER_BLOB);
455 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
456 RECORD(SM_LINE_TABLE);
457 RECORD(SM_HEADER_FILE_INFO);
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000459 // Preprocessor Block.
Chris Lattner2f4efd12009-04-27 00:40:25 +0000460 BLOCK(PREPROCESSOR_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000461 RECORD(PP_MACRO_OBJECT_LIKE);
462 RECORD(PP_MACRO_FUNCTION_LIKE);
463 RECORD(PP_TOKEN);
464
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000465 // Decls and Types block.
466 BLOCK(DECLTYPES_BLOCK);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000467 RECORD(TYPE_EXT_QUAL);
468 RECORD(TYPE_FIXED_WIDTH_INT);
469 RECORD(TYPE_COMPLEX);
470 RECORD(TYPE_POINTER);
471 RECORD(TYPE_BLOCK_POINTER);
472 RECORD(TYPE_LVALUE_REFERENCE);
473 RECORD(TYPE_RVALUE_REFERENCE);
474 RECORD(TYPE_MEMBER_POINTER);
475 RECORD(TYPE_CONSTANT_ARRAY);
476 RECORD(TYPE_INCOMPLETE_ARRAY);
477 RECORD(TYPE_VARIABLE_ARRAY);
478 RECORD(TYPE_VECTOR);
479 RECORD(TYPE_EXT_VECTOR);
480 RECORD(TYPE_FUNCTION_PROTO);
481 RECORD(TYPE_FUNCTION_NO_PROTO);
482 RECORD(TYPE_TYPEDEF);
483 RECORD(TYPE_TYPEOF_EXPR);
484 RECORD(TYPE_TYPEOF);
485 RECORD(TYPE_RECORD);
486 RECORD(TYPE_ENUM);
487 RECORD(TYPE_OBJC_INTERFACE);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000488 RECORD(TYPE_OBJC_OBJECT_POINTER);
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +0000489 RECORD(TYPE_OBJC_PROTOCOL_LIST);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000490 RECORD(DECL_ATTR);
491 RECORD(DECL_TRANSLATION_UNIT);
492 RECORD(DECL_TYPEDEF);
493 RECORD(DECL_ENUM);
494 RECORD(DECL_RECORD);
495 RECORD(DECL_ENUM_CONSTANT);
496 RECORD(DECL_FUNCTION);
497 RECORD(DECL_OBJC_METHOD);
498 RECORD(DECL_OBJC_INTERFACE);
499 RECORD(DECL_OBJC_PROTOCOL);
500 RECORD(DECL_OBJC_IVAR);
501 RECORD(DECL_OBJC_AT_DEFS_FIELD);
502 RECORD(DECL_OBJC_CLASS);
503 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
504 RECORD(DECL_OBJC_CATEGORY);
505 RECORD(DECL_OBJC_CATEGORY_IMPL);
506 RECORD(DECL_OBJC_IMPLEMENTATION);
507 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
508 RECORD(DECL_OBJC_PROPERTY);
509 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000510 RECORD(DECL_FIELD);
511 RECORD(DECL_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000512 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000513 RECORD(DECL_PARM_VAR);
Chris Lattner0ff8cda2009-04-26 22:32:16 +0000514 RECORD(DECL_ORIGINAL_PARM_VAR);
515 RECORD(DECL_FILE_SCOPE_ASM);
516 RECORD(DECL_BLOCK);
517 RECORD(DECL_CONTEXT_LEXICAL);
518 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000519 // Statements and Exprs can occur in the Decls and Types block.
Chris Lattner0558df22009-04-27 00:49:53 +0000520 AddStmtsExprs(Stream, Record);
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000521#undef RECORD
522#undef BLOCK
523 Stream.ExitBlock();
524}
525
Douglas Gregore650c8c2009-07-07 00:12:59 +0000526/// \brief Adjusts the given filename to only write out the portion of the
527/// filename that is not part of the system root directory.
Mike Stump1eb44332009-09-09 15:08:12 +0000528///
Douglas Gregore650c8c2009-07-07 00:12:59 +0000529/// \param Filename the file name to adjust.
530///
531/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
532/// the returned filename will be adjusted by this system root.
533///
534/// \returns either the original filename (if it needs no adjustment) or the
535/// adjusted filename (which points into the @p Filename parameter).
Mike Stump1eb44332009-09-09 15:08:12 +0000536static const char *
Douglas Gregore650c8c2009-07-07 00:12:59 +0000537adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
538 assert(Filename && "No file name to adjust?");
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregore650c8c2009-07-07 00:12:59 +0000540 if (!isysroot)
541 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Douglas Gregore650c8c2009-07-07 00:12:59 +0000543 // Verify that the filename and the system root have the same prefix.
544 unsigned Pos = 0;
545 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
546 if (Filename[Pos] != isysroot[Pos])
547 return Filename; // Prefixes don't match.
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Douglas Gregore650c8c2009-07-07 00:12:59 +0000549 // We hit the end of the filename before we hit the end of the system root.
550 if (!Filename[Pos])
551 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Douglas Gregore650c8c2009-07-07 00:12:59 +0000553 // If the file name has a '/' at the current position, skip over the '/'.
554 // We distinguish sysroot-based includes from absolute includes by the
555 // absence of '/' at the beginning of sysroot-based includes.
556 if (Filename[Pos] == '/')
557 ++Pos;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Douglas Gregore650c8c2009-07-07 00:12:59 +0000559 return Filename + Pos;
560}
Chris Lattnerb145b1e2009-04-26 22:26:21 +0000561
Douglas Gregorab41e632009-04-27 22:23:34 +0000562/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
Douglas Gregore650c8c2009-07-07 00:12:59 +0000563void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
Douglas Gregor2bec0412009-04-10 21:16:55 +0000564 using namespace llvm;
Douglas Gregorb64c1932009-05-12 01:31:05 +0000565
Douglas Gregore650c8c2009-07-07 00:12:59 +0000566 // Metadata
567 const TargetInfo &Target = Context.Target;
568 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
569 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
570 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
571 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
572 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
573 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
574 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
575 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
576 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Douglas Gregore650c8c2009-07-07 00:12:59 +0000578 RecordData Record;
579 Record.push_back(pch::METADATA);
580 Record.push_back(pch::VERSION_MAJOR);
581 Record.push_back(pch::VERSION_MINOR);
582 Record.push_back(CLANG_VERSION_MAJOR);
583 Record.push_back(CLANG_VERSION_MINOR);
584 Record.push_back(isysroot != 0);
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000585 const std::string &TripleStr = Target.getTriple().getTriple();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000586 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Douglas Gregorb64c1932009-05-12 01:31:05 +0000588 // Original file name
589 SourceManager &SM = Context.getSourceManager();
590 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
591 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
592 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
593 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
594 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
595
596 llvm::sys::Path MainFilePath(MainFile->getName());
597 std::string MainFileName;
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregorb64c1932009-05-12 01:31:05 +0000599 if (!MainFilePath.isAbsolute()) {
600 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000601 P.appendComponent(MainFilePath.str());
602 MainFileName = P.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000603 } else {
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000604 MainFileName = MainFilePath.str();
Douglas Gregorb64c1932009-05-12 01:31:05 +0000605 }
606
Douglas Gregore650c8c2009-07-07 00:12:59 +0000607 const char *MainFileNameStr = MainFileName.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +0000608 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000609 isysroot);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000610 RecordData Record;
611 Record.push_back(pch::ORIGINAL_FILE_NAME);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000612 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
Douglas Gregorb64c1932009-05-12 01:31:05 +0000613 }
Douglas Gregor445e23e2009-10-05 21:07:28 +0000614
615 // Subversion branch/version information.
616 BitCodeAbbrev *SvnAbbrev = new BitCodeAbbrev();
617 SvnAbbrev->Add(BitCodeAbbrevOp(pch::SVN_BRANCH_REVISION));
618 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // SVN revision
619 SvnAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
620 unsigned SvnAbbrevCode = Stream.EmitAbbrev(SvnAbbrev);
621 Record.clear();
622 Record.push_back(pch::SVN_BRANCH_REVISION);
623 Record.push_back(getClangSubversionRevision());
624 Stream.EmitRecordWithBlob(SvnAbbrevCode, Record, getClangSubversionPath());
Douglas Gregor2bec0412009-04-10 21:16:55 +0000625}
626
627/// \brief Write the LangOptions structure.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000628void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
629 RecordData Record;
630 Record.push_back(LangOpts.Trigraphs);
631 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
632 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
633 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
634 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
635 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
636 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
637 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
638 Record.push_back(LangOpts.C99); // C99 Support
639 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
640 Record.push_back(LangOpts.CPlusPlus); // C++ Support
641 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000642 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000644 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
645 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
646 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C modern abi enabled
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000648 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000649 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
650 Record.push_back(LangOpts.LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000651 Record.push_back(LangOpts.AltiVec);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000652 Record.push_back(LangOpts.Exceptions); // Support exception handling.
653
654 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
655 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
656 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
657
Chris Lattnerea5ce472009-04-27 07:35:58 +0000658 // Whether static initializers are protected by locks.
659 Record.push_back(LangOpts.ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +0000660 Record.push_back(LangOpts.POSIXThreads);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000661 Record.push_back(LangOpts.Blocks); // block extension to C
662 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
663 // they are unused.
664 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
665 // (modulo the platform support).
666
667 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
668 // signed integer arithmetic overflows.
669
670 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
671 // may be ripped out at any time.
672
673 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
Mike Stump1eb44332009-09-09 15:08:12 +0000674 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000675 // defined.
676 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
677 // opposed to __DYNAMIC__).
678 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
679
680 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
681 // used (instead of C99 semantics).
682 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
Anders Carlssona33d9b42009-05-13 19:49:53 +0000683 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
684 // be enabled.
Eli Friedman15b91762009-06-05 07:05:05 +0000685 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
686 // unsigned type
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000687 Record.push_back(LangOpts.getGCMode());
688 Record.push_back(LangOpts.getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000689 Record.push_back(LangOpts.getStackProtectorMode());
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000690 Record.push_back(LangOpts.InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +0000691 Record.push_back(LangOpts.OpenCL);
Anders Carlsson92f58222009-08-22 22:30:33 +0000692 Record.push_back(LangOpts.ElideConstructors);
Douglas Gregorc9490c02009-04-16 22:23:12 +0000693 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000694}
695
Douglas Gregor14f79002009-04-10 03:52:48 +0000696//===----------------------------------------------------------------------===//
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000697// stat cache Serialization
698//===----------------------------------------------------------------------===//
699
700namespace {
701// Trait used for the on-disk hash table of stat cache results.
702class VISIBILITY_HIDDEN PCHStatCacheTrait {
703public:
704 typedef const char * key_type;
705 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000707 typedef std::pair<int, struct stat> data_type;
708 typedef const data_type& data_type_ref;
709
710 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000711 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
714 std::pair<unsigned,unsigned>
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000715 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
716 data_type_ref Data) {
717 unsigned StrLen = strlen(path);
718 clang::io::Emit16(Out, StrLen);
719 unsigned DataLen = 1; // result value
720 if (Data.first == 0)
721 DataLen += 4 + 4 + 2 + 8 + 8;
722 clang::io::Emit8(Out, DataLen);
723 return std::make_pair(StrLen + 1, DataLen);
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000726 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
727 Out.write(path, KeyLen);
728 }
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000730 void EmitData(llvm::raw_ostream& Out, key_type_ref,
731 data_type_ref Data, unsigned DataLen) {
732 using namespace clang::io;
733 uint64_t Start = Out.tell(); (void)Start;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000735 // Result of stat()
736 Emit8(Out, Data.first? 1 : 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000738 if (Data.first == 0) {
739 Emit32(Out, (uint32_t) Data.second.st_ino);
740 Emit32(Out, (uint32_t) Data.second.st_dev);
741 Emit16(Out, (uint16_t) Data.second.st_mode);
742 Emit64(Out, (uint64_t) Data.second.st_mtime);
743 Emit64(Out, (uint64_t) Data.second.st_size);
744 }
745
746 assert(Out.tell() - Start == DataLen && "Wrong data length");
747 }
748};
749} // end anonymous namespace
750
751/// \brief Write the stat() system call cache to the PCH file.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000752void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
753 const char *isysroot) {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000754 // Build the on-disk hash table containing information about every
755 // stat() call.
756 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
757 unsigned NumStatEntries = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000758 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000759 StatEnd = StatCalls.end();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000760 Stat != StatEnd; ++Stat, ++NumStatEntries) {
761 const char *Filename = Stat->first();
762 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
763 Generator.insert(Filename, Stat->second);
764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000766 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000767 llvm::SmallString<4096> StatCacheData;
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000768 uint32_t BucketOffset;
769 {
770 llvm::raw_svector_ostream Out(StatCacheData);
771 // Make sure that no bucket is at offset 0
772 clang::io::Emit32(Out, 0);
773 BucketOffset = Generator.Emit(Out);
774 }
775
776 // Create a blob abbreviation
777 using namespace llvm;
778 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
779 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
780 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
781 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
782 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
783 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
784
785 // Write the stat cache
786 RecordData Record;
787 Record.push_back(pch::STAT_CACHE);
788 Record.push_back(BucketOffset);
789 Record.push_back(NumStatEntries);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000790 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000791}
792
793//===----------------------------------------------------------------------===//
Douglas Gregor14f79002009-04-10 03:52:48 +0000794// Source Manager Serialization
795//===----------------------------------------------------------------------===//
796
797/// \brief Create an abbreviation for the SLocEntry that refers to a
798/// file.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000799static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000800 using namespace llvm;
801 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
802 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
803 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
805 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
806 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregor14f79002009-04-10 03:52:48 +0000807 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
Douglas Gregorc9490c02009-04-16 22:23:12 +0000808 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000809}
810
811/// \brief Create an abbreviation for the SLocEntry that refers to a
812/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000813static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000814 using namespace llvm;
815 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
816 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
817 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
818 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
819 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000822 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000823}
824
825/// \brief Create an abbreviation for the SLocEntry that refers to a
826/// buffer's blob.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000827static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000828 using namespace llvm;
829 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
830 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
831 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregorc9490c02009-04-16 22:23:12 +0000832 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000833}
834
835/// \brief Create an abbreviation for the SLocEntry that refers to an
836/// buffer.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000837static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000838 using namespace llvm;
839 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
840 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
843 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregorf60e9912009-04-15 18:05:10 +0000845 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregorc9490c02009-04-16 22:23:12 +0000846 return Stream.EmitAbbrev(Abbrev);
Douglas Gregor14f79002009-04-10 03:52:48 +0000847}
848
849/// \brief Writes the block containing the serialized form of the
850/// source manager.
851///
852/// TODO: We should probably use an on-disk hash table (stored in a
853/// blob), indexed based on the file name, so that we only create
854/// entries for files that we actually need. In the common case (no
855/// errors), we probably won't have to create file entries for any of
856/// the files in the AST.
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000857void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000858 const Preprocessor &PP,
859 const char *isysroot) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000860 RecordData Record;
861
Chris Lattnerf04ad692009-04-10 17:16:57 +0000862 // Enter the source manager block.
Douglas Gregorc9490c02009-04-16 22:23:12 +0000863 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
Douglas Gregor14f79002009-04-10 03:52:48 +0000864
865 // Abbreviations for the various kinds of source-location entries.
Chris Lattner828e18c2009-04-27 19:03:22 +0000866 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
867 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
868 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
869 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
Douglas Gregor14f79002009-04-10 03:52:48 +0000870
Douglas Gregorbd945002009-04-13 16:31:14 +0000871 // Write the line table.
872 if (SourceMgr.hasLineTable()) {
873 LineTableInfo &LineTable = SourceMgr.getLineTable();
874
875 // Emit the file names
876 Record.push_back(LineTable.getNumFilenames());
877 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
878 // Emit the file name
879 const char *Filename = LineTable.getFilename(I);
Douglas Gregore650c8c2009-07-07 00:12:59 +0000880 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Douglas Gregorbd945002009-04-13 16:31:14 +0000881 unsigned FilenameLen = Filename? strlen(Filename) : 0;
882 Record.push_back(FilenameLen);
883 if (FilenameLen)
884 Record.insert(Record.end(), Filename, Filename + FilenameLen);
885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregorbd945002009-04-13 16:31:14 +0000887 // Emit the line entries
888 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
889 L != LEnd; ++L) {
890 // Emit the file ID
891 Record.push_back(L->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregorbd945002009-04-13 16:31:14 +0000893 // Emit the line entries
894 Record.push_back(L->second.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000895 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
Douglas Gregorbd945002009-04-13 16:31:14 +0000896 LEEnd = L->second.end();
897 LE != LEEnd; ++LE) {
898 Record.push_back(LE->FileOffset);
899 Record.push_back(LE->LineNo);
900 Record.push_back(LE->FilenameID);
901 Record.push_back((unsigned)LE->FileKind);
902 Record.push_back(LE->IncludeOffset);
903 }
Douglas Gregorbd945002009-04-13 16:31:14 +0000904 }
Zhongxing Xu3d8216a2009-05-22 08:38:27 +0000905 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
Douglas Gregorbd945002009-04-13 16:31:14 +0000906 }
907
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000908 // Write out entries for all of the header files we know about.
Mike Stump1eb44332009-09-09 15:08:12 +0000909 HeaderSearch &HS = PP.getHeaderSearchInfo();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000910 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000911 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000912 E = HS.header_file_end();
913 I != E; ++I) {
914 Record.push_back(I->isImport);
915 Record.push_back(I->DirInfo);
916 Record.push_back(I->NumIncludes);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000917 AddIdentifierRef(I->ControllingMacro, Record);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000918 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
919 Record.clear();
920 }
921
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000922 // Write out the source location entry table. We skip the first
923 // entry, which is always the same dummy entry.
Chris Lattner090d9b52009-04-27 19:01:47 +0000924 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000925 RecordData PreloadSLocs;
926 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
Douglas Gregorbdfe48a2009-10-16 22:46:09 +0000927 for (unsigned I = 1, N = SourceMgr.sloc_entry_size(); I != N; ++I) {
928 // Get this source location entry.
929 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
930
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000931 // Record the offset of this source-location entry.
932 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
933
934 // Figure out which record code to use.
935 unsigned Code;
936 if (SLoc->isFile()) {
937 if (SLoc->getFile().getContentCache()->Entry)
938 Code = pch::SM_SLOC_FILE_ENTRY;
939 else
940 Code = pch::SM_SLOC_BUFFER_ENTRY;
941 } else
942 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
943 Record.clear();
944 Record.push_back(Code);
945
946 Record.push_back(SLoc->getOffset());
947 if (SLoc->isFile()) {
948 const SrcMgr::FileInfo &File = SLoc->getFile();
949 Record.push_back(File.getIncludeLoc().getRawEncoding());
950 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
951 Record.push_back(File.hasLineDirectives());
952
953 const SrcMgr::ContentCache *Content = File.getContentCache();
954 if (Content->Entry) {
955 // The source location entry is a file. The blob associated
956 // with this entry is the file name.
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregore650c8c2009-07-07 00:12:59 +0000958 // Turn the file name into an absolute path, if it isn't already.
959 const char *Filename = Content->Entry->getName();
960 llvm::sys::Path FilePath(Filename, strlen(Filename));
961 std::string FilenameStr;
962 if (!FilePath.isAbsolute()) {
963 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000964 P.appendComponent(FilePath.str());
965 FilenameStr = P.str();
Douglas Gregore650c8c2009-07-07 00:12:59 +0000966 Filename = FilenameStr.c_str();
967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Douglas Gregore650c8c2009-07-07 00:12:59 +0000969 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
Daniel Dunbarec312a12009-08-24 09:31:37 +0000970 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000971
972 // FIXME: For now, preload all file source locations, so that
973 // we get the appropriate File entries in the reader. This is
974 // a temporary measure.
975 PreloadSLocs.push_back(SLocEntryOffsets.size());
976 } else {
977 // The source location entry is a buffer. The blob associated
978 // with this entry contains the contents of the buffer.
979
980 // We add one to the size so that we capture the trailing NULL
981 // that is required by llvm::MemoryBuffer::getMemBuffer (on
982 // the reader side).
983 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
984 const char *Name = Buffer->getBufferIdentifier();
Daniel Dunbarec312a12009-08-24 09:31:37 +0000985 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
986 llvm::StringRef(Name, strlen(Name) + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000987 Record.clear();
988 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
989 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
Daniel Dunbarec312a12009-08-24 09:31:37 +0000990 llvm::StringRef(Buffer->getBufferStart(),
991 Buffer->getBufferSize() + 1));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000992
993 if (strcmp(Name, "<built-in>") == 0)
994 PreloadSLocs.push_back(SLocEntryOffsets.size());
995 }
996 } else {
997 // The source location entry is an instantiation.
998 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
999 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1000 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1001 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1002
1003 // Compute the token length for this macro expansion.
1004 unsigned NextOffset = SourceMgr.getNextOffset();
Douglas Gregorbdfe48a2009-10-16 22:46:09 +00001005 if (I + 1 != N)
1006 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001007 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1008 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1009 }
1010 }
1011
Douglas Gregorc9490c02009-04-16 22:23:12 +00001012 Stream.ExitBlock();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001013
1014 if (SLocEntryOffsets.empty())
1015 return;
1016
1017 // Write the source-location offsets table into the PCH block. This
1018 // table is used for lazily loading source-location information.
1019 using namespace llvm;
1020 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1021 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
1022 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1023 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1024 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1025 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001027 Record.clear();
1028 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
1029 Record.push_back(SLocEntryOffsets.size());
1030 Record.push_back(SourceMgr.getNextOffset());
1031 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001032 (const char *)&SLocEntryOffsets.front(),
Chris Lattner090d9b52009-04-27 19:01:47 +00001033 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001034
1035 // Write the source location entry preloads array, telling the PCH
1036 // reader which source locations entries it should load eagerly.
1037 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor14f79002009-04-10 03:52:48 +00001038}
1039
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001040//===----------------------------------------------------------------------===//
1041// Preprocessor Serialization
1042//===----------------------------------------------------------------------===//
1043
Chris Lattner0b1fb982009-04-10 17:15:23 +00001044/// \brief Writes the block containing the serialized form of the
1045/// preprocessor.
1046///
Chris Lattnerdf961c22009-04-10 18:08:30 +00001047void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001048 RecordData Record;
Chris Lattnerf04ad692009-04-10 17:16:57 +00001049
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001050 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1051 if (PP.getCounterValue() != 0) {
1052 Record.push_back(PP.getCounterValue());
Douglas Gregorc9490c02009-04-16 22:23:12 +00001053 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
Chris Lattnerc1f9d822009-04-13 01:29:17 +00001054 Record.clear();
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001055 }
1056
1057 // Enter the preprocessor block.
1058 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001060 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1061 // FIXME: use diagnostics subsystem for localization etc.
1062 if (PP.SawDateOrTime())
1063 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001065 // Loop over all the macro definitions that are live at the end of the file,
1066 // emitting each to the PP section.
Douglas Gregor813a97b2009-10-17 17:25:45 +00001067 // FIXME: Make sure that this sees macros defined in included PCH files.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001068 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1069 I != E; ++I) {
Chris Lattner42d42b52009-04-10 21:41:48 +00001070 // FIXME: This emits macros in hash table order, we should do it in a stable
1071 // order so that output is reproducible.
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001072 MacroInfo *MI = I->second;
1073
1074 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1075 // been redefined by the header (in which case they are not isBuiltinMacro).
1076 if (MI->isBuiltinMacro())
1077 continue;
1078
Douglas Gregor37e26842009-04-21 23:56:24 +00001079 // FIXME: Remove this identifier reference?
Chris Lattner7356a312009-04-11 21:15:38 +00001080 AddIdentifierRef(I->first, Record);
Douglas Gregor37e26842009-04-21 23:56:24 +00001081 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001082 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1083 Record.push_back(MI->isUsed());
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001085 unsigned Code;
1086 if (MI->isObjectLike()) {
1087 Code = pch::PP_MACRO_OBJECT_LIKE;
1088 } else {
1089 Code = pch::PP_MACRO_FUNCTION_LIKE;
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001091 Record.push_back(MI->isC99Varargs());
1092 Record.push_back(MI->isGNUVarargs());
1093 Record.push_back(MI->getNumArgs());
1094 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1095 I != E; ++I)
Chris Lattner7356a312009-04-11 21:15:38 +00001096 AddIdentifierRef(*I, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001097 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001098 Stream.EmitRecord(Code, Record);
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001099 Record.clear();
1100
Chris Lattnerdf961c22009-04-10 18:08:30 +00001101 // Emit the tokens array.
1102 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1103 // Note that we know that the preprocessor does not have any annotation
1104 // tokens in it because they are created by the parser, and thus can't be
1105 // in a macro definition.
1106 const Token &Tok = MI->getReplacementToken(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Chris Lattnerdf961c22009-04-10 18:08:30 +00001108 Record.push_back(Tok.getLocation().getRawEncoding());
1109 Record.push_back(Tok.getLength());
1110
Chris Lattnerdf961c22009-04-10 18:08:30 +00001111 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1112 // it is needed.
Chris Lattner7356a312009-04-11 21:15:38 +00001113 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Chris Lattnerdf961c22009-04-10 18:08:30 +00001115 // FIXME: Should translate token kind to a stable encoding.
1116 Record.push_back(Tok.getKind());
1117 // FIXME: Should translate token flags to a stable encoding.
1118 Record.push_back(Tok.getFlags());
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregorc9490c02009-04-16 22:23:12 +00001120 Stream.EmitRecord(pch::PP_TOKEN, Record);
Chris Lattnerdf961c22009-04-10 18:08:30 +00001121 Record.clear();
1122 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001123 ++NumMacros;
Chris Lattner7c5d24e2009-04-10 18:00:12 +00001124 }
Douglas Gregorc9490c02009-04-16 22:23:12 +00001125 Stream.ExitBlock();
Chris Lattner0b1fb982009-04-10 17:15:23 +00001126}
1127
Douglas Gregor2e222532009-07-02 17:08:52 +00001128void PCHWriter::WriteComments(ASTContext &Context) {
1129 using namespace llvm;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Douglas Gregor2e222532009-07-02 17:08:52 +00001131 if (Context.Comments.empty())
1132 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregor2e222532009-07-02 17:08:52 +00001134 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1135 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1136 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1137 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Douglas Gregor2e222532009-07-02 17:08:52 +00001139 RecordData Record;
1140 Record.push_back(pch::COMMENT_RANGES);
Mike Stump1eb44332009-09-09 15:08:12 +00001141 Stream.EmitRecordWithBlob(CommentCode, Record,
Douglas Gregor2e222532009-07-02 17:08:52 +00001142 (const char*)&Context.Comments[0],
1143 Context.Comments.size() * sizeof(SourceRange));
1144}
1145
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001146//===----------------------------------------------------------------------===//
1147// Type Serialization
1148//===----------------------------------------------------------------------===//
Chris Lattner0b1fb982009-04-10 17:15:23 +00001149
Douglas Gregor2cf26342009-04-09 22:27:44 +00001150/// \brief Write the representation of a type to the PCH stream.
John McCall0953e762009-09-24 19:53:00 +00001151void PCHWriter::WriteType(QualType T) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001152 pch::TypeID &ID = TypeIDs[T];
Chris Lattnerf04ad692009-04-10 17:16:57 +00001153 if (ID == 0) // we haven't seen this type before.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001154 ID = NextTypeID++;
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Douglas Gregor2cf26342009-04-09 22:27:44 +00001156 // Record the offset for this type.
1157 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
Douglas Gregorc9490c02009-04-16 22:23:12 +00001158 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1160 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001161 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001162 }
1163
1164 RecordData Record;
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Douglas Gregor2cf26342009-04-09 22:27:44 +00001166 // Emit the type's representation.
1167 PCHTypeWriter W(*this, Record);
John McCall0953e762009-09-24 19:53:00 +00001168
1169 if (T.hasNonFastQualifiers()) {
1170 Qualifiers Qs = T.getQualifiers();
1171 AddTypeRef(T.getUnqualifiedType(), Record);
1172 Record.push_back(Qs.getAsOpaqueValue());
1173 W.Code = pch::TYPE_EXT_QUAL;
1174 } else {
1175 switch (T->getTypeClass()) {
1176 // For all of the concrete, non-dependent types, call the
1177 // appropriate visitor function.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001178#define TYPE(Class, Base) \
John McCall0953e762009-09-24 19:53:00 +00001179 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001180#define ABSTRACT_TYPE(Class, Base)
1181#define DEPENDENT_TYPE(Class, Base)
1182#include "clang/AST/TypeNodes.def"
1183
John McCall0953e762009-09-24 19:53:00 +00001184 // For all of the dependent type nodes (which only occur in C++
1185 // templates), produce an error.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001186#define TYPE(Class, Base)
1187#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1188#include "clang/AST/TypeNodes.def"
John McCall0953e762009-09-24 19:53:00 +00001189 assert(false && "Cannot serialize dependent type nodes");
1190 break;
1191 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001192 }
1193
1194 // Emit the serialized record.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001195 Stream.EmitRecord(W.Code, Record);
Douglas Gregor0b748912009-04-14 21:18:50 +00001196
1197 // Flush any expressions that were written as part of this type.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001198 FlushStmts();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001199}
1200
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001201//===----------------------------------------------------------------------===//
1202// Declaration Serialization
1203//===----------------------------------------------------------------------===//
1204
Douglas Gregor2cf26342009-04-09 22:27:44 +00001205/// \brief Write the block containing all of the declaration IDs
1206/// lexically declared within the given DeclContext.
1207///
1208/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1209/// bistream, or 0 if no block was written.
Mike Stump1eb44332009-09-09 15:08:12 +00001210uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregor2cf26342009-04-09 22:27:44 +00001211 DeclContext *DC) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 if (DC->decls_empty())
Douglas Gregor2cf26342009-04-09 22:27:44 +00001213 return 0;
1214
Douglas Gregorc9490c02009-04-16 22:23:12 +00001215 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001216 RecordData Record;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1218 D != DEnd; ++D)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001219 AddDeclRef(*D, Record);
1220
Douglas Gregor25123082009-04-22 22:34:57 +00001221 ++NumLexicalDeclContexts;
Douglas Gregorc9490c02009-04-16 22:23:12 +00001222 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001223 return Offset;
1224}
1225
1226/// \brief Write the block containing all of the declaration IDs
1227/// visible from the given DeclContext.
1228///
1229/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1230/// bistream, or 0 if no block was written.
1231uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1232 DeclContext *DC) {
1233 if (DC->getPrimaryContext() != DC)
1234 return 0;
1235
Douglas Gregoraff22df2009-04-21 22:32:33 +00001236 // Since there is no name lookup into functions or methods, and we
1237 // perform name lookup for the translation unit via the
1238 // IdentifierInfo chains, don't bother to build a
1239 // visible-declarations table for these entities.
1240 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
Douglas Gregor58f06992009-04-18 15:49:20 +00001241 return 0;
1242
Douglas Gregor2cf26342009-04-09 22:27:44 +00001243 // Force the DeclContext to build a its name-lookup table.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001244 DC->lookup(DeclarationName());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001245
1246 // Serialize the contents of the mapping used for lookup. Note that,
1247 // although we have two very different code paths, the serialized
1248 // representation is the same for both cases: a declaration name,
1249 // followed by a size, followed by references to the visible
1250 // declarations that have that name.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001251 uint64_t Offset = Stream.GetCurrentBitNo();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001252 RecordData Record;
1253 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
Douglas Gregor8c700062009-04-13 21:20:57 +00001254 if (!Map)
1255 return 0;
1256
Douglas Gregor2cf26342009-04-09 22:27:44 +00001257 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1258 D != DEnd; ++D) {
1259 AddDeclarationName(D->first, Record);
1260 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1261 Record.push_back(Result.second - Result.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001262 for (; Result.first != Result.second; ++Result.first)
Douglas Gregor2cf26342009-04-09 22:27:44 +00001263 AddDeclRef(*Result.first, Record);
1264 }
1265
1266 if (Record.size() == 0)
1267 return 0;
1268
Douglas Gregorc9490c02009-04-16 22:23:12 +00001269 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
Douglas Gregor25123082009-04-22 22:34:57 +00001270 ++NumVisibleDeclContexts;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001271 return Offset;
1272}
1273
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001274//===----------------------------------------------------------------------===//
1275// Global Method Pool and Selector Serialization
1276//===----------------------------------------------------------------------===//
1277
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001278namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001279// Trait used for the on-disk hash table used in the method pool.
1280class VISIBILITY_HIDDEN PCHMethodPoolTrait {
1281 PCHWriter &Writer;
1282
1283public:
1284 typedef Selector key_type;
1285 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001287 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1288 typedef const data_type& data_type_ref;
1289
1290 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001292 static unsigned ComputeHash(Selector Sel) {
1293 unsigned N = Sel.getNumArgs();
1294 if (N == 0)
1295 ++N;
1296 unsigned R = 5381;
1297 for (unsigned I = 0; I != N; ++I)
1298 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +00001299 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001300 return R;
1301 }
Mike Stump1eb44332009-09-09 15:08:12 +00001302
1303 std::pair<unsigned,unsigned>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001304 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1305 data_type_ref Methods) {
1306 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1307 clang::io::Emit16(Out, KeyLen);
1308 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
Mike Stump1eb44332009-09-09 15:08:12 +00001309 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001310 Method = Method->Next)
1311 if (Method->Method)
1312 DataLen += 4;
Mike Stump1eb44332009-09-09 15:08:12 +00001313 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001314 Method = Method->Next)
1315 if (Method->Method)
1316 DataLen += 4;
1317 clang::io::Emit16(Out, DataLen);
1318 return std::make_pair(KeyLen, DataLen);
1319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Douglas Gregor83941df2009-04-25 17:48:32 +00001321 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
Mike Stump1eb44332009-09-09 15:08:12 +00001322 uint64_t Start = Out.tell();
Douglas Gregor83941df2009-04-25 17:48:32 +00001323 assert((Start >> 32) == 0 && "Selector key offset too large");
1324 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001325 unsigned N = Sel.getNumArgs();
1326 clang::io::Emit16(Out, N);
1327 if (N == 0)
1328 N = 1;
1329 for (unsigned I = 0; I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001330 clang::io::Emit32(Out,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001331 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001334 void EmitData(llvm::raw_ostream& Out, key_type_ref,
Douglas Gregora67e58c2009-04-24 21:49:02 +00001335 data_type_ref Methods, unsigned DataLen) {
1336 uint64_t Start = Out.tell(); (void)Start;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001337 unsigned NumInstanceMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001338 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001339 Method = Method->Next)
1340 if (Method->Method)
1341 ++NumInstanceMethods;
1342
1343 unsigned NumFactoryMethods = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001344 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001345 Method = Method->Next)
1346 if (Method->Method)
1347 ++NumFactoryMethods;
1348
1349 clang::io::Emit16(Out, NumInstanceMethods);
1350 clang::io::Emit16(Out, NumFactoryMethods);
Mike Stump1eb44332009-09-09 15:08:12 +00001351 for (const ObjCMethodList *Method = &Methods.first; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001352 Method = Method->Next)
1353 if (Method->Method)
1354 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Mike Stump1eb44332009-09-09 15:08:12 +00001355 for (const ObjCMethodList *Method = &Methods.second; Method;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001356 Method = Method->Next)
1357 if (Method->Method)
1358 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
Douglas Gregora67e58c2009-04-24 21:49:02 +00001359
1360 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001361 }
1362};
1363} // end anonymous namespace
1364
1365/// \brief Write the method pool into the PCH file.
1366///
1367/// The method pool contains both instance and factory methods, stored
1368/// in an on-disk hash table indexed by the selector.
1369void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1370 using namespace llvm;
1371
1372 // Create and write out the blob that contains the instance and
1373 // factor method pools.
1374 bool Empty = true;
1375 {
1376 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001378 // Create the on-disk hash table representation. Start by
1379 // iterating through the instance method pool.
1380 PCHMethodPoolTrait::key_type Key;
Douglas Gregor83941df2009-04-25 17:48:32 +00001381 unsigned NumSelectorsInMethodPool = 0;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001382 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001383 Instance = SemaRef.InstanceMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001384 InstanceEnd = SemaRef.InstanceMethodPool.end();
1385 Instance != InstanceEnd; ++Instance) {
1386 // Check whether there is a factory method with the same
1387 // selector.
1388 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1389 = SemaRef.FactoryMethodPool.find(Instance->first);
1390
1391 if (Factory == SemaRef.FactoryMethodPool.end())
1392 Generator.insert(Instance->first,
Mike Stump1eb44332009-09-09 15:08:12 +00001393 std::make_pair(Instance->second,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001394 ObjCMethodList()));
1395 else
1396 Generator.insert(Instance->first,
1397 std::make_pair(Instance->second, Factory->second));
1398
Douglas Gregor83941df2009-04-25 17:48:32 +00001399 ++NumSelectorsInMethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001400 Empty = false;
1401 }
1402
1403 // Now iterate through the factory method pool, to pick up any
1404 // selectors that weren't already in the instance method pool.
1405 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
Mike Stump1eb44332009-09-09 15:08:12 +00001406 Factory = SemaRef.FactoryMethodPool.begin(),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001407 FactoryEnd = SemaRef.FactoryMethodPool.end();
1408 Factory != FactoryEnd; ++Factory) {
1409 // Check whether there is an instance method with the same
1410 // selector. If so, there is no work to do here.
1411 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1412 = SemaRef.InstanceMethodPool.find(Factory->first);
1413
Douglas Gregor83941df2009-04-25 17:48:32 +00001414 if (Instance == SemaRef.InstanceMethodPool.end()) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001415 Generator.insert(Factory->first,
1416 std::make_pair(ObjCMethodList(), Factory->second));
Douglas Gregor83941df2009-04-25 17:48:32 +00001417 ++NumSelectorsInMethodPool;
1418 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001419
1420 Empty = false;
1421 }
1422
Douglas Gregor83941df2009-04-25 17:48:32 +00001423 if (Empty && SelectorOffsets.empty())
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001424 return;
1425
1426 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001427 llvm::SmallString<4096> MethodPool;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001428 uint32_t BucketOffset;
Douglas Gregor83941df2009-04-25 17:48:32 +00001429 SelectorOffsets.resize(SelVector.size());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001430 {
1431 PCHMethodPoolTrait Trait(*this);
1432 llvm::raw_svector_ostream Out(MethodPool);
1433 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001434 clang::io::Emit32(Out, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001435 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor83941df2009-04-25 17:48:32 +00001436
1437 // For every selector that we have seen but which was not
1438 // written into the hash table, write the selector itself and
1439 // record it's offset.
1440 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1441 if (SelectorOffsets[I] == 0)
1442 Trait.EmitKey(Out, SelVector[I], 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001443 }
1444
1445 // Create a blob abbreviation
1446 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1447 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1448 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor83941df2009-04-25 17:48:32 +00001449 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1451 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1452
Douglas Gregor83941df2009-04-25 17:48:32 +00001453 // Write the method pool
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001454 RecordData Record;
1455 Record.push_back(pch::METHOD_POOL);
1456 Record.push_back(BucketOffset);
Douglas Gregor83941df2009-04-25 17:48:32 +00001457 Record.push_back(NumSelectorsInMethodPool);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001458 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
Douglas Gregor83941df2009-04-25 17:48:32 +00001459
1460 // Create a blob abbreviation for the selector table offsets.
1461 Abbrev = new BitCodeAbbrev();
1462 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1464 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1465 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1466
1467 // Write the selector offsets table.
1468 Record.clear();
1469 Record.push_back(pch::SELECTOR_OFFSETS);
1470 Record.push_back(SelectorOffsets.size());
1471 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1472 (const char *)&SelectorOffsets.front(),
1473 SelectorOffsets.size() * 4);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001474 }
1475}
1476
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001477//===----------------------------------------------------------------------===//
1478// Identifier Table Serialization
1479//===----------------------------------------------------------------------===//
1480
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001481namespace {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001482class VISIBILITY_HIDDEN PCHIdentifierTableTrait {
1483 PCHWriter &Writer;
Douglas Gregor37e26842009-04-21 23:56:24 +00001484 Preprocessor &PP;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001485
Douglas Gregora92193e2009-04-28 21:18:29 +00001486 /// \brief Determines whether this is an "interesting" identifier
1487 /// that needs a full IdentifierInfo structure written into the hash
1488 /// table.
1489 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1490 return II->isPoisoned() ||
1491 II->isExtensionToken() ||
1492 II->hasMacroDefinition() ||
1493 II->getObjCOrBuiltinID() ||
1494 II->getFETokenInfo<void>();
1495 }
1496
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001497public:
1498 typedef const IdentifierInfo* key_type;
1499 typedef key_type key_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001501 typedef pch::IdentID data_type;
1502 typedef data_type data_type_ref;
Mike Stump1eb44332009-09-09 15:08:12 +00001503
1504 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
Douglas Gregor37e26842009-04-21 23:56:24 +00001505 : Writer(Writer), PP(PP) { }
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001506
1507 static unsigned ComputeHash(const IdentifierInfo* II) {
Daniel Dunbar2596e422009-10-17 23:52:28 +00001508 return llvm::HashString(II->getName());
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
1511 std::pair<unsigned,unsigned>
1512 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001513 pch::IdentID ID) {
1514 unsigned KeyLen = strlen(II->getName()) + 1;
Douglas Gregora92193e2009-04-28 21:18:29 +00001515 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1516 if (isInterestingIdentifier(II)) {
Douglas Gregor5998da52009-04-28 21:32:13 +00001517 DataLen += 2; // 2 bytes for builtin ID, flags
Mike Stump1eb44332009-09-09 15:08:12 +00001518 if (II->hasMacroDefinition() &&
Douglas Gregora92193e2009-04-28 21:18:29 +00001519 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
Douglas Gregor5998da52009-04-28 21:32:13 +00001520 DataLen += 4;
Douglas Gregora92193e2009-04-28 21:18:29 +00001521 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1522 DEnd = IdentifierResolver::end();
1523 D != DEnd; ++D)
1524 DataLen += sizeof(pch::DeclID);
1525 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001526 clang::io::Emit16(Out, DataLen);
Douglas Gregor02fc7512009-04-28 20:01:51 +00001527 // We emit the key length after the data length so that every
1528 // string is preceded by a 16-bit length. This matches the PTH
1529 // format for storing identifiers.
Douglas Gregord6595a42009-04-25 21:04:17 +00001530 clang::io::Emit16(Out, KeyLen);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001531 return std::make_pair(KeyLen, DataLen);
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
1534 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001535 unsigned KeyLen) {
1536 // Record the location of the key data. This is used when generating
1537 // the mapping from persistent IDs to strings.
1538 Writer.SetIdentifierOffset(II, Out.tell());
1539 Out.write(II->getName(), KeyLen);
1540 }
Mike Stump1eb44332009-09-09 15:08:12 +00001541
1542 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001543 pch::IdentID ID, unsigned) {
Douglas Gregora92193e2009-04-28 21:18:29 +00001544 if (!isInterestingIdentifier(II)) {
1545 clang::io::Emit32(Out, ID << 1);
1546 return;
1547 }
Douglas Gregor5998da52009-04-28 21:32:13 +00001548
Douglas Gregora92193e2009-04-28 21:18:29 +00001549 clang::io::Emit32(Out, (ID << 1) | 0x01);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001550 uint32_t Bits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001551 bool hasMacroDefinition =
1552 II->hasMacroDefinition() &&
Douglas Gregor37e26842009-04-21 23:56:24 +00001553 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
Douglas Gregor5998da52009-04-28 21:32:13 +00001554 Bits = (uint32_t)II->getObjCOrBuiltinID();
Douglas Gregor2deaea32009-04-22 18:49:13 +00001555 Bits = (Bits << 1) | hasMacroDefinition;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001556 Bits = (Bits << 1) | II->isExtensionToken();
1557 Bits = (Bits << 1) | II->isPoisoned();
1558 Bits = (Bits << 1) | II->isCPlusPlusOperatorKeyword();
Douglas Gregor5998da52009-04-28 21:32:13 +00001559 clang::io::Emit16(Out, Bits);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001560
Douglas Gregor37e26842009-04-21 23:56:24 +00001561 if (hasMacroDefinition)
Douglas Gregor5998da52009-04-28 21:32:13 +00001562 clang::io::Emit32(Out, Writer.getMacroOffset(II));
Douglas Gregor37e26842009-04-21 23:56:24 +00001563
Douglas Gregor668c1a42009-04-21 22:25:48 +00001564 // Emit the declaration IDs in reverse order, because the
1565 // IdentifierResolver provides the declarations as they would be
1566 // visible (e.g., the function "stat" would come before the struct
1567 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1568 // adds declarations to the end of the list (so we need to see the
1569 // struct "status" before the function "status").
Mike Stump1eb44332009-09-09 15:08:12 +00001570 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
Douglas Gregor668c1a42009-04-21 22:25:48 +00001571 IdentifierResolver::end());
1572 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1573 DEnd = Decls.rend();
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001574 D != DEnd; ++D)
Douglas Gregor668c1a42009-04-21 22:25:48 +00001575 clang::io::Emit32(Out, Writer.getDeclID(*D));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001576 }
1577};
1578} // end anonymous namespace
1579
Douglas Gregorafaf3082009-04-11 00:14:32 +00001580/// \brief Write the identifier table into the PCH file.
1581///
1582/// The identifier table consists of a blob containing string data
1583/// (the actual identifiers themselves) and a separate "offsets" index
1584/// that maps identifier IDs to locations within the blob.
Douglas Gregor37e26842009-04-21 23:56:24 +00001585void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001586 using namespace llvm;
1587
1588 // Create and write out the blob that contains the identifier
1589 // strings.
Douglas Gregorafaf3082009-04-11 00:14:32 +00001590 {
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001591 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor92b059e2009-04-28 20:33:11 +00001593 // Look for any identifiers that were named while processing the
1594 // headers, but are otherwise not needed. We add these to the hash
1595 // table to enable checking of the predefines buffer in the case
1596 // where the user adds new macro definitions when building the PCH
1597 // file.
1598 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1599 IDEnd = PP.getIdentifierTable().end();
1600 ID != IDEnd; ++ID)
1601 getIdentifierRef(ID->second);
1602
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001603 // Create the on-disk hash table representation.
Douglas Gregor92b059e2009-04-28 20:33:11 +00001604 IdentifierOffsets.resize(IdentifierIDs.size());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001605 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1606 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1607 ID != IDEnd; ++ID) {
1608 assert(ID->first && "NULL identifier in identifier table");
Douglas Gregor02fc7512009-04-28 20:01:51 +00001609 Generator.insert(ID->first, ID->second);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001610 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001611
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001612 // Create the on-disk hash table in a buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001613 llvm::SmallString<4096> IdentifierTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001614 uint32_t BucketOffset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001615 {
Douglas Gregor37e26842009-04-21 23:56:24 +00001616 PCHIdentifierTableTrait Trait(*this, PP);
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001617 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001618 // Make sure that no bucket is at offset 0
Douglas Gregora67e58c2009-04-24 21:49:02 +00001619 clang::io::Emit32(Out, 0);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001620 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001621 }
1622
1623 // Create a blob abbreviation
1624 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1625 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001626 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001627 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregorc9490c02009-04-16 22:23:12 +00001628 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001629
1630 // Write the identifier table
1631 RecordData Record;
1632 Record.push_back(pch::IDENTIFIER_TABLE);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001633 Record.push_back(BucketOffset);
Daniel Dunbarec312a12009-08-24 09:31:37 +00001634 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
Douglas Gregorafaf3082009-04-11 00:14:32 +00001635 }
1636
1637 // Write the offsets table for identifier IDs.
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001638 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1639 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1640 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1641 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1642 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1643
1644 RecordData Record;
1645 Record.push_back(pch::IDENTIFIER_OFFSET);
1646 Record.push_back(IdentifierOffsets.size());
1647 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1648 (const char *)&IdentifierOffsets.front(),
1649 IdentifierOffsets.size() * sizeof(uint32_t));
Douglas Gregorafaf3082009-04-11 00:14:32 +00001650}
1651
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001652//===----------------------------------------------------------------------===//
1653// General Serialization Routines
1654//===----------------------------------------------------------------------===//
1655
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001656/// \brief Write a record containing the given attributes.
1657void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1658 RecordData Record;
1659 for (; Attr; Attr = Attr->getNext()) {
1660 Record.push_back(Attr->getKind()); // FIXME: stable encoding
1661 Record.push_back(Attr->isInherited());
1662 switch (Attr->getKind()) {
1663 case Attr::Alias:
1664 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1665 break;
1666
1667 case Attr::Aligned:
1668 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1669 break;
1670
1671 case Attr::AlwaysInline:
1672 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001674 case Attr::AnalyzerNoReturn:
1675 break;
1676
1677 case Attr::Annotate:
1678 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1679 break;
1680
1681 case Attr::AsmLabel:
1682 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1683 break;
1684
1685 case Attr::Blocks:
1686 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1687 break;
1688
1689 case Attr::Cleanup:
1690 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1691 break;
1692
1693 case Attr::Const:
1694 break;
1695
1696 case Attr::Constructor:
1697 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1698 break;
1699
1700 case Attr::DLLExport:
1701 case Attr::DLLImport:
1702 case Attr::Deprecated:
1703 break;
1704
1705 case Attr::Destructor:
1706 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1707 break;
1708
1709 case Attr::FastCall:
1710 break;
1711
1712 case Attr::Format: {
1713 const FormatAttr *Format = cast<FormatAttr>(Attr);
1714 AddString(Format->getType(), Record);
1715 Record.push_back(Format->getFormatIdx());
1716 Record.push_back(Format->getFirstArg());
1717 break;
1718 }
1719
Fariborz Jahanian5b160922009-05-20 17:41:43 +00001720 case Attr::FormatArg: {
1721 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1722 Record.push_back(Format->getFormatIdx());
1723 break;
1724 }
1725
Fariborz Jahanian5b530052009-05-13 18:09:35 +00001726 case Attr::Sentinel : {
1727 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1728 Record.push_back(Sentinel->getSentinel());
1729 Record.push_back(Sentinel->getNullPos());
1730 break;
1731 }
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Chris Lattnercf2a7212009-04-20 19:12:28 +00001733 case Attr::GNUInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001734 case Attr::IBOutletKind:
Ryan Flynn76168e22009-08-09 20:07:29 +00001735 case Attr::Malloc:
Mike Stump1feade82009-08-26 22:31:08 +00001736 case Attr::NoDebug:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001737 case Attr::NoReturn:
1738 case Attr::NoThrow:
Mike Stump1feade82009-08-26 22:31:08 +00001739 case Attr::NoInline:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001740 break;
1741
1742 case Attr::NonNull: {
1743 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1744 Record.push_back(NonNull->size());
1745 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1746 break;
1747 }
1748
1749 case Attr::ObjCException:
1750 case Attr::ObjCNSObject:
Ted Kremenekb71368d2009-05-09 02:44:38 +00001751 case Attr::CFReturnsRetained:
1752 case Attr::NSReturnsRetained:
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001753 case Attr::Overloadable:
1754 break;
1755
Anders Carlssona860e752009-08-08 18:23:56 +00001756 case Attr::PragmaPack:
1757 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001758 break;
1759
Anders Carlssona860e752009-08-08 18:23:56 +00001760 case Attr::Packed:
1761 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001763 case Attr::Pure:
1764 break;
1765
1766 case Attr::Regparm:
1767 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1768 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Nate Begeman6f3d8382009-06-26 06:32:41 +00001770 case Attr::ReqdWorkGroupSize:
1771 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1772 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1773 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1774 break;
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001775
1776 case Attr::Section:
1777 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1778 break;
1779
1780 case Attr::StdCall:
1781 case Attr::TransparentUnion:
1782 case Attr::Unavailable:
1783 case Attr::Unused:
1784 case Attr::Used:
1785 break;
1786
1787 case Attr::Visibility:
1788 // FIXME: stable encoding
Mike Stump1eb44332009-09-09 15:08:12 +00001789 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001790 break;
1791
1792 case Attr::WarnUnusedResult:
1793 case Attr::Weak:
1794 case Attr::WeakImport:
1795 break;
1796 }
1797 }
1798
Douglas Gregorc9490c02009-04-16 22:23:12 +00001799 Stream.EmitRecord(pch::DECL_ATTR, Record);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00001800}
1801
1802void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1803 Record.push_back(Str.size());
1804 Record.insert(Record.end(), Str.begin(), Str.end());
1805}
1806
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001807/// \brief Note that the identifier II occurs at the given offset
1808/// within the identifier table.
1809void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001810 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
Douglas Gregor3251ceb2009-04-20 20:36:09 +00001811}
1812
Douglas Gregor83941df2009-04-25 17:48:32 +00001813/// \brief Note that the selector Sel occurs at the given offset
1814/// within the method pool/selector table.
1815void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1816 unsigned ID = SelectorIDs[Sel];
1817 assert(ID && "Unknown selector");
1818 SelectorOffsets[ID - 1] = Offset;
1819}
1820
Mike Stump1eb44332009-09-09 15:08:12 +00001821PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1822 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
Douglas Gregor25123082009-04-22 22:34:57 +00001823 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1824 NumVisibleDeclContexts(0) { }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001825
Douglas Gregore650c8c2009-07-07 00:12:59 +00001826void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1827 const char *isysroot) {
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001828 using namespace llvm;
1829
Douglas Gregore7785042009-04-20 15:53:59 +00001830 ASTContext &Context = SemaRef.Context;
1831 Preprocessor &PP = SemaRef.PP;
1832
Douglas Gregor2cf26342009-04-09 22:27:44 +00001833 // Emit the file header.
Douglas Gregorc9490c02009-04-16 22:23:12 +00001834 Stream.Emit((unsigned)'C', 8);
1835 Stream.Emit((unsigned)'P', 8);
1836 Stream.Emit((unsigned)'C', 8);
1837 Stream.Emit((unsigned)'H', 8);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Chris Lattnerb145b1e2009-04-26 22:26:21 +00001839 WriteBlockInfoBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001840
1841 // The translation unit is the first declaration we'll emit.
1842 DeclIDs[Context.getTranslationUnitDecl()] = 1;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001843 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001844
Douglas Gregor2deaea32009-04-22 18:49:13 +00001845 // Make sure that we emit IdentifierInfos (and any attached
1846 // declarations) for builtins.
1847 {
1848 IdentifierTable &Table = PP.getIdentifierTable();
1849 llvm::SmallVector<const char *, 32> BuiltinNames;
1850 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1851 Context.getLangOptions().NoBuiltin);
1852 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1853 getIdentifierRef(&Table.get(BuiltinNames[I]));
1854 }
1855
Chris Lattner63d65f82009-09-08 18:19:27 +00001856 // Build a record containing all of the tentative definitions in this file, in
1857 // TentativeDefinitionList order. Generally, this record will be empty for
1858 // headers.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001859 RecordData TentativeDefinitions;
Chris Lattner63d65f82009-09-08 18:19:27 +00001860 for (unsigned i = 0, e = SemaRef.TentativeDefinitionList.size(); i != e; ++i){
1861 VarDecl *VD =
1862 SemaRef.TentativeDefinitions.lookup(SemaRef.TentativeDefinitionList[i]);
1863 if (VD) AddDeclRef(VD, TentativeDefinitions);
1864 }
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001865
Douglas Gregor14c22f22009-04-22 22:18:58 +00001866 // Build a record containing all of the locally-scoped external
1867 // declarations in this header file. Generally, this record will be
1868 // empty.
1869 RecordData LocallyScopedExternalDecls;
Chris Lattner63d65f82009-09-08 18:19:27 +00001870 // FIXME: This is filling in the PCH file in densemap order which is
1871 // nondeterminstic!
Mike Stump1eb44332009-09-09 15:08:12 +00001872 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
Douglas Gregor14c22f22009-04-22 22:18:58 +00001873 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1874 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1875 TD != TDEnd; ++TD)
1876 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1877
Douglas Gregorb81c1702009-04-27 20:06:05 +00001878 // Build a record containing all of the ext_vector declarations.
1879 RecordData ExtVectorDecls;
1880 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1881 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
1882
Douglas Gregor2cf26342009-04-09 22:27:44 +00001883 // Write the remaining PCH contents.
Douglas Gregorad1de002009-04-18 05:55:16 +00001884 RecordData Record;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001885 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001886 WriteMetadata(Context, isysroot);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001887 WriteLanguageOptions(Context.getLangOptions());
Douglas Gregore650c8c2009-07-07 00:12:59 +00001888 if (StatCalls && !isysroot)
1889 WriteStatCache(*StatCalls, isysroot);
1890 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
Mike Stump1eb44332009-09-09 15:08:12 +00001891 WriteComments(Context);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001892 // Write the record of special types.
1893 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001895 AddTypeRef(Context.getBuiltinVaListType(), Record);
1896 AddTypeRef(Context.getObjCIdType(), Record);
1897 AddTypeRef(Context.getObjCSelType(), Record);
1898 AddTypeRef(Context.getObjCProtoType(), Record);
1899 AddTypeRef(Context.getObjCClassType(), Record);
1900 AddTypeRef(Context.getRawCFConstantStringType(), Record);
1901 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
1902 AddTypeRef(Context.getFILEType(), Record);
Mike Stump782fa302009-07-28 02:25:19 +00001903 AddTypeRef(Context.getjmp_bufType(), Record);
1904 AddTypeRef(Context.getsigjmp_bufType(), Record);
Douglas Gregord1571ac2009-08-21 00:27:50 +00001905 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
1906 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001907 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor366809a2009-04-26 03:49:13 +00001909 // Keep writing types and declarations until all types and
1910 // declarations have been written.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001911 Stream.EnterSubblock(pch::DECLTYPES_BLOCK_ID, 3);
1912 WriteDeclsBlockAbbrevs();
1913 while (!DeclTypesToEmit.empty()) {
1914 DeclOrType DOT = DeclTypesToEmit.front();
1915 DeclTypesToEmit.pop();
1916 if (DOT.isType())
1917 WriteType(DOT.getType());
1918 else
1919 WriteDecl(Context, DOT.getDecl());
1920 }
1921 Stream.ExitBlock();
1922
Douglas Gregor813a97b2009-10-17 17:25:45 +00001923 WritePreprocessor(PP);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001924 WriteMethodPool(SemaRef);
Douglas Gregor37e26842009-04-21 23:56:24 +00001925 WriteIdentifierTable(PP);
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001926
1927 // Write the type offsets array
1928 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1929 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
1930 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
1931 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
1932 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1933 Record.clear();
1934 Record.push_back(pch::TYPE_OFFSET);
1935 Record.push_back(TypeOffsets.size());
1936 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001937 (const char *)&TypeOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001938 TypeOffsets.size() * sizeof(TypeOffsets[0]));
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001940 // Write the declaration offsets array
1941 Abbrev = new BitCodeAbbrev();
1942 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
1943 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
1944 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
1945 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1946 Record.clear();
1947 Record.push_back(pch::DECL_OFFSET);
1948 Record.push_back(DeclOffsets.size());
1949 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
Mike Stump1eb44332009-09-09 15:08:12 +00001950 (const char *)&DeclOffsets.front(),
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001951 DeclOffsets.size() * sizeof(DeclOffsets[0]));
Douglas Gregorad1de002009-04-18 05:55:16 +00001952
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001953 // Write the record containing external, unnamed definitions.
Douglas Gregorfdd01722009-04-14 00:24:19 +00001954 if (!ExternalDefinitions.empty())
Douglas Gregorc9490c02009-04-16 22:23:12 +00001955 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001956
1957 // Write the record containing tentative definitions.
1958 if (!TentativeDefinitions.empty())
1959 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregor14c22f22009-04-22 22:18:58 +00001960
1961 // Write the record containing locally-scoped external definitions.
1962 if (!LocallyScopedExternalDecls.empty())
Mike Stump1eb44332009-09-09 15:08:12 +00001963 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
Douglas Gregor14c22f22009-04-22 22:18:58 +00001964 LocallyScopedExternalDecls);
Douglas Gregorb81c1702009-04-27 20:06:05 +00001965
1966 // Write the record containing ext_vector type names.
1967 if (!ExtVectorDecls.empty())
1968 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Douglas Gregor3e1af842009-04-17 22:13:46 +00001970 // Some simple statistics
Douglas Gregorad1de002009-04-18 05:55:16 +00001971 Record.clear();
Douglas Gregor3e1af842009-04-17 22:13:46 +00001972 Record.push_back(NumStatements);
Douglas Gregor37e26842009-04-21 23:56:24 +00001973 Record.push_back(NumMacros);
Douglas Gregor25123082009-04-22 22:34:57 +00001974 Record.push_back(NumLexicalDeclContexts);
1975 Record.push_back(NumVisibleDeclContexts);
Douglas Gregor3e1af842009-04-17 22:13:46 +00001976 Stream.EmitRecord(pch::STATISTICS, Record);
Douglas Gregorc9490c02009-04-16 22:23:12 +00001977 Stream.ExitBlock();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978}
1979
1980void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
1981 Record.push_back(Loc.getRawEncoding());
1982}
1983
1984void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
1985 Record.push_back(Value.getBitWidth());
1986 unsigned N = Value.getNumWords();
1987 const uint64_t* Words = Value.getRawData();
1988 for (unsigned I = 0; I != N; ++I)
1989 Record.push_back(Words[I]);
1990}
1991
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001992void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
1993 Record.push_back(Value.isUnsigned());
1994 AddAPInt(Value, Record);
1995}
1996
Douglas Gregor17fc2232009-04-14 21:55:33 +00001997void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
1998 AddAPInt(Value.bitcastToAPInt(), Record);
1999}
2000
Douglas Gregor2cf26342009-04-09 22:27:44 +00002001void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
Douglas Gregor2deaea32009-04-22 18:49:13 +00002002 Record.push_back(getIdentifierRef(II));
2003}
2004
2005pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
2006 if (II == 0)
2007 return 0;
Douglas Gregorafaf3082009-04-11 00:14:32 +00002008
2009 pch::IdentID &ID = IdentifierIDs[II];
2010 if (ID == 0)
2011 ID = IdentifierIDs.size();
Douglas Gregor2deaea32009-04-22 18:49:13 +00002012 return ID;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002013}
2014
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002015void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
2016 if (SelRef.getAsOpaquePtr() == 0) {
2017 Record.push_back(0);
2018 return;
2019 }
2020
2021 pch::SelectorID &SID = SelectorIDs[SelRef];
2022 if (SID == 0) {
2023 SID = SelectorIDs.size();
2024 SelVector.push_back(SelRef);
2025 }
2026 Record.push_back(SID);
2027}
2028
John McCalla1ee0c52009-10-16 21:56:05 +00002029void PCHWriter::AddDeclaratorInfo(DeclaratorInfo *DInfo, RecordData &Record) {
2030 if (DInfo == 0) {
2031 AddTypeRef(QualType(), Record);
2032 return;
2033 }
2034
2035 AddTypeRef(DInfo->getTypeLoc().getSourceType(), Record);
2036 TypeLocWriter TLW(*this, Record);
2037 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2038 TLW.Visit(TL);
2039}
2040
Douglas Gregor2cf26342009-04-09 22:27:44 +00002041void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
2042 if (T.isNull()) {
2043 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
2044 return;
2045 }
2046
John McCall0953e762009-09-24 19:53:00 +00002047 unsigned FastQuals = T.getFastQualifiers();
2048 T.removeFastQualifiers();
2049
2050 if (T.hasNonFastQualifiers()) {
2051 pch::TypeID &ID = TypeIDs[T];
2052 if (ID == 0) {
2053 // We haven't seen these qualifiers applied to this type before.
2054 // Assign it a new ID. This is the only time we enqueue a
2055 // qualified type, and it has no CV qualifiers.
2056 ID = NextTypeID++;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002057 DeclTypesToEmit.push(T);
John McCall0953e762009-09-24 19:53:00 +00002058 }
2059
2060 // Encode the type qualifiers in the type reference.
2061 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2062 return;
2063 }
2064
2065 assert(!T.hasQualifiers());
2066
Douglas Gregor2cf26342009-04-09 22:27:44 +00002067 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002068 pch::TypeID ID = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002069 switch (BT->getKind()) {
2070 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2071 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2072 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2073 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2074 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2075 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2076 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2077 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002078 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002079 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2080 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2081 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2082 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2083 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2084 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2085 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002086 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002087 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2088 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2089 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002090 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002091 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2092 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002093 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2094 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002095 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2096 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
Anders Carlssone89d1592009-06-26 18:41:36 +00002097 case BuiltinType::UndeducedAuto:
2098 assert(0 && "Should not see undeduced auto here");
2099 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002100 }
2101
John McCall0953e762009-09-24 19:53:00 +00002102 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002103 return;
2104 }
2105
John McCall0953e762009-09-24 19:53:00 +00002106 pch::TypeID &ID = TypeIDs[T];
Douglas Gregor366809a2009-04-26 03:49:13 +00002107 if (ID == 0) {
2108 // We haven't seen this type before. Assign it a new ID and put it
John McCall0953e762009-09-24 19:53:00 +00002109 // into the queue of types to emit.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002110 ID = NextTypeID++;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002111 DeclTypesToEmit.push(T);
Douglas Gregor366809a2009-04-26 03:49:13 +00002112 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002113
2114 // Encode the type qualifiers in the type reference.
John McCall0953e762009-09-24 19:53:00 +00002115 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002116}
2117
2118void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2119 if (D == 0) {
2120 Record.push_back(0);
2121 return;
2122 }
2123
Douglas Gregor8038d512009-04-10 17:25:41 +00002124 pch::DeclID &ID = DeclIDs[D];
Mike Stump1eb44332009-09-09 15:08:12 +00002125 if (ID == 0) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002126 // We haven't seen this declaration before. Give it a new ID and
2127 // enqueue it in the list of declarations to emit.
2128 ID = DeclIDs.size();
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002129 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002130 }
2131
2132 Record.push_back(ID);
2133}
2134
Douglas Gregor3251ceb2009-04-20 20:36:09 +00002135pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2136 if (D == 0)
2137 return 0;
2138
2139 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2140 return DeclIDs[D];
2141}
2142
Douglas Gregor2cf26342009-04-09 22:27:44 +00002143void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
Chris Lattnerea5ce472009-04-27 07:35:58 +00002144 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregor2cf26342009-04-09 22:27:44 +00002145 Record.push_back(Name.getNameKind());
2146 switch (Name.getNameKind()) {
2147 case DeclarationName::Identifier:
2148 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2149 break;
2150
2151 case DeclarationName::ObjCZeroArgSelector:
2152 case DeclarationName::ObjCOneArgSelector:
2153 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002154 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002155 break;
2156
2157 case DeclarationName::CXXConstructorName:
2158 case DeclarationName::CXXDestructorName:
2159 case DeclarationName::CXXConversionFunctionName:
2160 AddTypeRef(Name.getCXXNameType(), Record);
2161 break;
2162
2163 case DeclarationName::CXXOperatorName:
2164 Record.push_back(Name.getCXXOverloadedOperator());
2165 break;
2166
2167 case DeclarationName::CXXUsingDirective:
2168 // No extra data to emit
2169 break;
2170 }
2171}
Douglas Gregor0b748912009-04-14 21:18:50 +00002172