blob: eaba610137dd23ff63674830618fb90c9acc8c74 [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.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000274 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000275
276 // Remember that we saw this macro last so that we add the tokens that
277 // form its body to it.
278 LastMacro = MI;
279 break;
280 }
281
282 case pch::PP_TOKEN: {
283 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
284 // pretend we didn't see this.
285 if (LastMacro == 0) break;
286
287 Token Tok;
288 Tok.startToken();
289 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
290 Tok.setLength(Record[1]);
291 unsigned IdentInfo = Record[2];
292 IdentInfo = IdentInfo; // FIXME: Handle this right.
293 Tok.setKind((tok::TokenKind)Record[3]);
294 Tok.setFlag((Token::TokenFlags)Record[4]);
295 LastMacro->AddTokenToBody(Tok);
296 break;
297 }
298 }
299 }
300}
301
Douglas Gregor179cfb12009-04-10 20:39:37 +0000302PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
303 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
304 Error("Malformed block record");
305 return Failure;
306 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000307
308 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000309 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000310 while (!Stream.AtEndOfStream()) {
311 unsigned Code = Stream.ReadCode();
312 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000313 if (Stream.ReadBlockEnd()) {
314 Error("Error at end of module block");
315 return Failure;
316 }
317 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000318 }
319
320 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
321 switch (Stream.ReadSubBlockID()) {
322 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
323 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
324 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000325 if (Stream.SkipBlock()) {
326 Error("Malformed block record");
327 return Failure;
328 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000329 break;
330
Douglas Gregorab1cef72009-04-10 03:52:48 +0000331 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000332 if (ReadSourceManagerBlock()) {
333 Error("Malformed source manager block");
334 return Failure;
335 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000336 break;
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000337
338 case pch::PREPROCESSOR_BLOCK_ID:
339 if (ReadPreprocessorBlock()) {
340 Error("Malformed preprocessor block");
341 return Failure;
342 }
343 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000344 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000345 continue;
346 }
347
348 if (Code == llvm::bitc::DEFINE_ABBREV) {
349 Stream.ReadAbbrevRecord();
350 continue;
351 }
352
353 // Read and process a record.
354 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000355 const char *BlobStart = 0;
356 unsigned BlobLen = 0;
357 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
358 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000359 default: // Default behavior: ignore.
360 break;
361
362 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000363 if (!TypeOffsets.empty()) {
364 Error("Duplicate TYPE_OFFSET record in PCH file");
365 return Failure;
366 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000367 TypeOffsets.swap(Record);
368 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
369 break;
370
371 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000372 if (!DeclOffsets.empty()) {
373 Error("Duplicate DECL_OFFSET record in PCH file");
374 return Failure;
375 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000376 DeclOffsets.swap(Record);
377 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
378 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000379
380 case pch::LANGUAGE_OPTIONS:
381 if (ParseLanguageOptions(Record))
382 return IgnorePCH;
383 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000384
385 case pch::TARGET_TRIPLE:
386 std::string TargetTriple(BlobStart, BlobLen);
387 if (TargetTriple != Context.Target.getTargetTriple()) {
388 Diag(diag::warn_pch_target_triple)
389 << TargetTriple << Context.Target.getTargetTriple();
390 Diag(diag::note_ignoring_pch) << FileName;
391 return IgnorePCH;
392 }
393 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000394 }
395 }
396
Douglas Gregor179cfb12009-04-10 20:39:37 +0000397 Error("Premature end of bitstream");
398 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000399}
400
401PCHReader::~PCHReader() { }
402
403bool PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000404 // Set the PCH file name.
405 this->FileName = FileName;
406
Douglas Gregorc34897d2009-04-09 22:27:44 +0000407 // Open the PCH file.
408 std::string ErrStr;
409 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
410 if (!Buffer)
411 return Error(ErrStr.c_str());
412
413 // Initialize the stream
414 Stream.init((const unsigned char *)Buffer->getBufferStart(),
415 (const unsigned char *)Buffer->getBufferEnd());
416
417 // Sniff for the signature.
418 if (Stream.Read(8) != 'C' ||
419 Stream.Read(8) != 'P' ||
420 Stream.Read(8) != 'C' ||
421 Stream.Read(8) != 'H')
422 return Error("Not a PCH file");
423
424 // We expect a number of well-defined blocks, though we don't necessarily
425 // need to understand them all.
426 while (!Stream.AtEndOfStream()) {
427 unsigned Code = Stream.ReadCode();
428
429 if (Code != llvm::bitc::ENTER_SUBBLOCK)
430 return Error("Invalid record at top-level");
431
432 unsigned BlockID = Stream.ReadSubBlockID();
433
434 // We only know the PCH subblock ID.
435 switch (BlockID) {
436 case llvm::bitc::BLOCKINFO_BLOCK_ID:
437 if (Stream.ReadBlockInfoBlock())
438 return Error("Malformed BlockInfoBlock");
439 break;
440 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000441 switch (ReadPCHBlock()) {
442 case Success:
443 break;
444
445 case Failure:
Douglas Gregorc34897d2009-04-09 22:27:44 +0000446 return true;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000447
448 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000449 // FIXME: We could consider reading through to the end of this
450 // PCH block, skipping subblocks, to see if there are other
451 // PCH blocks elsewhere.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000452 return false;
453 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000454 break;
455 default:
456 if (Stream.SkipBlock())
457 return Error("Malformed block record");
458 break;
459 }
460 }
461
462 // Load the translation unit declaration
463 ReadDeclRecord(DeclOffsets[0], 0);
464
Chris Lattner9a1c0292009-04-10 22:13:17 +0000465 // If everything looks like it will be ok, then the PCH file load succeeded.
466 // Since the PCH file contains everything that is in the preprocessor's
467 // predefines buffer (and we validated that they are the same) clear out the
468 // predefines buffer so that it doesn't get processed again.
469 PP.setPredefines("");
470
Douglas Gregorc34897d2009-04-09 22:27:44 +0000471 return false;
472}
473
Douglas Gregor179cfb12009-04-10 20:39:37 +0000474/// \brief Parse the record that corresponds to a LangOptions data
475/// structure.
476///
477/// This routine compares the language options used to generate the
478/// PCH file against the language options set for the current
479/// compilation. For each option, we classify differences between the
480/// two compiler states as either "benign" or "important". Benign
481/// differences don't matter, and we accept them without complaint
482/// (and without modifying the language options). Differences between
483/// the states for important options cause the PCH file to be
484/// unusable, so we emit a warning and return true to indicate that
485/// there was an error.
486///
487/// \returns true if the PCH file is unacceptable, false otherwise.
488bool PCHReader::ParseLanguageOptions(
489 const llvm::SmallVectorImpl<uint64_t> &Record) {
490 const LangOptions &LangOpts = Context.getLangOptions();
491#define PARSE_LANGOPT_BENIGN(Option) ++Idx
492#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
493 if (Record[Idx] != LangOpts.Option) { \
494 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
495 Diag(diag::note_ignoring_pch) << FileName; \
496 return true; \
497 } \
498 ++Idx
499
500 unsigned Idx = 0;
501 PARSE_LANGOPT_BENIGN(Trigraphs);
502 PARSE_LANGOPT_BENIGN(BCPLComment);
503 PARSE_LANGOPT_BENIGN(DollarIdents);
504 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
505 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
506 PARSE_LANGOPT_BENIGN(ImplicitInt);
507 PARSE_LANGOPT_BENIGN(Digraphs);
508 PARSE_LANGOPT_BENIGN(HexFloats);
509 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
510 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
511 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
512 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
513 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
514 PARSE_LANGOPT_BENIGN(CXXOperatorName);
515 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
516 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
517 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
518 PARSE_LANGOPT_BENIGN(PascalStrings);
519 PARSE_LANGOPT_BENIGN(Boolean);
520 PARSE_LANGOPT_BENIGN(WritableStrings);
521 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
522 diag::warn_pch_lax_vector_conversions);
523 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
524 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
525 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
526 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
527 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
528 diag::warn_pch_thread_safe_statics);
529 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
530 PARSE_LANGOPT_BENIGN(EmitAllDecls);
531 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
532 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
533 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
534 diag::warn_pch_heinous_extensions);
535 // FIXME: Most of the options below are benign if the macro wasn't
536 // used. Unfortunately, this means that a PCH compiled without
537 // optimization can't be used with optimization turned on, even
538 // though the only thing that changes is whether __OPTIMIZE__ was
539 // defined... but if __OPTIMIZE__ never showed up in the header, it
540 // doesn't matter. We could consider making this some special kind
541 // of check.
542 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
543 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
544 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
545 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
546 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
547 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
548 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
549 Diag(diag::warn_pch_gc_mode)
550 << (unsigned)Record[Idx] << LangOpts.getGCMode();
551 Diag(diag::note_ignoring_pch) << FileName;
552 return true;
553 }
554 ++Idx;
555 PARSE_LANGOPT_BENIGN(getVisibilityMode());
556 PARSE_LANGOPT_BENIGN(InstantiationDepth);
557#undef PARSE_LANGOPT_IRRELEVANT
558#undef PARSE_LANGOPT_BENIGN
559
560 return false;
561}
562
Douglas Gregorc34897d2009-04-09 22:27:44 +0000563/// \brief Read and return the type at the given offset.
564///
565/// This routine actually reads the record corresponding to the type
566/// at the given offset in the bitstream. It is a helper routine for
567/// GetType, which deals with reading type IDs.
568QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
569 Stream.JumpToBit(Offset);
570 RecordData Record;
571 unsigned Code = Stream.ReadCode();
572 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
573 case pch::TYPE_FIXED_WIDTH_INT: {
574 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
575 return Context.getFixedWidthIntType(Record[0], Record[1]);
576 }
577
578 case pch::TYPE_COMPLEX: {
579 assert(Record.size() == 1 && "Incorrect encoding of complex type");
580 QualType ElemType = GetType(Record[0]);
581 return Context.getComplexType(ElemType);
582 }
583
584 case pch::TYPE_POINTER: {
585 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
586 QualType PointeeType = GetType(Record[0]);
587 return Context.getPointerType(PointeeType);
588 }
589
590 case pch::TYPE_BLOCK_POINTER: {
591 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
592 QualType PointeeType = GetType(Record[0]);
593 return Context.getBlockPointerType(PointeeType);
594 }
595
596 case pch::TYPE_LVALUE_REFERENCE: {
597 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
598 QualType PointeeType = GetType(Record[0]);
599 return Context.getLValueReferenceType(PointeeType);
600 }
601
602 case pch::TYPE_RVALUE_REFERENCE: {
603 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
604 QualType PointeeType = GetType(Record[0]);
605 return Context.getRValueReferenceType(PointeeType);
606 }
607
608 case pch::TYPE_MEMBER_POINTER: {
609 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
610 QualType PointeeType = GetType(Record[0]);
611 QualType ClassType = GetType(Record[1]);
612 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
613 }
614
615 // FIXME: Several other kinds of types to deserialize here!
616 default:
Douglas Gregorac8f2802009-04-10 17:25:41 +0000617 assert(false && "Unable to deserialize this type");
Douglas Gregorc34897d2009-04-09 22:27:44 +0000618 break;
619 }
620
621 // Suppress a GCC warning
622 return QualType();
623}
624
625/// \brief Note that we have loaded the declaration with the given
626/// Index.
627///
628/// This routine notes that this declaration has already been loaded,
629/// so that future GetDecl calls will return this declaration rather
630/// than trying to load a new declaration.
631inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
632 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
633 DeclAlreadyLoaded[Index] = true;
634 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
635}
636
637/// \brief Read the declaration at the given offset from the PCH file.
638Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
639 Decl *D = 0;
640 Stream.JumpToBit(Offset);
641 RecordData Record;
642 unsigned Code = Stream.ReadCode();
643 unsigned Idx = 0;
644 PCHDeclReader Reader(*this, Record, Idx);
645 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
646 case pch::DECL_TRANSLATION_UNIT:
647 assert(Index == 0 && "Translation unit must be at index 0");
648 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
649 D = Context.getTranslationUnitDecl();
650 LoadedDecl(Index, D);
651 break;
652
653 case pch::DECL_TYPEDEF: {
654 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
655 0, QualType());
656 LoadedDecl(Index, Typedef);
657 Reader.VisitTypedefDecl(Typedef);
658 D = Typedef;
659 break;
660 }
661
662 case pch::DECL_VAR: {
663 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
664 VarDecl::None, SourceLocation());
665 LoadedDecl(Index, Var);
666 Reader.VisitVarDecl(Var);
667 D = Var;
668 break;
669 }
670
671 default:
672 assert(false && "Cannot de-serialize this kind of declaration");
673 break;
674 }
675
676 // If this declaration is also a declaration context, get the
677 // offsets for its tables of lexical and visible declarations.
678 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
679 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
680 if (Offsets.first || Offsets.second) {
681 DC->setHasExternalLexicalStorage(Offsets.first != 0);
682 DC->setHasExternalVisibleStorage(Offsets.second != 0);
683 DeclContextOffsets[DC] = Offsets;
684 }
685 }
686 assert(Idx == Record.size());
687
688 return D;
689}
690
Douglas Gregorac8f2802009-04-10 17:25:41 +0000691QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000692 unsigned Quals = ID & 0x07;
693 unsigned Index = ID >> 3;
694
695 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
696 QualType T;
697 switch ((pch::PredefinedTypeIDs)Index) {
698 case pch::PREDEF_TYPE_NULL_ID: return QualType();
699 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
700 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
701
702 case pch::PREDEF_TYPE_CHAR_U_ID:
703 case pch::PREDEF_TYPE_CHAR_S_ID:
704 // FIXME: Check that the signedness of CharTy is correct!
705 T = Context.CharTy;
706 break;
707
708 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
709 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
710 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
711 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
712 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
713 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
714 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
715 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
716 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
717 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
718 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
719 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
720 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
721 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
722 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
723 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
724 }
725
726 assert(!T.isNull() && "Unknown predefined type");
727 return T.getQualifiedType(Quals);
728 }
729
730 Index -= pch::NUM_PREDEF_TYPE_IDS;
731 if (!TypeAlreadyLoaded[Index]) {
732 // Load the type from the PCH file.
733 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
734 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
735 TypeAlreadyLoaded[Index] = true;
736 }
737
738 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
739}
740
Douglas Gregorac8f2802009-04-10 17:25:41 +0000741Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000742 if (ID == 0)
743 return 0;
744
745 unsigned Index = ID - 1;
746 if (DeclAlreadyLoaded[Index])
747 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
748
749 // Load the declaration from the PCH file.
750 return ReadDeclRecord(DeclOffsets[Index], Index);
751}
752
753bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +0000754 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000755 assert(DC->hasExternalLexicalStorage() &&
756 "DeclContext has no lexical decls in storage");
757 uint64_t Offset = DeclContextOffsets[DC].first;
758 assert(Offset && "DeclContext has no lexical decls in storage");
759
760 // Load the record containing all of the declarations lexically in
761 // this context.
762 Stream.JumpToBit(Offset);
763 RecordData Record;
764 unsigned Code = Stream.ReadCode();
765 unsigned RecCode = Stream.ReadRecord(Code, Record);
766 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
767
768 // Load all of the declaration IDs
769 Decls.clear();
770 Decls.insert(Decls.end(), Record.begin(), Record.end());
771 return false;
772}
773
774bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
775 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
776 assert(DC->hasExternalVisibleStorage() &&
777 "DeclContext has no visible decls in storage");
778 uint64_t Offset = DeclContextOffsets[DC].second;
779 assert(Offset && "DeclContext has no visible decls in storage");
780
781 // Load the record containing all of the declarations visible in
782 // this context.
783 Stream.JumpToBit(Offset);
784 RecordData Record;
785 unsigned Code = Stream.ReadCode();
786 unsigned RecCode = Stream.ReadRecord(Code, Record);
787 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
788 if (Record.size() == 0)
789 return false;
790
791 Decls.clear();
792
793 unsigned Idx = 0;
794 // llvm::SmallVector<uintptr_t, 16> DeclIDs;
795 while (Idx < Record.size()) {
796 Decls.push_back(VisibleDeclaration());
797 Decls.back().Name = ReadDeclarationName(Record, Idx);
798
799 // FIXME: Don't actually read anything here!
800 unsigned Size = Record[Idx++];
801 llvm::SmallVector<unsigned, 4> & LoadedDecls
802 = Decls.back().Declarations;
803 LoadedDecls.reserve(Size);
804 for (unsigned I = 0; I < Size; ++I)
805 LoadedDecls.push_back(Record[Idx++]);
806 }
807
808 return false;
809}
810
811void PCHReader::PrintStats() {
812 std::fprintf(stderr, "*** PCH Statistics:\n");
813
814 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
815 TypeAlreadyLoaded.end(),
816 true);
817 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
818 DeclAlreadyLoaded.end(),
819 true);
820 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
821 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
822 ((float)NumTypesLoaded/(float)TypeAlreadyLoaded.size() * 100));
823 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
824 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
825 ((float)NumDeclsLoaded/(float)DeclAlreadyLoaded.size() * 100));
826 std::fprintf(stderr, "\n");
827}
828
829const IdentifierInfo *PCHReader::GetIdentifierInfo(const RecordData &Record,
830 unsigned &Idx) {
831 // FIXME: we need unique IDs for identifiers.
832 std::string Str;
833 unsigned Length = Record[Idx++];
834 Str.resize(Length);
835 for (unsigned I = 0; I != Length; ++I)
836 Str[I] = Record[Idx++];
837 return &Context.Idents.get(Str);
838}
839
840DeclarationName
841PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
842 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
843 switch (Kind) {
844 case DeclarationName::Identifier:
845 return DeclarationName(GetIdentifierInfo(Record, Idx));
846
847 case DeclarationName::ObjCZeroArgSelector:
848 case DeclarationName::ObjCOneArgSelector:
849 case DeclarationName::ObjCMultiArgSelector:
850 assert(false && "Unable to de-serialize Objective-C selectors");
851 break;
852
853 case DeclarationName::CXXConstructorName:
854 return Context.DeclarationNames.getCXXConstructorName(
855 GetType(Record[Idx++]));
856
857 case DeclarationName::CXXDestructorName:
858 return Context.DeclarationNames.getCXXDestructorName(
859 GetType(Record[Idx++]));
860
861 case DeclarationName::CXXConversionFunctionName:
862 return Context.DeclarationNames.getCXXConversionFunctionName(
863 GetType(Record[Idx++]));
864
865 case DeclarationName::CXXOperatorName:
866 return Context.DeclarationNames.getCXXOperatorName(
867 (OverloadedOperatorKind)Record[Idx++]);
868
869 case DeclarationName::CXXUsingDirective:
870 return DeclarationName::getUsingDirectiveName();
871 }
872
873 // Required to silence GCC warning
874 return DeclarationName();
875}
Douglas Gregor179cfb12009-04-10 20:39:37 +0000876
877DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
878 return PP.getDiagnostics().Report(FullSourceLoc(SourceLocation(),
879 Context.getSourceManager()),
880 DiagID);
881}