blob: d5923086c7a0fc2dc25f46934eb4ded713c883d2 [file] [log] [blame]
Douglas Gregorc34897d2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- 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 PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000018#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000022#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000023#include "llvm/Bitcode/BitstreamReader.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include <algorithm>
27#include <cstdio>
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Declaration deserialization
33//===----------------------------------------------------------------------===//
34namespace {
35 class VISIBILITY_HIDDEN PCHDeclReader {
36 PCHReader &Reader;
37 const PCHReader::RecordData &Record;
38 unsigned &Idx;
39
40 public:
41 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
42 unsigned &Idx)
43 : Reader(Reader), Record(Record), Idx(Idx) { }
44
45 void VisitDecl(Decl *D);
46 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
47 void VisitNamedDecl(NamedDecl *ND);
48 void VisitTypeDecl(TypeDecl *TD);
49 void VisitTypedefDecl(TypedefDecl *TD);
50 void VisitValueDecl(ValueDecl *VD);
51 void VisitVarDecl(VarDecl *VD);
52
53 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
54 };
55}
56
57void PCHDeclReader::VisitDecl(Decl *D) {
58 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
59 D->setLexicalDeclContext(
60 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
61 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
62 D->setInvalidDecl(Record[Idx++]);
63 // FIXME: hasAttrs
64 D->setImplicit(Record[Idx++]);
65 D->setAccess((AccessSpecifier)Record[Idx++]);
66}
67
68void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
69 VisitDecl(TU);
70}
71
72void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
73 VisitDecl(ND);
74 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
75}
76
77void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
78 VisitNamedDecl(TD);
79 // FIXME: circular dependencies here?
80 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
81}
82
83void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
84 VisitTypeDecl(TD);
85 TD->setUnderlyingType(Reader.GetType(Record[Idx++]));
86}
87
88void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
89 VisitNamedDecl(VD);
90 VD->setType(Reader.GetType(Record[Idx++]));
91}
92
93void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
94 VisitValueDecl(VD);
95 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
96 VD->setThreadSpecified(Record[Idx++]);
97 VD->setCXXDirectInitializer(Record[Idx++]);
98 VD->setDeclaredInCondition(Record[Idx++]);
99 VD->setPreviousDeclaration(
100 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
101 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
102}
103
104std::pair<uint64_t, uint64_t>
105PCHDeclReader::VisitDeclContext(DeclContext *DC) {
106 uint64_t LexicalOffset = Record[Idx++];
107 uint64_t VisibleOffset = 0;
108 if (DC->getPrimaryContext() == DC)
109 VisibleOffset = Record[Idx++];
110 return std::make_pair(LexicalOffset, VisibleOffset);
111}
112
113// FIXME: use the diagnostics machinery
114static bool Error(const char *Str) {
115 std::fprintf(stderr, "%s\n", Str);
116 return true;
117}
118
Douglas Gregorab1cef72009-04-10 03:52:48 +0000119/// \brief Read the source manager block
120bool PCHReader::ReadSourceManagerBlock() {
121 using namespace SrcMgr;
122 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID))
123 return Error("Malformed source manager block record");
124
125 SourceManager &SourceMgr = Context.getSourceManager();
126 RecordData Record;
127 while (true) {
128 unsigned Code = Stream.ReadCode();
129 if (Code == llvm::bitc::END_BLOCK) {
130 if (Stream.ReadBlockEnd())
131 return Error("Error at end of Source Manager block");
132 return false;
133 }
134
135 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
136 // No known subblocks, always skip them.
137 Stream.ReadSubBlockID();
138 if (Stream.SkipBlock())
139 return Error("Malformed block record");
140 continue;
141 }
142
143 if (Code == llvm::bitc::DEFINE_ABBREV) {
144 Stream.ReadAbbrevRecord();
145 continue;
146 }
147
148 // Read a record.
149 const char *BlobStart;
150 unsigned BlobLen;
151 Record.clear();
152 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
153 default: // Default behavior: ignore.
154 break;
155
156 case pch::SM_SLOC_FILE_ENTRY: {
157 // FIXME: We would really like to delay the creation of this
158 // FileEntry until it is actually required, e.g., when producing
159 // a diagnostic with a source location in this file.
160 const FileEntry *File
161 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
162 // FIXME: Error recovery if file cannot be found.
163 SourceMgr.createFileID(File,
164 SourceLocation::getFromRawEncoding(Record[1]),
165 (CharacteristicKind)Record[2]);
166 break;
167 }
168
169 case pch::SM_SLOC_BUFFER_ENTRY: {
170 const char *Name = BlobStart;
171 unsigned Code = Stream.ReadCode();
172 Record.clear();
173 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
174 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
175 SourceMgr.createFileIDForMemBuffer(
176 llvm::MemoryBuffer::getMemBuffer(BlobStart, BlobStart + BlobLen - 1,
177 Name));
178 break;
179 }
180
181 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
182 SourceLocation SpellingLoc
183 = SourceLocation::getFromRawEncoding(Record[1]);
184 SourceMgr.createInstantiationLoc(
185 SpellingLoc,
186 SourceLocation::getFromRawEncoding(Record[2]),
187 SourceLocation::getFromRawEncoding(Record[3]),
188 Lexer::MeasureTokenLength(SpellingLoc,
189 SourceMgr));
190 break;
191 }
192
193 }
194 }
195}
196
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000197bool PCHReader::ReadPreprocessorBlock() {
198 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
199 return Error("Malformed preprocessor block record");
200
201 std::string CurName; // FIXME: HACK.
202 RecordData Record;
203 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
204 MacroInfo *LastMacro = 0;
205
206 while (true) {
207 unsigned Code = Stream.ReadCode();
208 switch (Code) {
209 case llvm::bitc::END_BLOCK:
210 if (Stream.ReadBlockEnd())
211 return Error("Error at end of preprocessor block");
212 return false;
213
214 case llvm::bitc::ENTER_SUBBLOCK:
215 // No known subblocks, always skip them.
216 Stream.ReadSubBlockID();
217 if (Stream.SkipBlock())
218 return Error("Malformed block record");
219 continue;
220
221 case llvm::bitc::DEFINE_ABBREV:
222 Stream.ReadAbbrevRecord();
223 continue;
224 default: break;
225 }
226
227 // Read a record.
228 Record.clear();
229 pch::PreprocessorRecordTypes RecType =
230 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
231 switch (RecType) {
232 default: // Default behavior: ignore unknown records.
233 break;
234
235 case pch::PP_MACRO_NAME:
236 // Set CurName. FIXME: This is a hack and should be removed when we have
237 // identifier id's.
238 CurName.clear();
239 for (unsigned i = 0, e = Record.size(); i != e; ++i)
240 CurName += (char)Record[i];
241 break;
242
243 case pch::PP_MACRO_OBJECT_LIKE:
244 case pch::PP_MACRO_FUNCTION_LIKE: {
245 unsigned IdentInfo = Record[0];
246 IdentInfo = IdentInfo; // FIXME: Decode into identifier info*.
247 assert(!CurName.empty());
248 IdentifierInfo *II = PP.getIdentifierInfo(CurName.c_str());
249
250 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
251 bool isUsed = Record[2];
252
253 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
254 MI->setIsUsed(isUsed);
255
256 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
257 // Decode function-like macro info.
258 bool isC99VarArgs = Record[3];
259 bool isGNUVarArgs = Record[4];
260 MacroArgs.clear();
261 unsigned NumArgs = Record[5];
262 for (unsigned i = 0; i != NumArgs; ++i)
263 ; // FIXME: Decode macro arg names: MacroArgs.push_back(Record[6+i]);
264
265 // Install function-like macro info.
266 MI->setIsFunctionLike();
267 if (isC99VarArgs) MI->setIsC99Varargs();
268 if (isGNUVarArgs) MI->setIsGNUVarargs();
269 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
270 PP.getPreprocessorAllocator());
271 }
272
273 // Finally, install the macro.
274 II = II;
275#if 0
276 // FIXME: Do this when predefines buffer is worked out.
277 PP.setMacroInfo(II, MI);
278#endif
279
280 // Remember that we saw this macro last so that we add the tokens that
281 // form its body to it.
282 LastMacro = MI;
283 break;
284 }
285
286 case pch::PP_TOKEN: {
287 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
288 // pretend we didn't see this.
289 if (LastMacro == 0) break;
290
291 Token Tok;
292 Tok.startToken();
293 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
294 Tok.setLength(Record[1]);
295 unsigned IdentInfo = Record[2];
296 IdentInfo = IdentInfo; // FIXME: Handle this right.
297 Tok.setKind((tok::TokenKind)Record[3]);
298 Tok.setFlag((Token::TokenFlags)Record[4]);
299 LastMacro->AddTokenToBody(Tok);
300 break;
301 }
302 }
303 }
304}
305
Douglas Gregor179cfb12009-04-10 20:39:37 +0000306PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
307 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
308 Error("Malformed block record");
309 return Failure;
310 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000311
312 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000313 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000314 while (!Stream.AtEndOfStream()) {
315 unsigned Code = Stream.ReadCode();
316 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000317 if (Stream.ReadBlockEnd()) {
318 Error("Error at end of module block");
319 return Failure;
320 }
321 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000322 }
323
324 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
325 switch (Stream.ReadSubBlockID()) {
326 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
327 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
328 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000329 if (Stream.SkipBlock()) {
330 Error("Malformed block record");
331 return Failure;
332 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000333 break;
334
Douglas Gregorab1cef72009-04-10 03:52:48 +0000335 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000336 if (ReadSourceManagerBlock()) {
337 Error("Malformed source manager block");
338 return Failure;
339 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000340 break;
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000341
342 case pch::PREPROCESSOR_BLOCK_ID:
343 if (ReadPreprocessorBlock()) {
344 Error("Malformed preprocessor block");
345 return Failure;
346 }
347 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000348 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000349 continue;
350 }
351
352 if (Code == llvm::bitc::DEFINE_ABBREV) {
353 Stream.ReadAbbrevRecord();
354 continue;
355 }
356
357 // Read and process a record.
358 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000359 const char *BlobStart = 0;
360 unsigned BlobLen = 0;
361 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
362 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000363 default: // Default behavior: ignore.
364 break;
365
366 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000367 if (!TypeOffsets.empty()) {
368 Error("Duplicate TYPE_OFFSET record in PCH file");
369 return Failure;
370 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000371 TypeOffsets.swap(Record);
372 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
373 break;
374
375 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000376 if (!DeclOffsets.empty()) {
377 Error("Duplicate DECL_OFFSET record in PCH file");
378 return Failure;
379 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000380 DeclOffsets.swap(Record);
381 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
382 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000383
384 case pch::LANGUAGE_OPTIONS:
385 if (ParseLanguageOptions(Record))
386 return IgnorePCH;
387 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000388
389 case pch::TARGET_TRIPLE:
390 std::string TargetTriple(BlobStart, BlobLen);
391 if (TargetTriple != Context.Target.getTargetTriple()) {
392 Diag(diag::warn_pch_target_triple)
393 << TargetTriple << Context.Target.getTargetTriple();
394 Diag(diag::note_ignoring_pch) << FileName;
395 return IgnorePCH;
396 }
397 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000398 }
399 }
400
Douglas Gregor179cfb12009-04-10 20:39:37 +0000401 Error("Premature end of bitstream");
402 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000403}
404
405PCHReader::~PCHReader() { }
406
407bool PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000408 // Set the PCH file name.
409 this->FileName = FileName;
410
Douglas Gregorc34897d2009-04-09 22:27:44 +0000411 // Open the PCH file.
412 std::string ErrStr;
413 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
414 if (!Buffer)
415 return Error(ErrStr.c_str());
416
417 // Initialize the stream
418 Stream.init((const unsigned char *)Buffer->getBufferStart(),
419 (const unsigned char *)Buffer->getBufferEnd());
420
421 // Sniff for the signature.
422 if (Stream.Read(8) != 'C' ||
423 Stream.Read(8) != 'P' ||
424 Stream.Read(8) != 'C' ||
425 Stream.Read(8) != 'H')
426 return Error("Not a PCH file");
427
428 // We expect a number of well-defined blocks, though we don't necessarily
429 // need to understand them all.
430 while (!Stream.AtEndOfStream()) {
431 unsigned Code = Stream.ReadCode();
432
433 if (Code != llvm::bitc::ENTER_SUBBLOCK)
434 return Error("Invalid record at top-level");
435
436 unsigned BlockID = Stream.ReadSubBlockID();
437
438 // We only know the PCH subblock ID.
439 switch (BlockID) {
440 case llvm::bitc::BLOCKINFO_BLOCK_ID:
441 if (Stream.ReadBlockInfoBlock())
442 return Error("Malformed BlockInfoBlock");
443 break;
444 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000445 switch (ReadPCHBlock()) {
446 case Success:
447 break;
448
449 case Failure:
Douglas Gregorc34897d2009-04-09 22:27:44 +0000450 return true;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000451
452 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000453 // FIXME: We could consider reading through to the end of this
454 // PCH block, skipping subblocks, to see if there are other
455 // PCH blocks elsewhere.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000456 return false;
457 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000458 break;
459 default:
460 if (Stream.SkipBlock())
461 return Error("Malformed block record");
462 break;
463 }
464 }
465
466 // Load the translation unit declaration
467 ReadDeclRecord(DeclOffsets[0], 0);
468
469 return false;
470}
471
Douglas Gregor179cfb12009-04-10 20:39:37 +0000472/// \brief Parse the record that corresponds to a LangOptions data
473/// structure.
474///
475/// This routine compares the language options used to generate the
476/// PCH file against the language options set for the current
477/// compilation. For each option, we classify differences between the
478/// two compiler states as either "benign" or "important". Benign
479/// differences don't matter, and we accept them without complaint
480/// (and without modifying the language options). Differences between
481/// the states for important options cause the PCH file to be
482/// unusable, so we emit a warning and return true to indicate that
483/// there was an error.
484///
485/// \returns true if the PCH file is unacceptable, false otherwise.
486bool PCHReader::ParseLanguageOptions(
487 const llvm::SmallVectorImpl<uint64_t> &Record) {
488 const LangOptions &LangOpts = Context.getLangOptions();
489#define PARSE_LANGOPT_BENIGN(Option) ++Idx
490#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
491 if (Record[Idx] != LangOpts.Option) { \
492 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
493 Diag(diag::note_ignoring_pch) << FileName; \
494 return true; \
495 } \
496 ++Idx
497
498 unsigned Idx = 0;
499 PARSE_LANGOPT_BENIGN(Trigraphs);
500 PARSE_LANGOPT_BENIGN(BCPLComment);
501 PARSE_LANGOPT_BENIGN(DollarIdents);
502 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
503 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
504 PARSE_LANGOPT_BENIGN(ImplicitInt);
505 PARSE_LANGOPT_BENIGN(Digraphs);
506 PARSE_LANGOPT_BENIGN(HexFloats);
507 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
508 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
509 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
510 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
511 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
512 PARSE_LANGOPT_BENIGN(CXXOperatorName);
513 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
514 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
515 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
516 PARSE_LANGOPT_BENIGN(PascalStrings);
517 PARSE_LANGOPT_BENIGN(Boolean);
518 PARSE_LANGOPT_BENIGN(WritableStrings);
519 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
520 diag::warn_pch_lax_vector_conversions);
521 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
522 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
523 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
524 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
525 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
526 diag::warn_pch_thread_safe_statics);
527 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
528 PARSE_LANGOPT_BENIGN(EmitAllDecls);
529 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
530 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
531 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
532 diag::warn_pch_heinous_extensions);
533 // FIXME: Most of the options below are benign if the macro wasn't
534 // used. Unfortunately, this means that a PCH compiled without
535 // optimization can't be used with optimization turned on, even
536 // though the only thing that changes is whether __OPTIMIZE__ was
537 // defined... but if __OPTIMIZE__ never showed up in the header, it
538 // doesn't matter. We could consider making this some special kind
539 // of check.
540 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
541 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
542 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
543 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
544 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
545 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
546 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
547 Diag(diag::warn_pch_gc_mode)
548 << (unsigned)Record[Idx] << LangOpts.getGCMode();
549 Diag(diag::note_ignoring_pch) << FileName;
550 return true;
551 }
552 ++Idx;
553 PARSE_LANGOPT_BENIGN(getVisibilityMode());
554 PARSE_LANGOPT_BENIGN(InstantiationDepth);
555#undef PARSE_LANGOPT_IRRELEVANT
556#undef PARSE_LANGOPT_BENIGN
557
558 return false;
559}
560
Douglas Gregorc34897d2009-04-09 22:27:44 +0000561/// \brief Read and return the type at the given offset.
562///
563/// This routine actually reads the record corresponding to the type
564/// at the given offset in the bitstream. It is a helper routine for
565/// GetType, which deals with reading type IDs.
566QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
567 Stream.JumpToBit(Offset);
568 RecordData Record;
569 unsigned Code = Stream.ReadCode();
570 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
571 case pch::TYPE_FIXED_WIDTH_INT: {
572 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
573 return Context.getFixedWidthIntType(Record[0], Record[1]);
574 }
575
576 case pch::TYPE_COMPLEX: {
577 assert(Record.size() == 1 && "Incorrect encoding of complex type");
578 QualType ElemType = GetType(Record[0]);
579 return Context.getComplexType(ElemType);
580 }
581
582 case pch::TYPE_POINTER: {
583 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
584 QualType PointeeType = GetType(Record[0]);
585 return Context.getPointerType(PointeeType);
586 }
587
588 case pch::TYPE_BLOCK_POINTER: {
589 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
590 QualType PointeeType = GetType(Record[0]);
591 return Context.getBlockPointerType(PointeeType);
592 }
593
594 case pch::TYPE_LVALUE_REFERENCE: {
595 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
596 QualType PointeeType = GetType(Record[0]);
597 return Context.getLValueReferenceType(PointeeType);
598 }
599
600 case pch::TYPE_RVALUE_REFERENCE: {
601 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
602 QualType PointeeType = GetType(Record[0]);
603 return Context.getRValueReferenceType(PointeeType);
604 }
605
606 case pch::TYPE_MEMBER_POINTER: {
607 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
608 QualType PointeeType = GetType(Record[0]);
609 QualType ClassType = GetType(Record[1]);
610 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
611 }
612
613 // FIXME: Several other kinds of types to deserialize here!
614 default:
Douglas Gregorac8f2802009-04-10 17:25:41 +0000615 assert(false && "Unable to deserialize this type");
Douglas Gregorc34897d2009-04-09 22:27:44 +0000616 break;
617 }
618
619 // Suppress a GCC warning
620 return QualType();
621}
622
623/// \brief Note that we have loaded the declaration with the given
624/// Index.
625///
626/// This routine notes that this declaration has already been loaded,
627/// so that future GetDecl calls will return this declaration rather
628/// than trying to load a new declaration.
629inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
630 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
631 DeclAlreadyLoaded[Index] = true;
632 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
633}
634
635/// \brief Read the declaration at the given offset from the PCH file.
636Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
637 Decl *D = 0;
638 Stream.JumpToBit(Offset);
639 RecordData Record;
640 unsigned Code = Stream.ReadCode();
641 unsigned Idx = 0;
642 PCHDeclReader Reader(*this, Record, Idx);
643 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
644 case pch::DECL_TRANSLATION_UNIT:
645 assert(Index == 0 && "Translation unit must be at index 0");
646 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
647 D = Context.getTranslationUnitDecl();
648 LoadedDecl(Index, D);
649 break;
650
651 case pch::DECL_TYPEDEF: {
652 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
653 0, QualType());
654 LoadedDecl(Index, Typedef);
655 Reader.VisitTypedefDecl(Typedef);
656 D = Typedef;
657 break;
658 }
659
660 case pch::DECL_VAR: {
661 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
662 VarDecl::None, SourceLocation());
663 LoadedDecl(Index, Var);
664 Reader.VisitVarDecl(Var);
665 D = Var;
666 break;
667 }
668
669 default:
670 assert(false && "Cannot de-serialize this kind of declaration");
671 break;
672 }
673
674 // If this declaration is also a declaration context, get the
675 // offsets for its tables of lexical and visible declarations.
676 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
677 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
678 if (Offsets.first || Offsets.second) {
679 DC->setHasExternalLexicalStorage(Offsets.first != 0);
680 DC->setHasExternalVisibleStorage(Offsets.second != 0);
681 DeclContextOffsets[DC] = Offsets;
682 }
683 }
684 assert(Idx == Record.size());
685
686 return D;
687}
688
Douglas Gregorac8f2802009-04-10 17:25:41 +0000689QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000690 unsigned Quals = ID & 0x07;
691 unsigned Index = ID >> 3;
692
693 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
694 QualType T;
695 switch ((pch::PredefinedTypeIDs)Index) {
696 case pch::PREDEF_TYPE_NULL_ID: return QualType();
697 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
698 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
699
700 case pch::PREDEF_TYPE_CHAR_U_ID:
701 case pch::PREDEF_TYPE_CHAR_S_ID:
702 // FIXME: Check that the signedness of CharTy is correct!
703 T = Context.CharTy;
704 break;
705
706 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
707 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
708 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
709 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
710 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
711 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
712 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
713 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
714 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
715 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
716 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
717 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
718 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
719 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
720 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
721 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
722 }
723
724 assert(!T.isNull() && "Unknown predefined type");
725 return T.getQualifiedType(Quals);
726 }
727
728 Index -= pch::NUM_PREDEF_TYPE_IDS;
729 if (!TypeAlreadyLoaded[Index]) {
730 // Load the type from the PCH file.
731 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
732 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
733 TypeAlreadyLoaded[Index] = true;
734 }
735
736 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
737}
738
Douglas Gregorac8f2802009-04-10 17:25:41 +0000739Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000740 if (ID == 0)
741 return 0;
742
743 unsigned Index = ID - 1;
744 if (DeclAlreadyLoaded[Index])
745 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
746
747 // Load the declaration from the PCH file.
748 return ReadDeclRecord(DeclOffsets[Index], Index);
749}
750
751bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +0000752 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000753 assert(DC->hasExternalLexicalStorage() &&
754 "DeclContext has no lexical decls in storage");
755 uint64_t Offset = DeclContextOffsets[DC].first;
756 assert(Offset && "DeclContext has no lexical decls in storage");
757
758 // Load the record containing all of the declarations lexically in
759 // this context.
760 Stream.JumpToBit(Offset);
761 RecordData Record;
762 unsigned Code = Stream.ReadCode();
763 unsigned RecCode = Stream.ReadRecord(Code, Record);
764 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
765
766 // Load all of the declaration IDs
767 Decls.clear();
768 Decls.insert(Decls.end(), Record.begin(), Record.end());
769 return false;
770}
771
772bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
773 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
774 assert(DC->hasExternalVisibleStorage() &&
775 "DeclContext has no visible decls in storage");
776 uint64_t Offset = DeclContextOffsets[DC].second;
777 assert(Offset && "DeclContext has no visible decls in storage");
778
779 // Load the record containing all of the declarations visible in
780 // this context.
781 Stream.JumpToBit(Offset);
782 RecordData Record;
783 unsigned Code = Stream.ReadCode();
784 unsigned RecCode = Stream.ReadRecord(Code, Record);
785 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
786 if (Record.size() == 0)
787 return false;
788
789 Decls.clear();
790
791 unsigned Idx = 0;
792 // llvm::SmallVector<uintptr_t, 16> DeclIDs;
793 while (Idx < Record.size()) {
794 Decls.push_back(VisibleDeclaration());
795 Decls.back().Name = ReadDeclarationName(Record, Idx);
796
797 // FIXME: Don't actually read anything here!
798 unsigned Size = Record[Idx++];
799 llvm::SmallVector<unsigned, 4> & LoadedDecls
800 = Decls.back().Declarations;
801 LoadedDecls.reserve(Size);
802 for (unsigned I = 0; I < Size; ++I)
803 LoadedDecls.push_back(Record[Idx++]);
804 }
805
806 return false;
807}
808
809void PCHReader::PrintStats() {
810 std::fprintf(stderr, "*** PCH Statistics:\n");
811
812 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
813 TypeAlreadyLoaded.end(),
814 true);
815 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
816 DeclAlreadyLoaded.end(),
817 true);
818 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
819 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
820 ((float)NumTypesLoaded/(float)TypeAlreadyLoaded.size() * 100));
821 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
822 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
823 ((float)NumDeclsLoaded/(float)DeclAlreadyLoaded.size() * 100));
824 std::fprintf(stderr, "\n");
825}
826
827const IdentifierInfo *PCHReader::GetIdentifierInfo(const RecordData &Record,
828 unsigned &Idx) {
829 // FIXME: we need unique IDs for identifiers.
830 std::string Str;
831 unsigned Length = Record[Idx++];
832 Str.resize(Length);
833 for (unsigned I = 0; I != Length; ++I)
834 Str[I] = Record[Idx++];
835 return &Context.Idents.get(Str);
836}
837
838DeclarationName
839PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
840 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
841 switch (Kind) {
842 case DeclarationName::Identifier:
843 return DeclarationName(GetIdentifierInfo(Record, Idx));
844
845 case DeclarationName::ObjCZeroArgSelector:
846 case DeclarationName::ObjCOneArgSelector:
847 case DeclarationName::ObjCMultiArgSelector:
848 assert(false && "Unable to de-serialize Objective-C selectors");
849 break;
850
851 case DeclarationName::CXXConstructorName:
852 return Context.DeclarationNames.getCXXConstructorName(
853 GetType(Record[Idx++]));
854
855 case DeclarationName::CXXDestructorName:
856 return Context.DeclarationNames.getCXXDestructorName(
857 GetType(Record[Idx++]));
858
859 case DeclarationName::CXXConversionFunctionName:
860 return Context.DeclarationNames.getCXXConversionFunctionName(
861 GetType(Record[Idx++]));
862
863 case DeclarationName::CXXOperatorName:
864 return Context.DeclarationNames.getCXXOperatorName(
865 (OverloadedOperatorKind)Record[Idx++]);
866
867 case DeclarationName::CXXUsingDirective:
868 return DeclarationName::getUsingDirectiveName();
869 }
870
871 // Required to silence GCC warning
872 return DeclarationName();
873}
Douglas Gregor179cfb12009-04-10 20:39:37 +0000874
875DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
876 return PP.getDiagnostics().Report(FullSourceLoc(SourceLocation(),
877 Context.getSourceManager()),
878 DiagID);
879}