blob: b21beed307a2caba9821977ed47e5ada0d50546a [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 Gregorb3a04c82009-04-10 23:10:45 +0000119/// \brief Check the contents of the predefines buffer against the
120/// contents of the predefines buffer used to build the PCH file.
121///
122/// The contents of the two predefines buffers should be the same. If
123/// not, then some command-line option changed the preprocessor state
124/// and we must reject the PCH file.
125///
126/// \param PCHPredef The start of the predefines buffer in the PCH
127/// file.
128///
129/// \param PCHPredefLen The length of the predefines buffer in the PCH
130/// file.
131///
132/// \param PCHBufferID The FileID for the PCH predefines buffer.
133///
134/// \returns true if there was a mismatch (in which case the PCH file
135/// should be ignored), or false otherwise.
136bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
137 unsigned PCHPredefLen,
138 FileID PCHBufferID) {
139 const char *Predef = PP.getPredefines().c_str();
140 unsigned PredefLen = PP.getPredefines().size();
141
142 // If the two predefines buffers compare equal, we're done!.
143 if (PredefLen == PCHPredefLen &&
144 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
145 return false;
146
147 // The predefines buffers are different. Produce a reasonable
148 // diagnostic showing where they are different.
149
150 // The source locations (potentially in the two different predefines
151 // buffers)
152 SourceLocation Loc1, Loc2;
153 SourceManager &SourceMgr = PP.getSourceManager();
154
155 // Create a source buffer for our predefines string, so
156 // that we can build a diagnostic that points into that
157 // source buffer.
158 FileID BufferID;
159 if (Predef && Predef[0]) {
160 llvm::MemoryBuffer *Buffer
161 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
162 "<built-in>");
163 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
164 }
165
166 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
167 std::pair<const char *, const char *> Locations
168 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
169
170 if (Locations.first != Predef + MinLen) {
171 // We found the location in the two buffers where there is a
172 // difference. Form source locations to point there (in both
173 // buffers).
174 unsigned Offset = Locations.first - Predef;
175 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
176 .getFileLocWithOffset(Offset);
177 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
178 .getFileLocWithOffset(Offset);
179 } else if (PredefLen > PCHPredefLen) {
180 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
181 .getFileLocWithOffset(MinLen);
182 } else {
183 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
184 .getFileLocWithOffset(MinLen);
185 }
186
187 Diag(Loc1, diag::warn_pch_preprocessor);
188 if (Loc2.isValid())
189 Diag(Loc2, diag::note_predef_in_pch);
190 Diag(diag::note_ignoring_pch) << FileName;
191 return true;
192}
193
Douglas Gregorab1cef72009-04-10 03:52:48 +0000194/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000195PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000196 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000197 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
198 Error("Malformed source manager block record");
199 return Failure;
200 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000201
202 SourceManager &SourceMgr = Context.getSourceManager();
203 RecordData Record;
204 while (true) {
205 unsigned Code = Stream.ReadCode();
206 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000207 if (Stream.ReadBlockEnd()) {
208 Error("Error at end of Source Manager block");
209 return Failure;
210 }
211
212 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000213 }
214
215 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
216 // No known subblocks, always skip them.
217 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000218 if (Stream.SkipBlock()) {
219 Error("Malformed block record");
220 return Failure;
221 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000222 continue;
223 }
224
225 if (Code == llvm::bitc::DEFINE_ABBREV) {
226 Stream.ReadAbbrevRecord();
227 continue;
228 }
229
230 // Read a record.
231 const char *BlobStart;
232 unsigned BlobLen;
233 Record.clear();
234 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
235 default: // Default behavior: ignore.
236 break;
237
238 case pch::SM_SLOC_FILE_ENTRY: {
239 // FIXME: We would really like to delay the creation of this
240 // FileEntry until it is actually required, e.g., when producing
241 // a diagnostic with a source location in this file.
242 const FileEntry *File
243 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
244 // FIXME: Error recovery if file cannot be found.
245 SourceMgr.createFileID(File,
246 SourceLocation::getFromRawEncoding(Record[1]),
247 (CharacteristicKind)Record[2]);
248 break;
249 }
250
251 case pch::SM_SLOC_BUFFER_ENTRY: {
252 const char *Name = BlobStart;
253 unsigned Code = Stream.ReadCode();
254 Record.clear();
255 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
256 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000257 llvm::MemoryBuffer *Buffer
258 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
259 BlobStart + BlobLen - 1,
260 Name);
261 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
262
263 if (strcmp(Name, "<built-in>") == 0
264 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
265 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000266 break;
267 }
268
269 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
270 SourceLocation SpellingLoc
271 = SourceLocation::getFromRawEncoding(Record[1]);
272 SourceMgr.createInstantiationLoc(
273 SpellingLoc,
274 SourceLocation::getFromRawEncoding(Record[2]),
275 SourceLocation::getFromRawEncoding(Record[3]),
276 Lexer::MeasureTokenLength(SpellingLoc,
277 SourceMgr));
278 break;
279 }
280
281 }
282 }
283}
284
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000285bool PCHReader::ReadPreprocessorBlock() {
286 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
287 return Error("Malformed preprocessor block record");
288
289 std::string CurName; // FIXME: HACK.
290 RecordData Record;
291 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
292 MacroInfo *LastMacro = 0;
293
294 while (true) {
295 unsigned Code = Stream.ReadCode();
296 switch (Code) {
297 case llvm::bitc::END_BLOCK:
298 if (Stream.ReadBlockEnd())
299 return Error("Error at end of preprocessor block");
300 return false;
301
302 case llvm::bitc::ENTER_SUBBLOCK:
303 // No known subblocks, always skip them.
304 Stream.ReadSubBlockID();
305 if (Stream.SkipBlock())
306 return Error("Malformed block record");
307 continue;
308
309 case llvm::bitc::DEFINE_ABBREV:
310 Stream.ReadAbbrevRecord();
311 continue;
312 default: break;
313 }
314
315 // Read a record.
316 Record.clear();
317 pch::PreprocessorRecordTypes RecType =
318 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
319 switch (RecType) {
320 default: // Default behavior: ignore unknown records.
321 break;
322
323 case pch::PP_MACRO_NAME:
324 // Set CurName. FIXME: This is a hack and should be removed when we have
325 // identifier id's.
326 CurName.clear();
327 for (unsigned i = 0, e = Record.size(); i != e; ++i)
328 CurName += (char)Record[i];
329 break;
330
331 case pch::PP_MACRO_OBJECT_LIKE:
332 case pch::PP_MACRO_FUNCTION_LIKE: {
333 unsigned IdentInfo = Record[0];
334 IdentInfo = IdentInfo; // FIXME: Decode into identifier info*.
335 assert(!CurName.empty());
336 IdentifierInfo *II = PP.getIdentifierInfo(CurName.c_str());
337
338 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
339 bool isUsed = Record[2];
340
341 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
342 MI->setIsUsed(isUsed);
343
344 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
345 // Decode function-like macro info.
346 bool isC99VarArgs = Record[3];
347 bool isGNUVarArgs = Record[4];
348 MacroArgs.clear();
349 unsigned NumArgs = Record[5];
350 for (unsigned i = 0; i != NumArgs; ++i)
351 ; // FIXME: Decode macro arg names: MacroArgs.push_back(Record[6+i]);
352
353 // Install function-like macro info.
354 MI->setIsFunctionLike();
355 if (isC99VarArgs) MI->setIsC99Varargs();
356 if (isGNUVarArgs) MI->setIsGNUVarargs();
357 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
358 PP.getPreprocessorAllocator());
359 }
360
361 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000362 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000363
364 // Remember that we saw this macro last so that we add the tokens that
365 // form its body to it.
366 LastMacro = MI;
367 break;
368 }
369
370 case pch::PP_TOKEN: {
371 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
372 // pretend we didn't see this.
373 if (LastMacro == 0) break;
374
375 Token Tok;
376 Tok.startToken();
377 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
378 Tok.setLength(Record[1]);
379 unsigned IdentInfo = Record[2];
380 IdentInfo = IdentInfo; // FIXME: Handle this right.
381 Tok.setKind((tok::TokenKind)Record[3]);
382 Tok.setFlag((Token::TokenFlags)Record[4]);
383 LastMacro->AddTokenToBody(Tok);
384 break;
385 }
386 }
387 }
388}
389
Douglas Gregor179cfb12009-04-10 20:39:37 +0000390PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
391 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
392 Error("Malformed block record");
393 return Failure;
394 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000395
396 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000397 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000398 while (!Stream.AtEndOfStream()) {
399 unsigned Code = Stream.ReadCode();
400 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000401 if (Stream.ReadBlockEnd()) {
402 Error("Error at end of module block");
403 return Failure;
404 }
405 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000406 }
407
408 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
409 switch (Stream.ReadSubBlockID()) {
410 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
411 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
412 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000413 if (Stream.SkipBlock()) {
414 Error("Malformed block record");
415 return Failure;
416 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000417 break;
418
Douglas Gregorab1cef72009-04-10 03:52:48 +0000419 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000420 switch (ReadSourceManagerBlock()) {
421 case Success:
422 break;
423
424 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000425 Error("Malformed source manager block");
426 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000427
428 case IgnorePCH:
429 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000430 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000431 break;
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000432
433 case pch::PREPROCESSOR_BLOCK_ID:
434 if (ReadPreprocessorBlock()) {
435 Error("Malformed preprocessor block");
436 return Failure;
437 }
438 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000439 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000440 continue;
441 }
442
443 if (Code == llvm::bitc::DEFINE_ABBREV) {
444 Stream.ReadAbbrevRecord();
445 continue;
446 }
447
448 // Read and process a record.
449 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000450 const char *BlobStart = 0;
451 unsigned BlobLen = 0;
452 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
453 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000454 default: // Default behavior: ignore.
455 break;
456
457 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000458 if (!TypeOffsets.empty()) {
459 Error("Duplicate TYPE_OFFSET record in PCH file");
460 return Failure;
461 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000462 TypeOffsets.swap(Record);
463 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
464 break;
465
466 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000467 if (!DeclOffsets.empty()) {
468 Error("Duplicate DECL_OFFSET record in PCH file");
469 return Failure;
470 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000471 DeclOffsets.swap(Record);
472 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
473 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000474
475 case pch::LANGUAGE_OPTIONS:
476 if (ParseLanguageOptions(Record))
477 return IgnorePCH;
478 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000479
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000480 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000481 std::string TargetTriple(BlobStart, BlobLen);
482 if (TargetTriple != Context.Target.getTargetTriple()) {
483 Diag(diag::warn_pch_target_triple)
484 << TargetTriple << Context.Target.getTargetTriple();
485 Diag(diag::note_ignoring_pch) << FileName;
486 return IgnorePCH;
487 }
488 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000489 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000490
491 case pch::IDENTIFIER_TABLE:
492 IdentifierTable = BlobStart;
493 break;
494
495 case pch::IDENTIFIER_OFFSET:
496 if (!IdentifierData.empty()) {
497 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
498 return Failure;
499 }
500 IdentifierData.swap(Record);
501#ifndef NDEBUG
502 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
503 if ((IdentifierData[I] & 0x01) == 0) {
504 Error("Malformed identifier table in the precompiled header");
505 return Failure;
506 }
507 }
508#endif
509 break;
510 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000511 }
512
Douglas Gregor179cfb12009-04-10 20:39:37 +0000513 Error("Premature end of bitstream");
514 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000515}
516
517PCHReader::~PCHReader() { }
518
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000519PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000520 // Set the PCH file name.
521 this->FileName = FileName;
522
Douglas Gregorc34897d2009-04-09 22:27:44 +0000523 // Open the PCH file.
524 std::string ErrStr;
525 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000526 if (!Buffer) {
527 Error(ErrStr.c_str());
528 return IgnorePCH;
529 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000530
531 // Initialize the stream
532 Stream.init((const unsigned char *)Buffer->getBufferStart(),
533 (const unsigned char *)Buffer->getBufferEnd());
534
535 // Sniff for the signature.
536 if (Stream.Read(8) != 'C' ||
537 Stream.Read(8) != 'P' ||
538 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000539 Stream.Read(8) != 'H') {
540 Error("Not a PCH file");
541 return IgnorePCH;
542 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000543
544 // We expect a number of well-defined blocks, though we don't necessarily
545 // need to understand them all.
546 while (!Stream.AtEndOfStream()) {
547 unsigned Code = Stream.ReadCode();
548
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000549 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
550 Error("Invalid record at top-level");
551 return Failure;
552 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000553
554 unsigned BlockID = Stream.ReadSubBlockID();
555
556 // We only know the PCH subblock ID.
557 switch (BlockID) {
558 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000559 if (Stream.ReadBlockInfoBlock()) {
560 Error("Malformed BlockInfoBlock");
561 return Failure;
562 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000563 break;
564 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000565 switch (ReadPCHBlock()) {
566 case Success:
567 break;
568
569 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000570 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000571
572 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000573 // FIXME: We could consider reading through to the end of this
574 // PCH block, skipping subblocks, to see if there are other
575 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000576 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000577 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000578 break;
579 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000580 if (Stream.SkipBlock()) {
581 Error("Malformed block record");
582 return Failure;
583 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000584 break;
585 }
586 }
587
588 // Load the translation unit declaration
589 ReadDeclRecord(DeclOffsets[0], 0);
590
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000591 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000592}
593
Douglas Gregor179cfb12009-04-10 20:39:37 +0000594/// \brief Parse the record that corresponds to a LangOptions data
595/// structure.
596///
597/// This routine compares the language options used to generate the
598/// PCH file against the language options set for the current
599/// compilation. For each option, we classify differences between the
600/// two compiler states as either "benign" or "important". Benign
601/// differences don't matter, and we accept them without complaint
602/// (and without modifying the language options). Differences between
603/// the states for important options cause the PCH file to be
604/// unusable, so we emit a warning and return true to indicate that
605/// there was an error.
606///
607/// \returns true if the PCH file is unacceptable, false otherwise.
608bool PCHReader::ParseLanguageOptions(
609 const llvm::SmallVectorImpl<uint64_t> &Record) {
610 const LangOptions &LangOpts = Context.getLangOptions();
611#define PARSE_LANGOPT_BENIGN(Option) ++Idx
612#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
613 if (Record[Idx] != LangOpts.Option) { \
614 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
615 Diag(diag::note_ignoring_pch) << FileName; \
616 return true; \
617 } \
618 ++Idx
619
620 unsigned Idx = 0;
621 PARSE_LANGOPT_BENIGN(Trigraphs);
622 PARSE_LANGOPT_BENIGN(BCPLComment);
623 PARSE_LANGOPT_BENIGN(DollarIdents);
624 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
625 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
626 PARSE_LANGOPT_BENIGN(ImplicitInt);
627 PARSE_LANGOPT_BENIGN(Digraphs);
628 PARSE_LANGOPT_BENIGN(HexFloats);
629 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
630 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
631 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
632 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
633 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
634 PARSE_LANGOPT_BENIGN(CXXOperatorName);
635 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
636 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
637 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
638 PARSE_LANGOPT_BENIGN(PascalStrings);
639 PARSE_LANGOPT_BENIGN(Boolean);
640 PARSE_LANGOPT_BENIGN(WritableStrings);
641 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
642 diag::warn_pch_lax_vector_conversions);
643 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
644 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
645 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
646 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
647 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
648 diag::warn_pch_thread_safe_statics);
649 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
650 PARSE_LANGOPT_BENIGN(EmitAllDecls);
651 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
652 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
653 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
654 diag::warn_pch_heinous_extensions);
655 // FIXME: Most of the options below are benign if the macro wasn't
656 // used. Unfortunately, this means that a PCH compiled without
657 // optimization can't be used with optimization turned on, even
658 // though the only thing that changes is whether __OPTIMIZE__ was
659 // defined... but if __OPTIMIZE__ never showed up in the header, it
660 // doesn't matter. We could consider making this some special kind
661 // of check.
662 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
663 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
664 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
665 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
666 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
667 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
668 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
669 Diag(diag::warn_pch_gc_mode)
670 << (unsigned)Record[Idx] << LangOpts.getGCMode();
671 Diag(diag::note_ignoring_pch) << FileName;
672 return true;
673 }
674 ++Idx;
675 PARSE_LANGOPT_BENIGN(getVisibilityMode());
676 PARSE_LANGOPT_BENIGN(InstantiationDepth);
677#undef PARSE_LANGOPT_IRRELEVANT
678#undef PARSE_LANGOPT_BENIGN
679
680 return false;
681}
682
Douglas Gregorc34897d2009-04-09 22:27:44 +0000683/// \brief Read and return the type at the given offset.
684///
685/// This routine actually reads the record corresponding to the type
686/// at the given offset in the bitstream. It is a helper routine for
687/// GetType, which deals with reading type IDs.
688QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
689 Stream.JumpToBit(Offset);
690 RecordData Record;
691 unsigned Code = Stream.ReadCode();
692 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
693 case pch::TYPE_FIXED_WIDTH_INT: {
694 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
695 return Context.getFixedWidthIntType(Record[0], Record[1]);
696 }
697
698 case pch::TYPE_COMPLEX: {
699 assert(Record.size() == 1 && "Incorrect encoding of complex type");
700 QualType ElemType = GetType(Record[0]);
701 return Context.getComplexType(ElemType);
702 }
703
704 case pch::TYPE_POINTER: {
705 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
706 QualType PointeeType = GetType(Record[0]);
707 return Context.getPointerType(PointeeType);
708 }
709
710 case pch::TYPE_BLOCK_POINTER: {
711 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
712 QualType PointeeType = GetType(Record[0]);
713 return Context.getBlockPointerType(PointeeType);
714 }
715
716 case pch::TYPE_LVALUE_REFERENCE: {
717 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
718 QualType PointeeType = GetType(Record[0]);
719 return Context.getLValueReferenceType(PointeeType);
720 }
721
722 case pch::TYPE_RVALUE_REFERENCE: {
723 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
724 QualType PointeeType = GetType(Record[0]);
725 return Context.getRValueReferenceType(PointeeType);
726 }
727
728 case pch::TYPE_MEMBER_POINTER: {
729 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
730 QualType PointeeType = GetType(Record[0]);
731 QualType ClassType = GetType(Record[1]);
732 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
733 }
734
735 // FIXME: Several other kinds of types to deserialize here!
736 default:
Douglas Gregorac8f2802009-04-10 17:25:41 +0000737 assert(false && "Unable to deserialize this type");
Douglas Gregorc34897d2009-04-09 22:27:44 +0000738 break;
739 }
740
741 // Suppress a GCC warning
742 return QualType();
743}
744
745/// \brief Note that we have loaded the declaration with the given
746/// Index.
747///
748/// This routine notes that this declaration has already been loaded,
749/// so that future GetDecl calls will return this declaration rather
750/// than trying to load a new declaration.
751inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
752 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
753 DeclAlreadyLoaded[Index] = true;
754 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
755}
756
757/// \brief Read the declaration at the given offset from the PCH file.
758Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
759 Decl *D = 0;
760 Stream.JumpToBit(Offset);
761 RecordData Record;
762 unsigned Code = Stream.ReadCode();
763 unsigned Idx = 0;
764 PCHDeclReader Reader(*this, Record, Idx);
765 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
766 case pch::DECL_TRANSLATION_UNIT:
767 assert(Index == 0 && "Translation unit must be at index 0");
768 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
769 D = Context.getTranslationUnitDecl();
770 LoadedDecl(Index, D);
771 break;
772
773 case pch::DECL_TYPEDEF: {
774 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
775 0, QualType());
776 LoadedDecl(Index, Typedef);
777 Reader.VisitTypedefDecl(Typedef);
778 D = Typedef;
779 break;
780 }
781
782 case pch::DECL_VAR: {
783 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
784 VarDecl::None, SourceLocation());
785 LoadedDecl(Index, Var);
786 Reader.VisitVarDecl(Var);
787 D = Var;
788 break;
789 }
790
791 default:
792 assert(false && "Cannot de-serialize this kind of declaration");
793 break;
794 }
795
796 // If this declaration is also a declaration context, get the
797 // offsets for its tables of lexical and visible declarations.
798 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
799 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
800 if (Offsets.first || Offsets.second) {
801 DC->setHasExternalLexicalStorage(Offsets.first != 0);
802 DC->setHasExternalVisibleStorage(Offsets.second != 0);
803 DeclContextOffsets[DC] = Offsets;
804 }
805 }
806 assert(Idx == Record.size());
807
808 return D;
809}
810
Douglas Gregorac8f2802009-04-10 17:25:41 +0000811QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000812 unsigned Quals = ID & 0x07;
813 unsigned Index = ID >> 3;
814
815 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
816 QualType T;
817 switch ((pch::PredefinedTypeIDs)Index) {
818 case pch::PREDEF_TYPE_NULL_ID: return QualType();
819 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
820 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
821
822 case pch::PREDEF_TYPE_CHAR_U_ID:
823 case pch::PREDEF_TYPE_CHAR_S_ID:
824 // FIXME: Check that the signedness of CharTy is correct!
825 T = Context.CharTy;
826 break;
827
828 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
829 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
830 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
831 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
832 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
833 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
834 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
835 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
836 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
837 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
838 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
839 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
840 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
841 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
842 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
843 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
844 }
845
846 assert(!T.isNull() && "Unknown predefined type");
847 return T.getQualifiedType(Quals);
848 }
849
850 Index -= pch::NUM_PREDEF_TYPE_IDS;
851 if (!TypeAlreadyLoaded[Index]) {
852 // Load the type from the PCH file.
853 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
854 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
855 TypeAlreadyLoaded[Index] = true;
856 }
857
858 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
859}
860
Douglas Gregorac8f2802009-04-10 17:25:41 +0000861Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000862 if (ID == 0)
863 return 0;
864
865 unsigned Index = ID - 1;
866 if (DeclAlreadyLoaded[Index])
867 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
868
869 // Load the declaration from the PCH file.
870 return ReadDeclRecord(DeclOffsets[Index], Index);
871}
872
873bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +0000874 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000875 assert(DC->hasExternalLexicalStorage() &&
876 "DeclContext has no lexical decls in storage");
877 uint64_t Offset = DeclContextOffsets[DC].first;
878 assert(Offset && "DeclContext has no lexical decls in storage");
879
880 // Load the record containing all of the declarations lexically in
881 // this context.
882 Stream.JumpToBit(Offset);
883 RecordData Record;
884 unsigned Code = Stream.ReadCode();
885 unsigned RecCode = Stream.ReadRecord(Code, Record);
886 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
887
888 // Load all of the declaration IDs
889 Decls.clear();
890 Decls.insert(Decls.end(), Record.begin(), Record.end());
891 return false;
892}
893
894bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
895 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
896 assert(DC->hasExternalVisibleStorage() &&
897 "DeclContext has no visible decls in storage");
898 uint64_t Offset = DeclContextOffsets[DC].second;
899 assert(Offset && "DeclContext has no visible decls in storage");
900
901 // Load the record containing all of the declarations visible in
902 // this context.
903 Stream.JumpToBit(Offset);
904 RecordData Record;
905 unsigned Code = Stream.ReadCode();
906 unsigned RecCode = Stream.ReadRecord(Code, Record);
907 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
908 if (Record.size() == 0)
909 return false;
910
911 Decls.clear();
912
913 unsigned Idx = 0;
914 // llvm::SmallVector<uintptr_t, 16> DeclIDs;
915 while (Idx < Record.size()) {
916 Decls.push_back(VisibleDeclaration());
917 Decls.back().Name = ReadDeclarationName(Record, Idx);
918
919 // FIXME: Don't actually read anything here!
920 unsigned Size = Record[Idx++];
921 llvm::SmallVector<unsigned, 4> & LoadedDecls
922 = Decls.back().Declarations;
923 LoadedDecls.reserve(Size);
924 for (unsigned I = 0; I < Size; ++I)
925 LoadedDecls.push_back(Record[Idx++]);
926 }
927
928 return false;
929}
930
931void PCHReader::PrintStats() {
932 std::fprintf(stderr, "*** PCH Statistics:\n");
933
934 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
935 TypeAlreadyLoaded.end(),
936 true);
937 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
938 DeclAlreadyLoaded.end(),
939 true);
940 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
941 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
942 ((float)NumTypesLoaded/(float)TypeAlreadyLoaded.size() * 100));
943 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
944 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
945 ((float)NumDeclsLoaded/(float)DeclAlreadyLoaded.size() * 100));
946 std::fprintf(stderr, "\n");
947}
948
949const IdentifierInfo *PCHReader::GetIdentifierInfo(const RecordData &Record,
950 unsigned &Idx) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000951 pch::IdentID ID = Record[Idx++];
952 if (ID == 0)
953 return 0;
954
955 if (!IdentifierTable || IdentifierData.empty()) {
956 Error("No identifier table in PCH file");
957 return 0;
958 }
959
960 if (IdentifierData[ID - 1] & 0x01) {
961 uint64_t Offset = IdentifierData[ID - 1];
962 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
963 &Context.Idents.get(IdentifierTable + Offset));
964 }
965
966 return reinterpret_cast<const IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000967}
968
969DeclarationName
970PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
971 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
972 switch (Kind) {
973 case DeclarationName::Identifier:
974 return DeclarationName(GetIdentifierInfo(Record, Idx));
975
976 case DeclarationName::ObjCZeroArgSelector:
977 case DeclarationName::ObjCOneArgSelector:
978 case DeclarationName::ObjCMultiArgSelector:
979 assert(false && "Unable to de-serialize Objective-C selectors");
980 break;
981
982 case DeclarationName::CXXConstructorName:
983 return Context.DeclarationNames.getCXXConstructorName(
984 GetType(Record[Idx++]));
985
986 case DeclarationName::CXXDestructorName:
987 return Context.DeclarationNames.getCXXDestructorName(
988 GetType(Record[Idx++]));
989
990 case DeclarationName::CXXConversionFunctionName:
991 return Context.DeclarationNames.getCXXConversionFunctionName(
992 GetType(Record[Idx++]));
993
994 case DeclarationName::CXXOperatorName:
995 return Context.DeclarationNames.getCXXOperatorName(
996 (OverloadedOperatorKind)Record[Idx++]);
997
998 case DeclarationName::CXXUsingDirective:
999 return DeclarationName::getUsingDirectiveName();
1000 }
1001
1002 // Required to silence GCC warning
1003 return DeclarationName();
1004}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001005
1006DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001007 return Diag(SourceLocation(), DiagID);
1008}
1009
1010DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1011 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001012 Context.getSourceManager()),
1013 DiagID);
1014}