blob: 45d9b1baced0d6d6642dd27811fdc32309c3011a [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- 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"
15#include "../Sema/Sema.h" // FIXME: move header into include/clang/Sema
16#include "../Sema/IdentifierResolver.h" // FIXME: move header
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclContextInternals.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeLocVisitor.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Lex/HeaderSearch.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/OnDiskHashTable.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/Version.h"
32#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Bitcode/BitstreamWriter.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/System/Path.h"
38#include <cstdio>
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// Type serialization
43//===----------------------------------------------------------------------===//
44
45namespace {
46 class PCHTypeWriter {
47 PCHWriter &Writer;
48 PCHWriter::RecordData &Record;
49
50 public:
51 /// \brief Type code that corresponds to the record generated.
52 pch::TypeCode Code;
53
54 PCHTypeWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
55 : Writer(Writer), Record(Record), Code(pch::TYPE_EXT_QUAL) { }
56
57 void VisitArrayType(const ArrayType *T);
58 void VisitFunctionType(const FunctionType *T);
59 void VisitTagType(const TagType *T);
60
61#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
62#define ABSTRACT_TYPE(Class, Base)
63#define DEPENDENT_TYPE(Class, Base)
64#include "clang/AST/TypeNodes.def"
65 };
66}
67
68void PCHTypeWriter::VisitBuiltinType(const BuiltinType *T) {
69 assert(false && "Built-in types are never serialized");
70}
71
72void PCHTypeWriter::VisitComplexType(const ComplexType *T) {
73 Writer.AddTypeRef(T->getElementType(), Record);
74 Code = pch::TYPE_COMPLEX;
75}
76
77void PCHTypeWriter::VisitPointerType(const PointerType *T) {
78 Writer.AddTypeRef(T->getPointeeType(), Record);
79 Code = pch::TYPE_POINTER;
80}
81
82void PCHTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
83 Writer.AddTypeRef(T->getPointeeType(), Record);
84 Code = pch::TYPE_BLOCK_POINTER;
85}
86
87void PCHTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
88 Writer.AddTypeRef(T->getPointeeType(), Record);
89 Code = pch::TYPE_LVALUE_REFERENCE;
90}
91
92void PCHTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
93 Writer.AddTypeRef(T->getPointeeType(), Record);
94 Code = pch::TYPE_RVALUE_REFERENCE;
95}
96
97void PCHTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
98 Writer.AddTypeRef(T->getPointeeType(), Record);
99 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
100 Code = pch::TYPE_MEMBER_POINTER;
101}
102
103void PCHTypeWriter::VisitArrayType(const ArrayType *T) {
104 Writer.AddTypeRef(T->getElementType(), Record);
105 Record.push_back(T->getSizeModifier()); // FIXME: stable values
106 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
107}
108
109void PCHTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
110 VisitArrayType(T);
111 Writer.AddAPInt(T->getSize(), Record);
112 Code = pch::TYPE_CONSTANT_ARRAY;
113}
114
115void PCHTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
116 VisitArrayType(T);
117 Code = pch::TYPE_INCOMPLETE_ARRAY;
118}
119
120void PCHTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
121 VisitArrayType(T);
122 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
123 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
124 Writer.AddStmt(T->getSizeExpr());
125 Code = pch::TYPE_VARIABLE_ARRAY;
126}
127
128void PCHTypeWriter::VisitVectorType(const VectorType *T) {
129 Writer.AddTypeRef(T->getElementType(), Record);
130 Record.push_back(T->getNumElements());
131 Record.push_back(T->isAltiVec());
132 Record.push_back(T->isPixel());
133 Code = pch::TYPE_VECTOR;
134}
135
136void PCHTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
137 VisitVectorType(T);
138 Code = pch::TYPE_EXT_VECTOR;
139}
140
141void PCHTypeWriter::VisitFunctionType(const FunctionType *T) {
142 Writer.AddTypeRef(T->getResultType(), Record);
143 Record.push_back(T->getNoReturnAttr());
144 // FIXME: need to stabilize encoding of calling convention...
145 Record.push_back(T->getCallConv());
146}
147
148void PCHTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
149 VisitFunctionType(T);
150 Code = pch::TYPE_FUNCTION_NO_PROTO;
151}
152
153void PCHTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
154 VisitFunctionType(T);
155 Record.push_back(T->getNumArgs());
156 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
157 Writer.AddTypeRef(T->getArgType(I), Record);
158 Record.push_back(T->isVariadic());
159 Record.push_back(T->getTypeQuals());
160 Record.push_back(T->hasExceptionSpec());
161 Record.push_back(T->hasAnyExceptionSpec());
162 Record.push_back(T->getNumExceptions());
163 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
164 Writer.AddTypeRef(T->getExceptionType(I), Record);
165 Code = pch::TYPE_FUNCTION_PROTO;
166}
167
168#if 0
169// For when we want it....
170void PCHTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
171 Writer.AddDeclRef(T->getDecl(), Record);
172 Code = pch::TYPE_UNRESOLVED_USING;
173}
174#endif
175
176void PCHTypeWriter::VisitTypedefType(const TypedefType *T) {
177 Writer.AddDeclRef(T->getDecl(), Record);
178 Code = pch::TYPE_TYPEDEF;
179}
180
181void PCHTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
182 Writer.AddStmt(T->getUnderlyingExpr());
183 Code = pch::TYPE_TYPEOF_EXPR;
184}
185
186void PCHTypeWriter::VisitTypeOfType(const TypeOfType *T) {
187 Writer.AddTypeRef(T->getUnderlyingType(), Record);
188 Code = pch::TYPE_TYPEOF;
189}
190
191void PCHTypeWriter::VisitDecltypeType(const DecltypeType *T) {
192 Writer.AddStmt(T->getUnderlyingExpr());
193 Code = pch::TYPE_DECLTYPE;
194}
195
196void PCHTypeWriter::VisitTagType(const TagType *T) {
197 Writer.AddDeclRef(T->getDecl(), Record);
198 assert(!T->isBeingDefined() &&
199 "Cannot serialize in the middle of a type definition");
200}
201
202void PCHTypeWriter::VisitRecordType(const RecordType *T) {
203 VisitTagType(T);
204 Code = pch::TYPE_RECORD;
205}
206
207void PCHTypeWriter::VisitEnumType(const EnumType *T) {
208 VisitTagType(T);
209 Code = pch::TYPE_ENUM;
210}
211
212void PCHTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
213 Writer.AddTypeRef(T->getUnderlyingType(), Record);
214 Record.push_back(T->getTagKind());
215 Code = pch::TYPE_ELABORATED;
216}
217
218void
219PCHTypeWriter::VisitSubstTemplateTypeParmType(
220 const SubstTemplateTypeParmType *T) {
221 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
222 Writer.AddTypeRef(T->getReplacementType(), Record);
223 Code = pch::TYPE_SUBST_TEMPLATE_TYPE_PARM;
224}
225
226void
227PCHTypeWriter::VisitTemplateSpecializationType(
228 const TemplateSpecializationType *T) {
229 // FIXME: Serialize this type (C++ only)
230 assert(false && "Cannot serialize template specialization types");
231}
232
233void PCHTypeWriter::VisitQualifiedNameType(const QualifiedNameType *T) {
234 // FIXME: Serialize this type (C++ only)
235 assert(false && "Cannot serialize qualified name types");
236}
237
238void PCHTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
239 Writer.AddDeclRef(T->getDecl(), Record);
240 Record.push_back(T->getNumProtocols());
241 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
242 E = T->qual_end(); I != E; ++I)
243 Writer.AddDeclRef(*I, Record);
244 Code = pch::TYPE_OBJC_INTERFACE;
245}
246
247void
248PCHTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
249 Writer.AddTypeRef(T->getPointeeType(), Record);
250 Record.push_back(T->getNumProtocols());
251 for (ObjCInterfaceType::qual_iterator I = T->qual_begin(),
252 E = T->qual_end(); I != E; ++I)
253 Writer.AddDeclRef(*I, Record);
254 Code = pch::TYPE_OBJC_OBJECT_POINTER;
255}
256
257namespace {
258
259class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
260 PCHWriter &Writer;
261 PCHWriter::RecordData &Record;
262
263public:
264 TypeLocWriter(PCHWriter &Writer, PCHWriter::RecordData &Record)
265 : Writer(Writer), Record(Record) { }
266
267#define ABSTRACT_TYPELOC(CLASS, PARENT)
268#define TYPELOC(CLASS, PARENT) \
269 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
270#include "clang/AST/TypeLocNodes.def"
271
272 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
273 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
274};
275
276}
277
278void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
279 // nothing to do
280}
281void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
282 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
283 if (TL.needsExtraLocalData()) {
284 Record.push_back(TL.getWrittenTypeSpec());
285 Record.push_back(TL.getWrittenSignSpec());
286 Record.push_back(TL.getWrittenWidthSpec());
287 Record.push_back(TL.hasModeAttr());
288 }
289}
290void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
291 Writer.AddSourceLocation(TL.getNameLoc(), Record);
292}
293void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
294 Writer.AddSourceLocation(TL.getStarLoc(), Record);
295}
296void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
297 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
298}
299void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
300 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
301}
302void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
303 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
304}
305void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
306 Writer.AddSourceLocation(TL.getStarLoc(), Record);
307}
308void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
309 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
310 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
311 Record.push_back(TL.getSizeExpr() ? 1 : 0);
312 if (TL.getSizeExpr())
313 Writer.AddStmt(TL.getSizeExpr());
314}
315void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
316 VisitArrayTypeLoc(TL);
317}
318void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
319 VisitArrayTypeLoc(TL);
320}
321void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
322 VisitArrayTypeLoc(TL);
323}
324void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
325 DependentSizedArrayTypeLoc TL) {
326 VisitArrayTypeLoc(TL);
327}
328void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
329 DependentSizedExtVectorTypeLoc TL) {
330 Writer.AddSourceLocation(TL.getNameLoc(), Record);
331}
332void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
333 Writer.AddSourceLocation(TL.getNameLoc(), Record);
334}
335void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
336 Writer.AddSourceLocation(TL.getNameLoc(), Record);
337}
338void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
339 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
340 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
341 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
342 Writer.AddDeclRef(TL.getArg(i), Record);
343}
344void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
345 VisitFunctionTypeLoc(TL);
346}
347void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
348 VisitFunctionTypeLoc(TL);
349}
350void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
351 Writer.AddSourceLocation(TL.getNameLoc(), Record);
352}
353void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
354 Writer.AddSourceLocation(TL.getNameLoc(), Record);
355}
356void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
357 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
358 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
359 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
360}
361void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
362 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
363 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
364 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
365 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
366}
367void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
368 Writer.AddSourceLocation(TL.getNameLoc(), Record);
369}
370void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
371 Writer.AddSourceLocation(TL.getNameLoc(), Record);
372}
373void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
374 Writer.AddSourceLocation(TL.getNameLoc(), Record);
375}
376void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
377 Writer.AddSourceLocation(TL.getNameLoc(), Record);
378}
379void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
380 Writer.AddSourceLocation(TL.getNameLoc(), Record);
381}
382void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
383 SubstTemplateTypeParmTypeLoc TL) {
384 Writer.AddSourceLocation(TL.getNameLoc(), Record);
385}
386void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
387 TemplateSpecializationTypeLoc TL) {
388 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
389 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
390 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
391 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
392 Writer.AddTemplateArgumentLoc(TL.getArgLoc(i), Record);
393}
394void TypeLocWriter::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
395 Writer.AddSourceLocation(TL.getNameLoc(), Record);
396}
397void TypeLocWriter::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
398 Writer.AddSourceLocation(TL.getNameLoc(), Record);
399}
400void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
401 Writer.AddSourceLocation(TL.getNameLoc(), Record);
402 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
403 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
404 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
405 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
406}
407void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
408 Writer.AddSourceLocation(TL.getStarLoc(), Record);
409 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
410 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
411 Record.push_back(TL.hasBaseTypeAsWritten());
412 Record.push_back(TL.hasProtocolsAsWritten());
413 if (TL.hasProtocolsAsWritten())
414 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
415 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
416}
417
418//===----------------------------------------------------------------------===//
419// PCHWriter Implementation
420//===----------------------------------------------------------------------===//
421
422static void EmitBlockID(unsigned ID, const char *Name,
423 llvm::BitstreamWriter &Stream,
424 PCHWriter::RecordData &Record) {
425 Record.clear();
426 Record.push_back(ID);
427 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
428
429 // Emit the block name if present.
430 if (Name == 0 || Name[0] == 0) return;
431 Record.clear();
432 while (*Name)
433 Record.push_back(*Name++);
434 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
435}
436
437static void EmitRecordID(unsigned ID, const char *Name,
438 llvm::BitstreamWriter &Stream,
439 PCHWriter::RecordData &Record) {
440 Record.clear();
441 Record.push_back(ID);
442 while (*Name)
443 Record.push_back(*Name++);
444 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
445}
446
447static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
448 PCHWriter::RecordData &Record) {
449#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
450 RECORD(STMT_STOP);
451 RECORD(STMT_NULL_PTR);
452 RECORD(STMT_NULL);
453 RECORD(STMT_COMPOUND);
454 RECORD(STMT_CASE);
455 RECORD(STMT_DEFAULT);
456 RECORD(STMT_LABEL);
457 RECORD(STMT_IF);
458 RECORD(STMT_SWITCH);
459 RECORD(STMT_WHILE);
460 RECORD(STMT_DO);
461 RECORD(STMT_FOR);
462 RECORD(STMT_GOTO);
463 RECORD(STMT_INDIRECT_GOTO);
464 RECORD(STMT_CONTINUE);
465 RECORD(STMT_BREAK);
466 RECORD(STMT_RETURN);
467 RECORD(STMT_DECL);
468 RECORD(STMT_ASM);
469 RECORD(EXPR_PREDEFINED);
470 RECORD(EXPR_DECL_REF);
471 RECORD(EXPR_INTEGER_LITERAL);
472 RECORD(EXPR_FLOATING_LITERAL);
473 RECORD(EXPR_IMAGINARY_LITERAL);
474 RECORD(EXPR_STRING_LITERAL);
475 RECORD(EXPR_CHARACTER_LITERAL);
476 RECORD(EXPR_PAREN);
477 RECORD(EXPR_UNARY_OPERATOR);
478 RECORD(EXPR_SIZEOF_ALIGN_OF);
479 RECORD(EXPR_ARRAY_SUBSCRIPT);
480 RECORD(EXPR_CALL);
481 RECORD(EXPR_MEMBER);
482 RECORD(EXPR_BINARY_OPERATOR);
483 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
484 RECORD(EXPR_CONDITIONAL_OPERATOR);
485 RECORD(EXPR_IMPLICIT_CAST);
486 RECORD(EXPR_CSTYLE_CAST);
487 RECORD(EXPR_COMPOUND_LITERAL);
488 RECORD(EXPR_EXT_VECTOR_ELEMENT);
489 RECORD(EXPR_INIT_LIST);
490 RECORD(EXPR_DESIGNATED_INIT);
491 RECORD(EXPR_IMPLICIT_VALUE_INIT);
492 RECORD(EXPR_VA_ARG);
493 RECORD(EXPR_ADDR_LABEL);
494 RECORD(EXPR_STMT);
495 RECORD(EXPR_TYPES_COMPATIBLE);
496 RECORD(EXPR_CHOOSE);
497 RECORD(EXPR_GNU_NULL);
498 RECORD(EXPR_SHUFFLE_VECTOR);
499 RECORD(EXPR_BLOCK);
500 RECORD(EXPR_BLOCK_DECL_REF);
501 RECORD(EXPR_OBJC_STRING_LITERAL);
502 RECORD(EXPR_OBJC_ENCODE);
503 RECORD(EXPR_OBJC_SELECTOR_EXPR);
504 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
505 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
506 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
507 RECORD(EXPR_OBJC_KVC_REF_EXPR);
508 RECORD(EXPR_OBJC_MESSAGE_EXPR);
509 RECORD(EXPR_OBJC_SUPER_EXPR);
510 RECORD(STMT_OBJC_FOR_COLLECTION);
511 RECORD(STMT_OBJC_CATCH);
512 RECORD(STMT_OBJC_FINALLY);
513 RECORD(STMT_OBJC_AT_TRY);
514 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
515 RECORD(STMT_OBJC_AT_THROW);
516 RECORD(EXPR_CXX_OPERATOR_CALL);
517 RECORD(EXPR_CXX_CONSTRUCT);
518 RECORD(EXPR_CXX_STATIC_CAST);
519 RECORD(EXPR_CXX_DYNAMIC_CAST);
520 RECORD(EXPR_CXX_REINTERPRET_CAST);
521 RECORD(EXPR_CXX_CONST_CAST);
522 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
523 RECORD(EXPR_CXX_BOOL_LITERAL);
524 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
525#undef RECORD
526}
527
528void PCHWriter::WriteBlockInfoBlock() {
529 RecordData Record;
530 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
531
532#define BLOCK(X) EmitBlockID(pch::X ## _ID, #X, Stream, Record)
533#define RECORD(X) EmitRecordID(pch::X, #X, Stream, Record)
534
535 // PCH Top-Level Block.
536 BLOCK(PCH_BLOCK);
537 RECORD(ORIGINAL_FILE_NAME);
538 RECORD(TYPE_OFFSET);
539 RECORD(DECL_OFFSET);
540 RECORD(LANGUAGE_OPTIONS);
541 RECORD(METADATA);
542 RECORD(IDENTIFIER_OFFSET);
543 RECORD(IDENTIFIER_TABLE);
544 RECORD(EXTERNAL_DEFINITIONS);
545 RECORD(SPECIAL_TYPES);
546 RECORD(STATISTICS);
547 RECORD(TENTATIVE_DEFINITIONS);
548 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
549 RECORD(SELECTOR_OFFSETS);
550 RECORD(METHOD_POOL);
551 RECORD(PP_COUNTER_VALUE);
552 RECORD(SOURCE_LOCATION_OFFSETS);
553 RECORD(SOURCE_LOCATION_PRELOADS);
554 RECORD(STAT_CACHE);
555 RECORD(EXT_VECTOR_DECLS);
556 RECORD(COMMENT_RANGES);
557 RECORD(VERSION_CONTROL_BRANCH_REVISION);
558
559 // SourceManager Block.
560 BLOCK(SOURCE_MANAGER_BLOCK);
561 RECORD(SM_SLOC_FILE_ENTRY);
562 RECORD(SM_SLOC_BUFFER_ENTRY);
563 RECORD(SM_SLOC_BUFFER_BLOB);
564 RECORD(SM_SLOC_INSTANTIATION_ENTRY);
565 RECORD(SM_LINE_TABLE);
566 RECORD(SM_HEADER_FILE_INFO);
567
568 // Preprocessor Block.
569 BLOCK(PREPROCESSOR_BLOCK);
570 RECORD(PP_MACRO_OBJECT_LIKE);
571 RECORD(PP_MACRO_FUNCTION_LIKE);
572 RECORD(PP_TOKEN);
573
574 // Decls and Types block.
575 BLOCK(DECLTYPES_BLOCK);
576 RECORD(TYPE_EXT_QUAL);
577 RECORD(TYPE_COMPLEX);
578 RECORD(TYPE_POINTER);
579 RECORD(TYPE_BLOCK_POINTER);
580 RECORD(TYPE_LVALUE_REFERENCE);
581 RECORD(TYPE_RVALUE_REFERENCE);
582 RECORD(TYPE_MEMBER_POINTER);
583 RECORD(TYPE_CONSTANT_ARRAY);
584 RECORD(TYPE_INCOMPLETE_ARRAY);
585 RECORD(TYPE_VARIABLE_ARRAY);
586 RECORD(TYPE_VECTOR);
587 RECORD(TYPE_EXT_VECTOR);
588 RECORD(TYPE_FUNCTION_PROTO);
589 RECORD(TYPE_FUNCTION_NO_PROTO);
590 RECORD(TYPE_TYPEDEF);
591 RECORD(TYPE_TYPEOF_EXPR);
592 RECORD(TYPE_TYPEOF);
593 RECORD(TYPE_RECORD);
594 RECORD(TYPE_ENUM);
595 RECORD(TYPE_OBJC_INTERFACE);
596 RECORD(TYPE_OBJC_OBJECT_POINTER);
597 RECORD(DECL_ATTR);
598 RECORD(DECL_TRANSLATION_UNIT);
599 RECORD(DECL_TYPEDEF);
600 RECORD(DECL_ENUM);
601 RECORD(DECL_RECORD);
602 RECORD(DECL_ENUM_CONSTANT);
603 RECORD(DECL_FUNCTION);
604 RECORD(DECL_OBJC_METHOD);
605 RECORD(DECL_OBJC_INTERFACE);
606 RECORD(DECL_OBJC_PROTOCOL);
607 RECORD(DECL_OBJC_IVAR);
608 RECORD(DECL_OBJC_AT_DEFS_FIELD);
609 RECORD(DECL_OBJC_CLASS);
610 RECORD(DECL_OBJC_FORWARD_PROTOCOL);
611 RECORD(DECL_OBJC_CATEGORY);
612 RECORD(DECL_OBJC_CATEGORY_IMPL);
613 RECORD(DECL_OBJC_IMPLEMENTATION);
614 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
615 RECORD(DECL_OBJC_PROPERTY);
616 RECORD(DECL_OBJC_PROPERTY_IMPL);
617 RECORD(DECL_FIELD);
618 RECORD(DECL_VAR);
619 RECORD(DECL_IMPLICIT_PARAM);
620 RECORD(DECL_PARM_VAR);
621 RECORD(DECL_FILE_SCOPE_ASM);
622 RECORD(DECL_BLOCK);
623 RECORD(DECL_CONTEXT_LEXICAL);
624 RECORD(DECL_CONTEXT_VISIBLE);
625 // Statements and Exprs can occur in the Decls and Types block.
626 AddStmtsExprs(Stream, Record);
627#undef RECORD
628#undef BLOCK
629 Stream.ExitBlock();
630}
631
632/// \brief Adjusts the given filename to only write out the portion of the
633/// filename that is not part of the system root directory.
634///
635/// \param Filename the file name to adjust.
636///
637/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
638/// the returned filename will be adjusted by this system root.
639///
640/// \returns either the original filename (if it needs no adjustment) or the
641/// adjusted filename (which points into the @p Filename parameter).
642static const char *
643adjustFilenameForRelocatablePCH(const char *Filename, const char *isysroot) {
644 assert(Filename && "No file name to adjust?");
645
646 if (!isysroot)
647 return Filename;
648
649 // Verify that the filename and the system root have the same prefix.
650 unsigned Pos = 0;
651 for (; Filename[Pos] && isysroot[Pos]; ++Pos)
652 if (Filename[Pos] != isysroot[Pos])
653 return Filename; // Prefixes don't match.
654
655 // We hit the end of the filename before we hit the end of the system root.
656 if (!Filename[Pos])
657 return Filename;
658
659 // If the file name has a '/' at the current position, skip over the '/'.
660 // We distinguish sysroot-based includes from absolute includes by the
661 // absence of '/' at the beginning of sysroot-based includes.
662 if (Filename[Pos] == '/')
663 ++Pos;
664
665 return Filename + Pos;
666}
667
668/// \brief Write the PCH metadata (e.g., i686-apple-darwin9).
669void PCHWriter::WriteMetadata(ASTContext &Context, const char *isysroot) {
670 using namespace llvm;
671
672 // Metadata
673 const TargetInfo &Target = Context.Target;
674 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
675 MetaAbbrev->Add(BitCodeAbbrevOp(pch::METADATA));
676 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH major
677 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // PCH minor
678 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
679 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
680 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
681 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
682 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
683
684 RecordData Record;
685 Record.push_back(pch::METADATA);
686 Record.push_back(pch::VERSION_MAJOR);
687 Record.push_back(pch::VERSION_MINOR);
688 Record.push_back(CLANG_VERSION_MAJOR);
689 Record.push_back(CLANG_VERSION_MINOR);
690 Record.push_back(isysroot != 0);
691 const std::string &TripleStr = Target.getTriple().getTriple();
692 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, TripleStr);
693
694 // Original file name
695 SourceManager &SM = Context.getSourceManager();
696 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
697 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
698 FileAbbrev->Add(BitCodeAbbrevOp(pch::ORIGINAL_FILE_NAME));
699 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
700 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
701
702 llvm::sys::Path MainFilePath(MainFile->getName());
703 std::string MainFileName;
704
705 if (!MainFilePath.isAbsolute()) {
706 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
707 P.appendComponent(MainFilePath.str());
708 MainFileName = P.str();
709 } else {
710 MainFileName = MainFilePath.str();
711 }
712
713 const char *MainFileNameStr = MainFileName.c_str();
714 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
715 isysroot);
716 RecordData Record;
717 Record.push_back(pch::ORIGINAL_FILE_NAME);
718 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
719 }
720
721 // Repository branch/version information.
722 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
723 RepoAbbrev->Add(BitCodeAbbrevOp(pch::VERSION_CONTROL_BRANCH_REVISION));
724 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
725 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
726 Record.clear();
727 Record.push_back(pch::VERSION_CONTROL_BRANCH_REVISION);
728 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
729 getClangFullRepositoryVersion());
730}
731
732/// \brief Write the LangOptions structure.
733void PCHWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
734 RecordData Record;
735 Record.push_back(LangOpts.Trigraphs);
736 Record.push_back(LangOpts.BCPLComment); // BCPL-style '//' comments.
737 Record.push_back(LangOpts.DollarIdents); // '$' allowed in identifiers.
738 Record.push_back(LangOpts.AsmPreprocessor); // Preprocessor in asm mode.
739 Record.push_back(LangOpts.GNUMode); // True in gnu99 mode false in c99 mode (etc)
740 Record.push_back(LangOpts.ImplicitInt); // C89 implicit 'int'.
741 Record.push_back(LangOpts.Digraphs); // C94, C99 and C++
742 Record.push_back(LangOpts.HexFloats); // C99 Hexadecimal float constants.
743 Record.push_back(LangOpts.C99); // C99 Support
744 Record.push_back(LangOpts.Microsoft); // Microsoft extensions.
745 Record.push_back(LangOpts.CPlusPlus); // C++ Support
746 Record.push_back(LangOpts.CPlusPlus0x); // C++0x Support
747 Record.push_back(LangOpts.CXXOperatorNames); // Treat C++ operator names as keywords.
748
749 Record.push_back(LangOpts.ObjC1); // Objective-C 1 support enabled.
750 Record.push_back(LangOpts.ObjC2); // Objective-C 2 support enabled.
751 Record.push_back(LangOpts.ObjCNonFragileABI); // Objective-C
752 // modern abi enabled.
753 Record.push_back(LangOpts.ObjCNonFragileABI2); // Objective-C enhanced
754 // modern abi enabled.
755
756 Record.push_back(LangOpts.PascalStrings); // Allow Pascal strings
757 Record.push_back(LangOpts.WritableStrings); // Allow writable strings
758 Record.push_back(LangOpts.LaxVectorConversions);
759 Record.push_back(LangOpts.AltiVec);
760 Record.push_back(LangOpts.Exceptions); // Support exception handling.
761
762 Record.push_back(LangOpts.NeXTRuntime); // Use NeXT runtime.
763 Record.push_back(LangOpts.Freestanding); // Freestanding implementation
764 Record.push_back(LangOpts.NoBuiltin); // Do not use builtin functions (-fno-builtin)
765
766 // Whether static initializers are protected by locks.
767 Record.push_back(LangOpts.ThreadsafeStatics);
768 Record.push_back(LangOpts.POSIXThreads);
769 Record.push_back(LangOpts.Blocks); // block extension to C
770 Record.push_back(LangOpts.EmitAllDecls); // Emit all declarations, even if
771 // they are unused.
772 Record.push_back(LangOpts.MathErrno); // Math functions must respect errno
773 // (modulo the platform support).
774
775 Record.push_back(LangOpts.OverflowChecking); // Extension to call a handler function when
776 // signed integer arithmetic overflows.
777
778 Record.push_back(LangOpts.HeinousExtensions); // Extensions that we really don't like and
779 // may be ripped out at any time.
780
781 Record.push_back(LangOpts.Optimize); // Whether __OPTIMIZE__ should be defined.
782 Record.push_back(LangOpts.OptimizeSize); // Whether __OPTIMIZE_SIZE__ should be
783 // defined.
784 Record.push_back(LangOpts.Static); // Should __STATIC__ be defined (as
785 // opposed to __DYNAMIC__).
786 Record.push_back(LangOpts.PICLevel); // The value for __PIC__, if non-zero.
787
788 Record.push_back(LangOpts.GNUInline); // Should GNU inline semantics be
789 // used (instead of C99 semantics).
790 Record.push_back(LangOpts.NoInline); // Should __NO_INLINE__ be defined.
791 Record.push_back(LangOpts.AccessControl); // Whether C++ access control should
792 // be enabled.
793 Record.push_back(LangOpts.CharIsSigned); // Whether char is a signed or
794 // unsigned type
795 Record.push_back(LangOpts.ShortWChar); // force wchar_t to be unsigned short
796 Record.push_back(LangOpts.getGCMode());
797 Record.push_back(LangOpts.getVisibilityMode());
798 Record.push_back(LangOpts.getStackProtectorMode());
799 Record.push_back(LangOpts.InstantiationDepth);
800 Record.push_back(LangOpts.OpenCL);
801 Record.push_back(LangOpts.CatchUndefined);
802 Record.push_back(LangOpts.ElideConstructors);
803 Stream.EmitRecord(pch::LANGUAGE_OPTIONS, Record);
804}
805
806//===----------------------------------------------------------------------===//
807// stat cache Serialization
808//===----------------------------------------------------------------------===//
809
810namespace {
811// Trait used for the on-disk hash table of stat cache results.
812class PCHStatCacheTrait {
813public:
814 typedef const char * key_type;
815 typedef key_type key_type_ref;
816
817 typedef std::pair<int, struct stat> data_type;
818 typedef const data_type& data_type_ref;
819
820 static unsigned ComputeHash(const char *path) {
821 return llvm::HashString(path);
822 }
823
824 std::pair<unsigned,unsigned>
825 EmitKeyDataLength(llvm::raw_ostream& Out, const char *path,
826 data_type_ref Data) {
827 unsigned StrLen = strlen(path);
828 clang::io::Emit16(Out, StrLen);
829 unsigned DataLen = 1; // result value
830 if (Data.first == 0)
831 DataLen += 4 + 4 + 2 + 8 + 8;
832 clang::io::Emit8(Out, DataLen);
833 return std::make_pair(StrLen + 1, DataLen);
834 }
835
836 void EmitKey(llvm::raw_ostream& Out, const char *path, unsigned KeyLen) {
837 Out.write(path, KeyLen);
838 }
839
840 void EmitData(llvm::raw_ostream& Out, key_type_ref,
841 data_type_ref Data, unsigned DataLen) {
842 using namespace clang::io;
843 uint64_t Start = Out.tell(); (void)Start;
844
845 // Result of stat()
846 Emit8(Out, Data.first? 1 : 0);
847
848 if (Data.first == 0) {
849 Emit32(Out, (uint32_t) Data.second.st_ino);
850 Emit32(Out, (uint32_t) Data.second.st_dev);
851 Emit16(Out, (uint16_t) Data.second.st_mode);
852 Emit64(Out, (uint64_t) Data.second.st_mtime);
853 Emit64(Out, (uint64_t) Data.second.st_size);
854 }
855
856 assert(Out.tell() - Start == DataLen && "Wrong data length");
857 }
858};
859} // end anonymous namespace
860
861/// \brief Write the stat() system call cache to the PCH file.
862void PCHWriter::WriteStatCache(MemorizeStatCalls &StatCalls,
863 const char *isysroot) {
864 // Build the on-disk hash table containing information about every
865 // stat() call.
866 OnDiskChainedHashTableGenerator<PCHStatCacheTrait> Generator;
867 unsigned NumStatEntries = 0;
868 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
869 StatEnd = StatCalls.end();
870 Stat != StatEnd; ++Stat, ++NumStatEntries) {
871 const char *Filename = Stat->first();
872 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
873 Generator.insert(Filename, Stat->second);
874 }
875
876 // Create the on-disk hash table in a buffer.
877 llvm::SmallString<4096> StatCacheData;
878 uint32_t BucketOffset;
879 {
880 llvm::raw_svector_ostream Out(StatCacheData);
881 // Make sure that no bucket is at offset 0
882 clang::io::Emit32(Out, 0);
883 BucketOffset = Generator.Emit(Out);
884 }
885
886 // Create a blob abbreviation
887 using namespace llvm;
888 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
889 Abbrev->Add(BitCodeAbbrevOp(pch::STAT_CACHE));
890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
891 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
892 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
893 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
894
895 // Write the stat cache
896 RecordData Record;
897 Record.push_back(pch::STAT_CACHE);
898 Record.push_back(BucketOffset);
899 Record.push_back(NumStatEntries);
900 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
901}
902
903//===----------------------------------------------------------------------===//
904// Source Manager Serialization
905//===----------------------------------------------------------------------===//
906
907/// \brief Create an abbreviation for the SLocEntry that refers to a
908/// file.
909static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
910 using namespace llvm;
911 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
912 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_FILE_ENTRY));
913 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
914 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
915 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
916 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
917 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
918 return Stream.EmitAbbrev(Abbrev);
919}
920
921/// \brief Create an abbreviation for the SLocEntry that refers to a
922/// buffer.
923static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
924 using namespace llvm;
925 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
926 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_ENTRY));
927 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
928 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
929 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
930 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
931 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
932 return Stream.EmitAbbrev(Abbrev);
933}
934
935/// \brief Create an abbreviation for the SLocEntry that refers to a
936/// buffer's blob.
937static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
938 using namespace llvm;
939 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
940 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_BUFFER_BLOB));
941 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
942 return Stream.EmitAbbrev(Abbrev);
943}
944
945/// \brief Create an abbreviation for the SLocEntry that refers to an
946/// buffer.
947static unsigned CreateSLocInstantiationAbbrev(llvm::BitstreamWriter &Stream) {
948 using namespace llvm;
949 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
950 Abbrev->Add(BitCodeAbbrevOp(pch::SM_SLOC_INSTANTIATION_ENTRY));
951 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
952 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
953 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
954 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
955 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
956 return Stream.EmitAbbrev(Abbrev);
957}
958
959/// \brief Writes the block containing the serialized form of the
960/// source manager.
961///
962/// TODO: We should probably use an on-disk hash table (stored in a
963/// blob), indexed based on the file name, so that we only create
964/// entries for files that we actually need. In the common case (no
965/// errors), we probably won't have to create file entries for any of
966/// the files in the AST.
967void PCHWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
968 const Preprocessor &PP,
969 const char *isysroot) {
970 RecordData Record;
971
972 // Enter the source manager block.
973 Stream.EnterSubblock(pch::SOURCE_MANAGER_BLOCK_ID, 3);
974
975 // Abbreviations for the various kinds of source-location entries.
976 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
977 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
978 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
979 unsigned SLocInstantiationAbbrv = CreateSLocInstantiationAbbrev(Stream);
980
981 // Write the line table.
982 if (SourceMgr.hasLineTable()) {
983 LineTableInfo &LineTable = SourceMgr.getLineTable();
984
985 // Emit the file names
986 Record.push_back(LineTable.getNumFilenames());
987 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
988 // Emit the file name
989 const char *Filename = LineTable.getFilename(I);
990 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
991 unsigned FilenameLen = Filename? strlen(Filename) : 0;
992 Record.push_back(FilenameLen);
993 if (FilenameLen)
994 Record.insert(Record.end(), Filename, Filename + FilenameLen);
995 }
996
997 // Emit the line entries
998 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
999 L != LEnd; ++L) {
1000 // Emit the file ID
1001 Record.push_back(L->first);
1002
1003 // Emit the line entries
1004 Record.push_back(L->second.size());
1005 for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1006 LEEnd = L->second.end();
1007 LE != LEEnd; ++LE) {
1008 Record.push_back(LE->FileOffset);
1009 Record.push_back(LE->LineNo);
1010 Record.push_back(LE->FilenameID);
1011 Record.push_back((unsigned)LE->FileKind);
1012 Record.push_back(LE->IncludeOffset);
1013 }
1014 }
1015 Stream.EmitRecord(pch::SM_LINE_TABLE, Record);
1016 }
1017
1018 // Write out entries for all of the header files we know about.
1019 HeaderSearch &HS = PP.getHeaderSearchInfo();
1020 Record.clear();
1021 for (HeaderSearch::header_file_iterator I = HS.header_file_begin(),
1022 E = HS.header_file_end();
1023 I != E; ++I) {
1024 Record.push_back(I->isImport);
1025 Record.push_back(I->DirInfo);
1026 Record.push_back(I->NumIncludes);
1027 AddIdentifierRef(I->ControllingMacro, Record);
1028 Stream.EmitRecord(pch::SM_HEADER_FILE_INFO, Record);
1029 Record.clear();
1030 }
1031
1032 // Write out the source location entry table. We skip the first
1033 // entry, which is always the same dummy entry.
1034 std::vector<uint32_t> SLocEntryOffsets;
1035 RecordData PreloadSLocs;
1036 SLocEntryOffsets.reserve(SourceMgr.sloc_entry_size() - 1);
1037 for (unsigned I = 1, N = SourceMgr.sloc_entry_size(); I != N; ++I) {
1038 // Get this source location entry.
1039 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getSLocEntry(I);
1040
1041 // Record the offset of this source-location entry.
1042 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1043
1044 // Figure out which record code to use.
1045 unsigned Code;
1046 if (SLoc->isFile()) {
1047 if (SLoc->getFile().getContentCache()->Entry)
1048 Code = pch::SM_SLOC_FILE_ENTRY;
1049 else
1050 Code = pch::SM_SLOC_BUFFER_ENTRY;
1051 } else
1052 Code = pch::SM_SLOC_INSTANTIATION_ENTRY;
1053 Record.clear();
1054 Record.push_back(Code);
1055
1056 Record.push_back(SLoc->getOffset());
1057 if (SLoc->isFile()) {
1058 const SrcMgr::FileInfo &File = SLoc->getFile();
1059 Record.push_back(File.getIncludeLoc().getRawEncoding());
1060 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1061 Record.push_back(File.hasLineDirectives());
1062
1063 const SrcMgr::ContentCache *Content = File.getContentCache();
1064 if (Content->Entry) {
1065 // The source location entry is a file. The blob associated
1066 // with this entry is the file name.
1067
1068 // Turn the file name into an absolute path, if it isn't already.
1069 const char *Filename = Content->Entry->getName();
1070 llvm::sys::Path FilePath(Filename, strlen(Filename));
1071 std::string FilenameStr;
1072 if (!FilePath.isAbsolute()) {
1073 llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory();
1074 P.appendComponent(FilePath.str());
1075 FilenameStr = P.str();
1076 Filename = FilenameStr.c_str();
1077 }
1078
1079 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1080 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
1081
1082 // FIXME: For now, preload all file source locations, so that
1083 // we get the appropriate File entries in the reader. This is
1084 // a temporary measure.
1085 PreloadSLocs.push_back(SLocEntryOffsets.size());
1086 } else {
1087 // The source location entry is a buffer. The blob associated
1088 // with this entry contains the contents of the buffer.
1089
1090 // We add one to the size so that we capture the trailing NULL
1091 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1092 // the reader side).
1093 const llvm::MemoryBuffer *Buffer = Content->getBuffer();
1094 const char *Name = Buffer->getBufferIdentifier();
1095 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1096 llvm::StringRef(Name, strlen(Name) + 1));
1097 Record.clear();
1098 Record.push_back(pch::SM_SLOC_BUFFER_BLOB);
1099 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1100 llvm::StringRef(Buffer->getBufferStart(),
1101 Buffer->getBufferSize() + 1));
1102
1103 if (strcmp(Name, "<built-in>") == 0)
1104 PreloadSLocs.push_back(SLocEntryOffsets.size());
1105 }
1106 } else {
1107 // The source location entry is an instantiation.
1108 const SrcMgr::InstantiationInfo &Inst = SLoc->getInstantiation();
1109 Record.push_back(Inst.getSpellingLoc().getRawEncoding());
1110 Record.push_back(Inst.getInstantiationLocStart().getRawEncoding());
1111 Record.push_back(Inst.getInstantiationLocEnd().getRawEncoding());
1112
1113 // Compute the token length for this macro expansion.
1114 unsigned NextOffset = SourceMgr.getNextOffset();
1115 if (I + 1 != N)
1116 NextOffset = SourceMgr.getSLocEntry(I + 1).getOffset();
1117 Record.push_back(NextOffset - SLoc->getOffset() - 1);
1118 Stream.EmitRecordWithAbbrev(SLocInstantiationAbbrv, Record);
1119 }
1120 }
1121
1122 Stream.ExitBlock();
1123
1124 if (SLocEntryOffsets.empty())
1125 return;
1126
1127 // Write the source-location offsets table into the PCH block. This
1128 // table is used for lazily loading source-location information.
1129 using namespace llvm;
1130 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1131 Abbrev->Add(BitCodeAbbrevOp(pch::SOURCE_LOCATION_OFFSETS));
1132 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1133 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // next offset
1134 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1135 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1136
1137 Record.clear();
1138 Record.push_back(pch::SOURCE_LOCATION_OFFSETS);
1139 Record.push_back(SLocEntryOffsets.size());
1140 Record.push_back(SourceMgr.getNextOffset());
1141 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1142 (const char *)&SLocEntryOffsets.front(),
1143 SLocEntryOffsets.size()*sizeof(SLocEntryOffsets[0]));
1144
1145 // Write the source location entry preloads array, telling the PCH
1146 // reader which source locations entries it should load eagerly.
1147 Stream.EmitRecord(pch::SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1148}
1149
1150//===----------------------------------------------------------------------===//
1151// Preprocessor Serialization
1152//===----------------------------------------------------------------------===//
1153
1154/// \brief Writes the block containing the serialized form of the
1155/// preprocessor.
1156///
1157void PCHWriter::WritePreprocessor(const Preprocessor &PP) {
1158 RecordData Record;
1159
1160 // If the preprocessor __COUNTER__ value has been bumped, remember it.
1161 if (PP.getCounterValue() != 0) {
1162 Record.push_back(PP.getCounterValue());
1163 Stream.EmitRecord(pch::PP_COUNTER_VALUE, Record);
1164 Record.clear();
1165 }
1166
1167 // Enter the preprocessor block.
1168 Stream.EnterSubblock(pch::PREPROCESSOR_BLOCK_ID, 2);
1169
1170 // If the PCH file contains __DATE__ or __TIME__ emit a warning about this.
1171 // FIXME: use diagnostics subsystem for localization etc.
1172 if (PP.SawDateOrTime())
1173 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1174
1175 // Loop over all the macro definitions that are live at the end of the file,
1176 // emitting each to the PP section.
1177 for (Preprocessor::macro_iterator I = PP.macro_begin(), E = PP.macro_end();
1178 I != E; ++I) {
1179 // FIXME: This emits macros in hash table order, we should do it in a stable
1180 // order so that output is reproducible.
1181 MacroInfo *MI = I->second;
1182
1183 // Don't emit builtin macros like __LINE__ to the PCH file unless they have
1184 // been redefined by the header (in which case they are not isBuiltinMacro).
1185 if (MI->isBuiltinMacro())
1186 continue;
1187
1188 AddIdentifierRef(I->first, Record);
1189 MacroOffsets[I->first] = Stream.GetCurrentBitNo();
1190 Record.push_back(MI->getDefinitionLoc().getRawEncoding());
1191 Record.push_back(MI->isUsed());
1192
1193 unsigned Code;
1194 if (MI->isObjectLike()) {
1195 Code = pch::PP_MACRO_OBJECT_LIKE;
1196 } else {
1197 Code = pch::PP_MACRO_FUNCTION_LIKE;
1198
1199 Record.push_back(MI->isC99Varargs());
1200 Record.push_back(MI->isGNUVarargs());
1201 Record.push_back(MI->getNumArgs());
1202 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
1203 I != E; ++I)
1204 AddIdentifierRef(*I, Record);
1205 }
1206 Stream.EmitRecord(Code, Record);
1207 Record.clear();
1208
1209 // Emit the tokens array.
1210 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
1211 // Note that we know that the preprocessor does not have any annotation
1212 // tokens in it because they are created by the parser, and thus can't be
1213 // in a macro definition.
1214 const Token &Tok = MI->getReplacementToken(TokNo);
1215
1216 Record.push_back(Tok.getLocation().getRawEncoding());
1217 Record.push_back(Tok.getLength());
1218
1219 // FIXME: When reading literal tokens, reconstruct the literal pointer if
1220 // it is needed.
1221 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
1222
1223 // FIXME: Should translate token kind to a stable encoding.
1224 Record.push_back(Tok.getKind());
1225 // FIXME: Should translate token flags to a stable encoding.
1226 Record.push_back(Tok.getFlags());
1227
1228 Stream.EmitRecord(pch::PP_TOKEN, Record);
1229 Record.clear();
1230 }
1231 ++NumMacros;
1232 }
1233 Stream.ExitBlock();
1234}
1235
1236void PCHWriter::WriteComments(ASTContext &Context) {
1237 using namespace llvm;
1238
1239 if (Context.Comments.empty())
1240 return;
1241
1242 BitCodeAbbrev *CommentAbbrev = new BitCodeAbbrev();
1243 CommentAbbrev->Add(BitCodeAbbrevOp(pch::COMMENT_RANGES));
1244 CommentAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1245 unsigned CommentCode = Stream.EmitAbbrev(CommentAbbrev);
1246
1247 RecordData Record;
1248 Record.push_back(pch::COMMENT_RANGES);
1249 Stream.EmitRecordWithBlob(CommentCode, Record,
1250 (const char*)&Context.Comments[0],
1251 Context.Comments.size() * sizeof(SourceRange));
1252}
1253
1254//===----------------------------------------------------------------------===//
1255// Type Serialization
1256//===----------------------------------------------------------------------===//
1257
1258/// \brief Write the representation of a type to the PCH stream.
1259void PCHWriter::WriteType(QualType T) {
1260 pch::TypeID &ID = TypeIDs[T];
1261 if (ID == 0) // we haven't seen this type before.
1262 ID = NextTypeID++;
1263
1264 // Record the offset for this type.
1265 if (TypeOffsets.size() == ID - pch::NUM_PREDEF_TYPE_IDS)
1266 TypeOffsets.push_back(Stream.GetCurrentBitNo());
1267 else if (TypeOffsets.size() < ID - pch::NUM_PREDEF_TYPE_IDS) {
1268 TypeOffsets.resize(ID + 1 - pch::NUM_PREDEF_TYPE_IDS);
1269 TypeOffsets[ID - pch::NUM_PREDEF_TYPE_IDS] = Stream.GetCurrentBitNo();
1270 }
1271
1272 RecordData Record;
1273
1274 // Emit the type's representation.
1275 PCHTypeWriter W(*this, Record);
1276
1277 if (T.hasLocalNonFastQualifiers()) {
1278 Qualifiers Qs = T.getLocalQualifiers();
1279 AddTypeRef(T.getLocalUnqualifiedType(), Record);
1280 Record.push_back(Qs.getAsOpaqueValue());
1281 W.Code = pch::TYPE_EXT_QUAL;
1282 } else {
1283 switch (T->getTypeClass()) {
1284 // For all of the concrete, non-dependent types, call the
1285 // appropriate visitor function.
1286#define TYPE(Class, Base) \
1287 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
1288#define ABSTRACT_TYPE(Class, Base)
1289#define DEPENDENT_TYPE(Class, Base)
1290#include "clang/AST/TypeNodes.def"
1291
1292 // For all of the dependent type nodes (which only occur in C++
1293 // templates), produce an error.
1294#define TYPE(Class, Base)
1295#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1296#include "clang/AST/TypeNodes.def"
1297 assert(false && "Cannot serialize dependent type nodes");
1298 break;
1299 }
1300 }
1301
1302 // Emit the serialized record.
1303 Stream.EmitRecord(W.Code, Record);
1304
1305 // Flush any expressions that were written as part of this type.
1306 FlushStmts();
1307}
1308
1309//===----------------------------------------------------------------------===//
1310// Declaration Serialization
1311//===----------------------------------------------------------------------===//
1312
1313/// \brief Write the block containing all of the declaration IDs
1314/// lexically declared within the given DeclContext.
1315///
1316/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
1317/// bistream, or 0 if no block was written.
1318uint64_t PCHWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
1319 DeclContext *DC) {
1320 if (DC->decls_empty())
1321 return 0;
1322
1323 uint64_t Offset = Stream.GetCurrentBitNo();
1324 RecordData Record;
1325 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
1326 D != DEnd; ++D)
1327 AddDeclRef(*D, Record);
1328
1329 ++NumLexicalDeclContexts;
1330 Stream.EmitRecord(pch::DECL_CONTEXT_LEXICAL, Record);
1331 return Offset;
1332}
1333
1334/// \brief Write the block containing all of the declaration IDs
1335/// visible from the given DeclContext.
1336///
1337/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
1338/// bistream, or 0 if no block was written.
1339uint64_t PCHWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
1340 DeclContext *DC) {
1341 if (DC->getPrimaryContext() != DC)
1342 return 0;
1343
1344 // Since there is no name lookup into functions or methods, and we
1345 // perform name lookup for the translation unit via the
1346 // IdentifierInfo chains, don't bother to build a
1347 // visible-declarations table for these entities.
1348 if (DC->isFunctionOrMethod() || DC->isTranslationUnit())
1349 return 0;
1350
1351 // Force the DeclContext to build a its name-lookup table.
1352 DC->lookup(DeclarationName());
1353
1354 // Serialize the contents of the mapping used for lookup. Note that,
1355 // although we have two very different code paths, the serialized
1356 // representation is the same for both cases: a declaration name,
1357 // followed by a size, followed by references to the visible
1358 // declarations that have that name.
1359 uint64_t Offset = Stream.GetCurrentBitNo();
1360 RecordData Record;
1361 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
1362 if (!Map)
1363 return 0;
1364
1365 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
1366 D != DEnd; ++D) {
1367 AddDeclarationName(D->first, Record);
1368 DeclContext::lookup_result Result = D->second.getLookupResult(Context);
1369 Record.push_back(Result.second - Result.first);
1370 for (; Result.first != Result.second; ++Result.first)
1371 AddDeclRef(*Result.first, Record);
1372 }
1373
1374 if (Record.size() == 0)
1375 return 0;
1376
1377 Stream.EmitRecord(pch::DECL_CONTEXT_VISIBLE, Record);
1378 ++NumVisibleDeclContexts;
1379 return Offset;
1380}
1381
1382//===----------------------------------------------------------------------===//
1383// Global Method Pool and Selector Serialization
1384//===----------------------------------------------------------------------===//
1385
1386namespace {
1387// Trait used for the on-disk hash table used in the method pool.
1388class PCHMethodPoolTrait {
1389 PCHWriter &Writer;
1390
1391public:
1392 typedef Selector key_type;
1393 typedef key_type key_type_ref;
1394
1395 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
1396 typedef const data_type& data_type_ref;
1397
1398 explicit PCHMethodPoolTrait(PCHWriter &Writer) : Writer(Writer) { }
1399
1400 static unsigned ComputeHash(Selector Sel) {
1401 unsigned N = Sel.getNumArgs();
1402 if (N == 0)
1403 ++N;
1404 unsigned R = 5381;
1405 for (unsigned I = 0; I != N; ++I)
1406 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
1407 R = llvm::HashString(II->getName(), R);
1408 return R;
1409 }
1410
1411 std::pair<unsigned,unsigned>
1412 EmitKeyDataLength(llvm::raw_ostream& Out, Selector Sel,
1413 data_type_ref Methods) {
1414 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
1415 clang::io::Emit16(Out, KeyLen);
1416 unsigned DataLen = 2 + 2; // 2 bytes for each of the method counts
1417 for (const ObjCMethodList *Method = &Methods.first; Method;
1418 Method = Method->Next)
1419 if (Method->Method)
1420 DataLen += 4;
1421 for (const ObjCMethodList *Method = &Methods.second; Method;
1422 Method = Method->Next)
1423 if (Method->Method)
1424 DataLen += 4;
1425 clang::io::Emit16(Out, DataLen);
1426 return std::make_pair(KeyLen, DataLen);
1427 }
1428
1429 void EmitKey(llvm::raw_ostream& Out, Selector Sel, unsigned) {
1430 uint64_t Start = Out.tell();
1431 assert((Start >> 32) == 0 && "Selector key offset too large");
1432 Writer.SetSelectorOffset(Sel, Start);
1433 unsigned N = Sel.getNumArgs();
1434 clang::io::Emit16(Out, N);
1435 if (N == 0)
1436 N = 1;
1437 for (unsigned I = 0; I != N; ++I)
1438 clang::io::Emit32(Out,
1439 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
1440 }
1441
1442 void EmitData(llvm::raw_ostream& Out, key_type_ref,
1443 data_type_ref Methods, unsigned DataLen) {
1444 uint64_t Start = Out.tell(); (void)Start;
1445 unsigned NumInstanceMethods = 0;
1446 for (const ObjCMethodList *Method = &Methods.first; Method;
1447 Method = Method->Next)
1448 if (Method->Method)
1449 ++NumInstanceMethods;
1450
1451 unsigned NumFactoryMethods = 0;
1452 for (const ObjCMethodList *Method = &Methods.second; Method;
1453 Method = Method->Next)
1454 if (Method->Method)
1455 ++NumFactoryMethods;
1456
1457 clang::io::Emit16(Out, NumInstanceMethods);
1458 clang::io::Emit16(Out, NumFactoryMethods);
1459 for (const ObjCMethodList *Method = &Methods.first; Method;
1460 Method = Method->Next)
1461 if (Method->Method)
1462 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1463 for (const ObjCMethodList *Method = &Methods.second; Method;
1464 Method = Method->Next)
1465 if (Method->Method)
1466 clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
1467
1468 assert(Out.tell() - Start == DataLen && "Data length is wrong");
1469 }
1470};
1471} // end anonymous namespace
1472
1473/// \brief Write the method pool into the PCH file.
1474///
1475/// The method pool contains both instance and factory methods, stored
1476/// in an on-disk hash table indexed by the selector.
1477void PCHWriter::WriteMethodPool(Sema &SemaRef) {
1478 using namespace llvm;
1479
1480 // Create and write out the blob that contains the instance and
1481 // factor method pools.
1482 bool Empty = true;
1483 {
1484 OnDiskChainedHashTableGenerator<PCHMethodPoolTrait> Generator;
1485
1486 // Create the on-disk hash table representation. Start by
1487 // iterating through the instance method pool.
1488 PCHMethodPoolTrait::key_type Key;
1489 unsigned NumSelectorsInMethodPool = 0;
1490 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1491 Instance = SemaRef.InstanceMethodPool.begin(),
1492 InstanceEnd = SemaRef.InstanceMethodPool.end();
1493 Instance != InstanceEnd; ++Instance) {
1494 // Check whether there is a factory method with the same
1495 // selector.
1496 llvm::DenseMap<Selector, ObjCMethodList>::iterator Factory
1497 = SemaRef.FactoryMethodPool.find(Instance->first);
1498
1499 if (Factory == SemaRef.FactoryMethodPool.end())
1500 Generator.insert(Instance->first,
1501 std::make_pair(Instance->second,
1502 ObjCMethodList()));
1503 else
1504 Generator.insert(Instance->first,
1505 std::make_pair(Instance->second, Factory->second));
1506
1507 ++NumSelectorsInMethodPool;
1508 Empty = false;
1509 }
1510
1511 // Now iterate through the factory method pool, to pick up any
1512 // selectors that weren't already in the instance method pool.
1513 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator
1514 Factory = SemaRef.FactoryMethodPool.begin(),
1515 FactoryEnd = SemaRef.FactoryMethodPool.end();
1516 Factory != FactoryEnd; ++Factory) {
1517 // Check whether there is an instance method with the same
1518 // selector. If so, there is no work to do here.
1519 llvm::DenseMap<Selector, ObjCMethodList>::iterator Instance
1520 = SemaRef.InstanceMethodPool.find(Factory->first);
1521
1522 if (Instance == SemaRef.InstanceMethodPool.end()) {
1523 Generator.insert(Factory->first,
1524 std::make_pair(ObjCMethodList(), Factory->second));
1525 ++NumSelectorsInMethodPool;
1526 }
1527
1528 Empty = false;
1529 }
1530
1531 if (Empty && SelectorOffsets.empty())
1532 return;
1533
1534 // Create the on-disk hash table in a buffer.
1535 llvm::SmallString<4096> MethodPool;
1536 uint32_t BucketOffset;
1537 SelectorOffsets.resize(SelVector.size());
1538 {
1539 PCHMethodPoolTrait Trait(*this);
1540 llvm::raw_svector_ostream Out(MethodPool);
1541 // Make sure that no bucket is at offset 0
1542 clang::io::Emit32(Out, 0);
1543 BucketOffset = Generator.Emit(Out, Trait);
1544
1545 // For every selector that we have seen but which was not
1546 // written into the hash table, write the selector itself and
1547 // record it's offset.
1548 for (unsigned I = 0, N = SelVector.size(); I != N; ++I)
1549 if (SelectorOffsets[I] == 0)
1550 Trait.EmitKey(Out, SelVector[I], 0);
1551 }
1552
1553 // Create a blob abbreviation
1554 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1555 Abbrev->Add(BitCodeAbbrevOp(pch::METHOD_POOL));
1556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1559 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
1560
1561 // Write the method pool
1562 RecordData Record;
1563 Record.push_back(pch::METHOD_POOL);
1564 Record.push_back(BucketOffset);
1565 Record.push_back(NumSelectorsInMethodPool);
1566 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
1567
1568 // Create a blob abbreviation for the selector table offsets.
1569 Abbrev = new BitCodeAbbrev();
1570 Abbrev->Add(BitCodeAbbrevOp(pch::SELECTOR_OFFSETS));
1571 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // index
1572 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1573 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1574
1575 // Write the selector offsets table.
1576 Record.clear();
1577 Record.push_back(pch::SELECTOR_OFFSETS);
1578 Record.push_back(SelectorOffsets.size());
1579 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
1580 (const char *)&SelectorOffsets.front(),
1581 SelectorOffsets.size() * 4);
1582 }
1583}
1584
1585//===----------------------------------------------------------------------===//
1586// Identifier Table Serialization
1587//===----------------------------------------------------------------------===//
1588
1589namespace {
1590class PCHIdentifierTableTrait {
1591 PCHWriter &Writer;
1592 Preprocessor &PP;
1593
1594 /// \brief Determines whether this is an "interesting" identifier
1595 /// that needs a full IdentifierInfo structure written into the hash
1596 /// table.
1597 static bool isInterestingIdentifier(const IdentifierInfo *II) {
1598 return II->isPoisoned() ||
1599 II->isExtensionToken() ||
1600 II->hasMacroDefinition() ||
1601 II->getObjCOrBuiltinID() ||
1602 II->getFETokenInfo<void>();
1603 }
1604
1605public:
1606 typedef const IdentifierInfo* key_type;
1607 typedef key_type key_type_ref;
1608
1609 typedef pch::IdentID data_type;
1610 typedef data_type data_type_ref;
1611
1612 PCHIdentifierTableTrait(PCHWriter &Writer, Preprocessor &PP)
1613 : Writer(Writer), PP(PP) { }
1614
1615 static unsigned ComputeHash(const IdentifierInfo* II) {
1616 return llvm::HashString(II->getName());
1617 }
1618
1619 std::pair<unsigned,unsigned>
1620 EmitKeyDataLength(llvm::raw_ostream& Out, const IdentifierInfo* II,
1621 pch::IdentID ID) {
1622 unsigned KeyLen = II->getLength() + 1;
1623 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
1624 if (isInterestingIdentifier(II)) {
1625 DataLen += 2; // 2 bytes for builtin ID, flags
1626 if (II->hasMacroDefinition() &&
1627 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro())
1628 DataLen += 4;
1629 for (IdentifierResolver::iterator D = IdentifierResolver::begin(II),
1630 DEnd = IdentifierResolver::end();
1631 D != DEnd; ++D)
1632 DataLen += sizeof(pch::DeclID);
1633 }
1634 clang::io::Emit16(Out, DataLen);
1635 // We emit the key length after the data length so that every
1636 // string is preceded by a 16-bit length. This matches the PTH
1637 // format for storing identifiers.
1638 clang::io::Emit16(Out, KeyLen);
1639 return std::make_pair(KeyLen, DataLen);
1640 }
1641
1642 void EmitKey(llvm::raw_ostream& Out, const IdentifierInfo* II,
1643 unsigned KeyLen) {
1644 // Record the location of the key data. This is used when generating
1645 // the mapping from persistent IDs to strings.
1646 Writer.SetIdentifierOffset(II, Out.tell());
1647 Out.write(II->getNameStart(), KeyLen);
1648 }
1649
1650 void EmitData(llvm::raw_ostream& Out, const IdentifierInfo* II,
1651 pch::IdentID ID, unsigned) {
1652 if (!isInterestingIdentifier(II)) {
1653 clang::io::Emit32(Out, ID << 1);
1654 return;
1655 }
1656
1657 clang::io::Emit32(Out, (ID << 1) | 0x01);
1658 uint32_t Bits = 0;
1659 bool hasMacroDefinition =
1660 II->hasMacroDefinition() &&
1661 !PP.getMacroInfo(const_cast<IdentifierInfo *>(II))->isBuiltinMacro();
1662 Bits = (uint32_t)II->getObjCOrBuiltinID();
1663 Bits = (Bits << 1) | unsigned(hasMacroDefinition);
1664 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
1665 Bits = (Bits << 1) | unsigned(II->isPoisoned());
1666 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
1667 clang::io::Emit16(Out, Bits);
1668
1669 if (hasMacroDefinition)
1670 clang::io::Emit32(Out, Writer.getMacroOffset(II));
1671
1672 // Emit the declaration IDs in reverse order, because the
1673 // IdentifierResolver provides the declarations as they would be
1674 // visible (e.g., the function "stat" would come before the struct
1675 // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
1676 // adds declarations to the end of the list (so we need to see the
1677 // struct "status" before the function "status").
1678 llvm::SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
1679 IdentifierResolver::end());
1680 for (llvm::SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
1681 DEnd = Decls.rend();
1682 D != DEnd; ++D)
1683 clang::io::Emit32(Out, Writer.getDeclID(*D));
1684 }
1685};
1686} // end anonymous namespace
1687
1688/// \brief Write the identifier table into the PCH file.
1689///
1690/// The identifier table consists of a blob containing string data
1691/// (the actual identifiers themselves) and a separate "offsets" index
1692/// that maps identifier IDs to locations within the blob.
1693void PCHWriter::WriteIdentifierTable(Preprocessor &PP) {
1694 using namespace llvm;
1695
1696 // Create and write out the blob that contains the identifier
1697 // strings.
1698 {
1699 OnDiskChainedHashTableGenerator<PCHIdentifierTableTrait> Generator;
1700
1701 // Look for any identifiers that were named while processing the
1702 // headers, but are otherwise not needed. We add these to the hash
1703 // table to enable checking of the predefines buffer in the case
1704 // where the user adds new macro definitions when building the PCH
1705 // file.
1706 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
1707 IDEnd = PP.getIdentifierTable().end();
1708 ID != IDEnd; ++ID)
1709 getIdentifierRef(ID->second);
1710
1711 // Create the on-disk hash table representation.
1712 IdentifierOffsets.resize(IdentifierIDs.size());
1713 for (llvm::DenseMap<const IdentifierInfo *, pch::IdentID>::iterator
1714 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
1715 ID != IDEnd; ++ID) {
1716 assert(ID->first && "NULL identifier in identifier table");
1717 Generator.insert(ID->first, ID->second);
1718 }
1719
1720 // Create the on-disk hash table in a buffer.
1721 llvm::SmallString<4096> IdentifierTable;
1722 uint32_t BucketOffset;
1723 {
1724 PCHIdentifierTableTrait Trait(*this, PP);
1725 llvm::raw_svector_ostream Out(IdentifierTable);
1726 // Make sure that no bucket is at offset 0
1727 clang::io::Emit32(Out, 0);
1728 BucketOffset = Generator.Emit(Out, Trait);
1729 }
1730
1731 // Create a blob abbreviation
1732 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1733 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_TABLE));
1734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1736 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
1737
1738 // Write the identifier table
1739 RecordData Record;
1740 Record.push_back(pch::IDENTIFIER_TABLE);
1741 Record.push_back(BucketOffset);
1742 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
1743 }
1744
1745 // Write the offsets table for identifier IDs.
1746 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1747 Abbrev->Add(BitCodeAbbrevOp(pch::IDENTIFIER_OFFSET));
1748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
1749 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1750 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
1751
1752 RecordData Record;
1753 Record.push_back(pch::IDENTIFIER_OFFSET);
1754 Record.push_back(IdentifierOffsets.size());
1755 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
1756 (const char *)&IdentifierOffsets.front(),
1757 IdentifierOffsets.size() * sizeof(uint32_t));
1758}
1759
1760//===----------------------------------------------------------------------===//
1761// General Serialization Routines
1762//===----------------------------------------------------------------------===//
1763
1764/// \brief Write a record containing the given attributes.
1765void PCHWriter::WriteAttributeRecord(const Attr *Attr) {
1766 RecordData Record;
1767 for (; Attr; Attr = Attr->getNext()) {
1768 Record.push_back(Attr->getKind()); // FIXME: stable encoding, target attrs
1769 Record.push_back(Attr->isInherited());
1770 switch (Attr->getKind()) {
1771 default:
1772 assert(0 && "Does not support PCH writing for this attribute yet!");
1773 break;
1774 case Attr::Alias:
1775 AddString(cast<AliasAttr>(Attr)->getAliasee(), Record);
1776 break;
1777
1778 case Attr::Aligned:
1779 Record.push_back(cast<AlignedAttr>(Attr)->getAlignment());
1780 break;
1781
1782 case Attr::AlwaysInline:
1783 break;
1784
1785 case Attr::AnalyzerNoReturn:
1786 break;
1787
1788 case Attr::Annotate:
1789 AddString(cast<AnnotateAttr>(Attr)->getAnnotation(), Record);
1790 break;
1791
1792 case Attr::AsmLabel:
1793 AddString(cast<AsmLabelAttr>(Attr)->getLabel(), Record);
1794 break;
1795
1796 case Attr::BaseCheck:
1797 break;
1798
1799 case Attr::Blocks:
1800 Record.push_back(cast<BlocksAttr>(Attr)->getType()); // FIXME: stable
1801 break;
1802
1803 case Attr::CDecl:
1804 break;
1805
1806 case Attr::Cleanup:
1807 AddDeclRef(cast<CleanupAttr>(Attr)->getFunctionDecl(), Record);
1808 break;
1809
1810 case Attr::Const:
1811 break;
1812
1813 case Attr::Constructor:
1814 Record.push_back(cast<ConstructorAttr>(Attr)->getPriority());
1815 break;
1816
1817 case Attr::DLLExport:
1818 case Attr::DLLImport:
1819 case Attr::Deprecated:
1820 break;
1821
1822 case Attr::Destructor:
1823 Record.push_back(cast<DestructorAttr>(Attr)->getPriority());
1824 break;
1825
1826 case Attr::FastCall:
1827 case Attr::Final:
1828 break;
1829
1830 case Attr::Format: {
1831 const FormatAttr *Format = cast<FormatAttr>(Attr);
1832 AddString(Format->getType(), Record);
1833 Record.push_back(Format->getFormatIdx());
1834 Record.push_back(Format->getFirstArg());
1835 break;
1836 }
1837
1838 case Attr::FormatArg: {
1839 const FormatArgAttr *Format = cast<FormatArgAttr>(Attr);
1840 Record.push_back(Format->getFormatIdx());
1841 break;
1842 }
1843
1844 case Attr::Sentinel : {
1845 const SentinelAttr *Sentinel = cast<SentinelAttr>(Attr);
1846 Record.push_back(Sentinel->getSentinel());
1847 Record.push_back(Sentinel->getNullPos());
1848 break;
1849 }
1850
1851 case Attr::GNUInline:
1852 case Attr::Hiding:
1853 case Attr::IBOutletKind:
1854 case Attr::Malloc:
1855 case Attr::NoDebug:
1856 case Attr::NoReturn:
1857 case Attr::NoThrow:
1858 case Attr::NoInline:
1859 break;
1860
1861 case Attr::NonNull: {
1862 const NonNullAttr *NonNull = cast<NonNullAttr>(Attr);
1863 Record.push_back(NonNull->size());
1864 Record.insert(Record.end(), NonNull->begin(), NonNull->end());
1865 break;
1866 }
1867
1868 case Attr::ObjCException:
1869 case Attr::ObjCNSObject:
1870 case Attr::CFReturnsRetained:
1871 case Attr::NSReturnsRetained:
1872 case Attr::Overloadable:
1873 case Attr::Override:
1874 break;
1875
1876 case Attr::PragmaPack:
1877 Record.push_back(cast<PragmaPackAttr>(Attr)->getAlignment());
1878 break;
1879
1880 case Attr::Packed:
1881 break;
1882
1883 case Attr::Pure:
1884 break;
1885
1886 case Attr::Regparm:
1887 Record.push_back(cast<RegparmAttr>(Attr)->getNumParams());
1888 break;
1889
1890 case Attr::ReqdWorkGroupSize:
1891 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getXDim());
1892 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getYDim());
1893 Record.push_back(cast<ReqdWorkGroupSizeAttr>(Attr)->getZDim());
1894 break;
1895
1896 case Attr::Section:
1897 AddString(cast<SectionAttr>(Attr)->getName(), Record);
1898 break;
1899
1900 case Attr::StdCall:
1901 case Attr::TransparentUnion:
1902 case Attr::Unavailable:
1903 case Attr::Unused:
1904 case Attr::Used:
1905 break;
1906
1907 case Attr::Visibility:
1908 // FIXME: stable encoding
1909 Record.push_back(cast<VisibilityAttr>(Attr)->getVisibility());
1910 break;
1911
1912 case Attr::WarnUnusedResult:
1913 case Attr::Weak:
1914 case Attr::WeakImport:
1915 break;
1916 }
1917 }
1918
1919 Stream.EmitRecord(pch::DECL_ATTR, Record);
1920}
1921
1922void PCHWriter::AddString(const std::string &Str, RecordData &Record) {
1923 Record.push_back(Str.size());
1924 Record.insert(Record.end(), Str.begin(), Str.end());
1925}
1926
1927/// \brief Note that the identifier II occurs at the given offset
1928/// within the identifier table.
1929void PCHWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
1930 IdentifierOffsets[IdentifierIDs[II] - 1] = Offset;
1931}
1932
1933/// \brief Note that the selector Sel occurs at the given offset
1934/// within the method pool/selector table.
1935void PCHWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
1936 unsigned ID = SelectorIDs[Sel];
1937 assert(ID && "Unknown selector");
1938 SelectorOffsets[ID - 1] = Offset;
1939}
1940
1941PCHWriter::PCHWriter(llvm::BitstreamWriter &Stream)
1942 : Stream(Stream), NextTypeID(pch::NUM_PREDEF_TYPE_IDS),
1943 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
1944 NumVisibleDeclContexts(0) { }
1945
1946void PCHWriter::WritePCH(Sema &SemaRef, MemorizeStatCalls *StatCalls,
1947 const char *isysroot) {
1948 using namespace llvm;
1949
1950 ASTContext &Context = SemaRef.Context;
1951 Preprocessor &PP = SemaRef.PP;
1952
1953 // Emit the file header.
1954 Stream.Emit((unsigned)'C', 8);
1955 Stream.Emit((unsigned)'P', 8);
1956 Stream.Emit((unsigned)'C', 8);
1957 Stream.Emit((unsigned)'H', 8);
1958
1959 WriteBlockInfoBlock();
1960
1961 // The translation unit is the first declaration we'll emit.
1962 DeclIDs[Context.getTranslationUnitDecl()] = 1;
1963 DeclTypesToEmit.push(Context.getTranslationUnitDecl());
1964
1965 // Make sure that we emit IdentifierInfos (and any attached
1966 // declarations) for builtins.
1967 {
1968 IdentifierTable &Table = PP.getIdentifierTable();
1969 llvm::SmallVector<const char *, 32> BuiltinNames;
1970 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
1971 Context.getLangOptions().NoBuiltin);
1972 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
1973 getIdentifierRef(&Table.get(BuiltinNames[I]));
1974 }
1975
1976 // Build a record containing all of the tentative definitions in this file, in
1977 // TentativeDefinitions order. Generally, this record will be empty for
1978 // headers.
1979 RecordData TentativeDefinitions;
1980 for (unsigned i = 0, e = SemaRef.TentativeDefinitions.size(); i != e; ++i) {
1981 AddDeclRef(SemaRef.TentativeDefinitions[i], TentativeDefinitions);
1982 }
1983
1984 // Build a record containing all of the locally-scoped external
1985 // declarations in this header file. Generally, this record will be
1986 // empty.
1987 RecordData LocallyScopedExternalDecls;
1988 // FIXME: This is filling in the PCH file in densemap order which is
1989 // nondeterminstic!
1990 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
1991 TD = SemaRef.LocallyScopedExternalDecls.begin(),
1992 TDEnd = SemaRef.LocallyScopedExternalDecls.end();
1993 TD != TDEnd; ++TD)
1994 AddDeclRef(TD->second, LocallyScopedExternalDecls);
1995
1996 // Build a record containing all of the ext_vector declarations.
1997 RecordData ExtVectorDecls;
1998 for (unsigned I = 0, N = SemaRef.ExtVectorDecls.size(); I != N; ++I)
1999 AddDeclRef(SemaRef.ExtVectorDecls[I], ExtVectorDecls);
2000
2001 // Write the remaining PCH contents.
2002 RecordData Record;
2003 Stream.EnterSubblock(pch::PCH_BLOCK_ID, 4);
2004 WriteMetadata(Context, isysroot);
2005 WriteLanguageOptions(Context.getLangOptions());
2006 if (StatCalls && !isysroot)
2007 WriteStatCache(*StatCalls, isysroot);
2008 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
2009 WriteComments(Context);
2010 // Write the record of special types.
2011 Record.clear();
2012
2013 AddTypeRef(Context.getBuiltinVaListType(), Record);
2014 AddTypeRef(Context.getObjCIdType(), Record);
2015 AddTypeRef(Context.getObjCSelType(), Record);
2016 AddTypeRef(Context.getObjCProtoType(), Record);
2017 AddTypeRef(Context.getObjCClassType(), Record);
2018 AddTypeRef(Context.getRawCFConstantStringType(), Record);
2019 AddTypeRef(Context.getRawObjCFastEnumerationStateType(), Record);
2020 AddTypeRef(Context.getFILEType(), Record);
2021 AddTypeRef(Context.getjmp_bufType(), Record);
2022 AddTypeRef(Context.getsigjmp_bufType(), Record);
2023 AddTypeRef(Context.ObjCIdRedefinitionType, Record);
2024 AddTypeRef(Context.ObjCClassRedefinitionType, Record);
2025#if 0
2026 // FIXME. Accommodate for this in several PCH/Indexer tests
2027 AddTypeRef(Context.ObjCSelRedefinitionType, Record);
2028#endif
2029 AddTypeRef(Context.getRawBlockdescriptorType(), Record);
2030 AddTypeRef(Context.getRawBlockdescriptorExtendedType(), Record);
2031 Stream.EmitRecord(pch::SPECIAL_TYPES, Record);
2032
2033 // Keep writing types and declarations until all types and
2034 // declarations have been written.
2035 Stream.EnterSubblock(pch::DECLTYPES_BLOCK_ID, 3);
2036 WriteDeclsBlockAbbrevs();
2037 while (!DeclTypesToEmit.empty()) {
2038 DeclOrType DOT = DeclTypesToEmit.front();
2039 DeclTypesToEmit.pop();
2040 if (DOT.isType())
2041 WriteType(DOT.getType());
2042 else
2043 WriteDecl(Context, DOT.getDecl());
2044 }
2045 Stream.ExitBlock();
2046
2047 WritePreprocessor(PP);
2048 WriteMethodPool(SemaRef);
2049 WriteIdentifierTable(PP);
2050
2051 // Write the type offsets array
2052 BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2053 Abbrev->Add(BitCodeAbbrevOp(pch::TYPE_OFFSET));
2054 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2055 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2056 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2057 Record.clear();
2058 Record.push_back(pch::TYPE_OFFSET);
2059 Record.push_back(TypeOffsets.size());
2060 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record,
2061 (const char *)&TypeOffsets.front(),
2062 TypeOffsets.size() * sizeof(TypeOffsets[0]));
2063
2064 // Write the declaration offsets array
2065 Abbrev = new BitCodeAbbrev();
2066 Abbrev->Add(BitCodeAbbrevOp(pch::DECL_OFFSET));
2067 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2068 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2069 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2070 Record.clear();
2071 Record.push_back(pch::DECL_OFFSET);
2072 Record.push_back(DeclOffsets.size());
2073 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record,
2074 (const char *)&DeclOffsets.front(),
2075 DeclOffsets.size() * sizeof(DeclOffsets[0]));
2076
2077 // Write the record containing external, unnamed definitions.
2078 if (!ExternalDefinitions.empty())
2079 Stream.EmitRecord(pch::EXTERNAL_DEFINITIONS, ExternalDefinitions);
2080
2081 // Write the record containing tentative definitions.
2082 if (!TentativeDefinitions.empty())
2083 Stream.EmitRecord(pch::TENTATIVE_DEFINITIONS, TentativeDefinitions);
2084
2085 // Write the record containing locally-scoped external definitions.
2086 if (!LocallyScopedExternalDecls.empty())
2087 Stream.EmitRecord(pch::LOCALLY_SCOPED_EXTERNAL_DECLS,
2088 LocallyScopedExternalDecls);
2089
2090 // Write the record containing ext_vector type names.
2091 if (!ExtVectorDecls.empty())
2092 Stream.EmitRecord(pch::EXT_VECTOR_DECLS, ExtVectorDecls);
2093
2094 // Some simple statistics
2095 Record.clear();
2096 Record.push_back(NumStatements);
2097 Record.push_back(NumMacros);
2098 Record.push_back(NumLexicalDeclContexts);
2099 Record.push_back(NumVisibleDeclContexts);
2100 Stream.EmitRecord(pch::STATISTICS, Record);
2101 Stream.ExitBlock();
2102}
2103
2104void PCHWriter::AddSourceLocation(SourceLocation Loc, RecordData &Record) {
2105 Record.push_back(Loc.getRawEncoding());
2106}
2107
2108void PCHWriter::AddAPInt(const llvm::APInt &Value, RecordData &Record) {
2109 Record.push_back(Value.getBitWidth());
2110 unsigned N = Value.getNumWords();
2111 const uint64_t* Words = Value.getRawData();
2112 for (unsigned I = 0; I != N; ++I)
2113 Record.push_back(Words[I]);
2114}
2115
2116void PCHWriter::AddAPSInt(const llvm::APSInt &Value, RecordData &Record) {
2117 Record.push_back(Value.isUnsigned());
2118 AddAPInt(Value, Record);
2119}
2120
2121void PCHWriter::AddAPFloat(const llvm::APFloat &Value, RecordData &Record) {
2122 AddAPInt(Value.bitcastToAPInt(), Record);
2123}
2124
2125void PCHWriter::AddIdentifierRef(const IdentifierInfo *II, RecordData &Record) {
2126 Record.push_back(getIdentifierRef(II));
2127}
2128
2129pch::IdentID PCHWriter::getIdentifierRef(const IdentifierInfo *II) {
2130 if (II == 0)
2131 return 0;
2132
2133 pch::IdentID &ID = IdentifierIDs[II];
2134 if (ID == 0)
2135 ID = IdentifierIDs.size();
2136 return ID;
2137}
2138
2139void PCHWriter::AddSelectorRef(const Selector SelRef, RecordData &Record) {
2140 if (SelRef.getAsOpaquePtr() == 0) {
2141 Record.push_back(0);
2142 return;
2143 }
2144
2145 pch::SelectorID &SID = SelectorIDs[SelRef];
2146 if (SID == 0) {
2147 SID = SelectorIDs.size();
2148 SelVector.push_back(SelRef);
2149 }
2150 Record.push_back(SID);
2151}
2152
2153void PCHWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
2154 RecordData &Record) {
2155 switch (Arg.getArgument().getKind()) {
2156 case TemplateArgument::Expression:
2157 AddStmt(Arg.getLocInfo().getAsExpr());
2158 break;
2159 case TemplateArgument::Type:
2160 AddTypeSourceInfo(Arg.getLocInfo().getAsTypeSourceInfo(), Record);
2161 break;
2162 case TemplateArgument::Template:
2163 Record.push_back(
2164 Arg.getTemplateQualifierRange().getBegin().getRawEncoding());
2165 Record.push_back(Arg.getTemplateQualifierRange().getEnd().getRawEncoding());
2166 Record.push_back(Arg.getTemplateNameLoc().getRawEncoding());
2167 break;
2168 case TemplateArgument::Null:
2169 case TemplateArgument::Integral:
2170 case TemplateArgument::Declaration:
2171 case TemplateArgument::Pack:
2172 break;
2173 }
2174}
2175
2176void PCHWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordData &Record) {
2177 if (TInfo == 0) {
2178 AddTypeRef(QualType(), Record);
2179 return;
2180 }
2181
2182 AddTypeRef(TInfo->getType(), Record);
2183 TypeLocWriter TLW(*this, Record);
2184 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2185 TLW.Visit(TL);
2186}
2187
2188void PCHWriter::AddTypeRef(QualType T, RecordData &Record) {
2189 if (T.isNull()) {
2190 Record.push_back(pch::PREDEF_TYPE_NULL_ID);
2191 return;
2192 }
2193
2194 unsigned FastQuals = T.getLocalFastQualifiers();
2195 T.removeFastQualifiers();
2196
2197 if (T.hasLocalNonFastQualifiers()) {
2198 pch::TypeID &ID = TypeIDs[T];
2199 if (ID == 0) {
2200 // We haven't seen these qualifiers applied to this type before.
2201 // Assign it a new ID. This is the only time we enqueue a
2202 // qualified type, and it has no CV qualifiers.
2203 ID = NextTypeID++;
2204 DeclTypesToEmit.push(T);
2205 }
2206
2207 // Encode the type qualifiers in the type reference.
2208 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2209 return;
2210 }
2211
2212 assert(!T.hasLocalQualifiers());
2213
2214 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr())) {
2215 pch::TypeID ID = 0;
2216 switch (BT->getKind()) {
2217 case BuiltinType::Void: ID = pch::PREDEF_TYPE_VOID_ID; break;
2218 case BuiltinType::Bool: ID = pch::PREDEF_TYPE_BOOL_ID; break;
2219 case BuiltinType::Char_U: ID = pch::PREDEF_TYPE_CHAR_U_ID; break;
2220 case BuiltinType::UChar: ID = pch::PREDEF_TYPE_UCHAR_ID; break;
2221 case BuiltinType::UShort: ID = pch::PREDEF_TYPE_USHORT_ID; break;
2222 case BuiltinType::UInt: ID = pch::PREDEF_TYPE_UINT_ID; break;
2223 case BuiltinType::ULong: ID = pch::PREDEF_TYPE_ULONG_ID; break;
2224 case BuiltinType::ULongLong: ID = pch::PREDEF_TYPE_ULONGLONG_ID; break;
2225 case BuiltinType::UInt128: ID = pch::PREDEF_TYPE_UINT128_ID; break;
2226 case BuiltinType::Char_S: ID = pch::PREDEF_TYPE_CHAR_S_ID; break;
2227 case BuiltinType::SChar: ID = pch::PREDEF_TYPE_SCHAR_ID; break;
2228 case BuiltinType::WChar: ID = pch::PREDEF_TYPE_WCHAR_ID; break;
2229 case BuiltinType::Short: ID = pch::PREDEF_TYPE_SHORT_ID; break;
2230 case BuiltinType::Int: ID = pch::PREDEF_TYPE_INT_ID; break;
2231 case BuiltinType::Long: ID = pch::PREDEF_TYPE_LONG_ID; break;
2232 case BuiltinType::LongLong: ID = pch::PREDEF_TYPE_LONGLONG_ID; break;
2233 case BuiltinType::Int128: ID = pch::PREDEF_TYPE_INT128_ID; break;
2234 case BuiltinType::Float: ID = pch::PREDEF_TYPE_FLOAT_ID; break;
2235 case BuiltinType::Double: ID = pch::PREDEF_TYPE_DOUBLE_ID; break;
2236 case BuiltinType::LongDouble: ID = pch::PREDEF_TYPE_LONGDOUBLE_ID; break;
2237 case BuiltinType::NullPtr: ID = pch::PREDEF_TYPE_NULLPTR_ID; break;
2238 case BuiltinType::Char16: ID = pch::PREDEF_TYPE_CHAR16_ID; break;
2239 case BuiltinType::Char32: ID = pch::PREDEF_TYPE_CHAR32_ID; break;
2240 case BuiltinType::Overload: ID = pch::PREDEF_TYPE_OVERLOAD_ID; break;
2241 case BuiltinType::Dependent: ID = pch::PREDEF_TYPE_DEPENDENT_ID; break;
2242 case BuiltinType::ObjCId: ID = pch::PREDEF_TYPE_OBJC_ID; break;
2243 case BuiltinType::ObjCClass: ID = pch::PREDEF_TYPE_OBJC_CLASS; break;
2244 case BuiltinType::ObjCSel: ID = pch::PREDEF_TYPE_OBJC_SEL; break;
2245 case BuiltinType::UndeducedAuto:
2246 assert(0 && "Should not see undeduced auto here");
2247 break;
2248 }
2249
2250 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2251 return;
2252 }
2253
2254 pch::TypeID &ID = TypeIDs[T];
2255 if (ID == 0) {
2256 // We haven't seen this type before. Assign it a new ID and put it
2257 // into the queue of types to emit.
2258 ID = NextTypeID++;
2259 DeclTypesToEmit.push(T);
2260 }
2261
2262 // Encode the type qualifiers in the type reference.
2263 Record.push_back((ID << Qualifiers::FastWidth) | FastQuals);
2264}
2265
2266void PCHWriter::AddDeclRef(const Decl *D, RecordData &Record) {
2267 if (D == 0) {
2268 Record.push_back(0);
2269 return;
2270 }
2271
2272 pch::DeclID &ID = DeclIDs[D];
2273 if (ID == 0) {
2274 // We haven't seen this declaration before. Give it a new ID and
2275 // enqueue it in the list of declarations to emit.
2276 ID = DeclIDs.size();
2277 DeclTypesToEmit.push(const_cast<Decl *>(D));
2278 }
2279
2280 Record.push_back(ID);
2281}
2282
2283pch::DeclID PCHWriter::getDeclID(const Decl *D) {
2284 if (D == 0)
2285 return 0;
2286
2287 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
2288 return DeclIDs[D];
2289}
2290
2291void PCHWriter::AddDeclarationName(DeclarationName Name, RecordData &Record) {
2292 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
2293 Record.push_back(Name.getNameKind());
2294 switch (Name.getNameKind()) {
2295 case DeclarationName::Identifier:
2296 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
2297 break;
2298
2299 case DeclarationName::ObjCZeroArgSelector:
2300 case DeclarationName::ObjCOneArgSelector:
2301 case DeclarationName::ObjCMultiArgSelector:
2302 AddSelectorRef(Name.getObjCSelector(), Record);
2303 break;
2304
2305 case DeclarationName::CXXConstructorName:
2306 case DeclarationName::CXXDestructorName:
2307 case DeclarationName::CXXConversionFunctionName:
2308 AddTypeRef(Name.getCXXNameType(), Record);
2309 break;
2310
2311 case DeclarationName::CXXOperatorName:
2312 Record.push_back(Name.getCXXOverloadedOperator());
2313 break;
2314
2315 case DeclarationName::CXXLiteralOperatorName:
2316 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
2317 break;
2318
2319 case DeclarationName::CXXUsingDirective:
2320 // No extra data to emit
2321 break;
2322 }
2323}
2324