blob: 057e66a6f7d4a8a78679c0028ccebb9ce6a7d807 [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 Gregor631f6c62009-04-14 00:24:19 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Douglas Gregor631f6c62009-04-14 00:24:19 +000018#include "clang/AST/DeclGroup.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/StmtVisitor.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000025#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000026#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000028#include "llvm/Bitcode/BitstreamReader.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include <algorithm>
32#include <cstdio>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Declaration deserialization
38//===----------------------------------------------------------------------===//
39namespace {
40 class VISIBILITY_HIDDEN PCHDeclReader {
41 PCHReader &Reader;
42 const PCHReader::RecordData &Record;
43 unsigned &Idx;
44
45 public:
46 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
47 unsigned &Idx)
48 : Reader(Reader), Record(Record), Idx(Idx) { }
49
50 void VisitDecl(Decl *D);
51 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
52 void VisitNamedDecl(NamedDecl *ND);
53 void VisitTypeDecl(TypeDecl *TD);
54 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000055 void VisitTagDecl(TagDecl *TD);
56 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000057 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000058 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000059 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000060 void VisitFunctionDecl(FunctionDecl *FD);
Douglas Gregor982365e2009-04-13 21:20:57 +000061 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000062 void VisitVarDecl(VarDecl *VD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000063 void VisitParmVarDecl(ParmVarDecl *PD);
64 void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD);
Douglas Gregor2a491792009-04-13 22:49:25 +000065 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
66 void VisitBlockDecl(BlockDecl *BD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000067 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
68 };
69}
70
71void PCHDeclReader::VisitDecl(Decl *D) {
72 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
73 D->setLexicalDeclContext(
74 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
75 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
76 D->setInvalidDecl(Record[Idx++]);
77 // FIXME: hasAttrs
78 D->setImplicit(Record[Idx++]);
79 D->setAccess((AccessSpecifier)Record[Idx++]);
80}
81
82void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
83 VisitDecl(TU);
84}
85
86void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
87 VisitDecl(ND);
88 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
89}
90
91void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
92 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000093 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
94}
95
96void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000097 // Note that we cannot use VisitTypeDecl here, because we need to
98 // set the underlying type of the typedef *before* we try to read
99 // the type associated with the TypedefDecl.
100 VisitNamedDecl(TD);
101 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
102 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
103 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000104}
105
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000106void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
107 VisitTypeDecl(TD);
108 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
109 TD->setDefinition(Record[Idx++]);
110 TD->setTypedefForAnonDecl(
111 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
112}
113
114void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
115 VisitTagDecl(ED);
116 ED->setIntegerType(Reader.GetType(Record[Idx++]));
117}
118
Douglas Gregor982365e2009-04-13 21:20:57 +0000119void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
120 VisitTagDecl(RD);
121 RD->setHasFlexibleArrayMember(Record[Idx++]);
122 RD->setAnonymousStructOrUnion(Record[Idx++]);
123}
124
Douglas Gregorc34897d2009-04-09 22:27:44 +0000125void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
126 VisitNamedDecl(VD);
127 VD->setType(Reader.GetType(Record[Idx++]));
128}
129
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000130void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
131 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000132 if (Record[Idx++])
133 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000134 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
135}
136
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000137void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
138 VisitValueDecl(FD);
139 // FIXME: function body
140 FD->setPreviousDeclaration(
141 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
142 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
143 FD->setInline(Record[Idx++]);
144 FD->setVirtual(Record[Idx++]);
145 FD->setPure(Record[Idx++]);
146 FD->setInheritedPrototype(Record[Idx++]);
147 FD->setHasPrototype(Record[Idx++]);
148 FD->setDeleted(Record[Idx++]);
149 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
150 unsigned NumParams = Record[Idx++];
151 llvm::SmallVector<ParmVarDecl *, 16> Params;
152 Params.reserve(NumParams);
153 for (unsigned I = 0; I != NumParams; ++I)
154 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
155 FD->setParams(Reader.getContext(), &Params[0], NumParams);
156}
157
Douglas Gregor982365e2009-04-13 21:20:57 +0000158void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
159 VisitValueDecl(FD);
160 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000161 if (Record[Idx++])
162 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000163}
164
Douglas Gregorc34897d2009-04-09 22:27:44 +0000165void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
166 VisitValueDecl(VD);
167 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
168 VD->setThreadSpecified(Record[Idx++]);
169 VD->setCXXDirectInitializer(Record[Idx++]);
170 VD->setDeclaredInCondition(Record[Idx++]);
171 VD->setPreviousDeclaration(
172 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
173 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000174 if (Record[Idx++])
175 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000176}
177
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000178void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
179 VisitVarDecl(PD);
180 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
181 // FIXME: default argument
182}
183
184void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
185 VisitParmVarDecl(PD);
186 PD->setOriginalType(Reader.GetType(Record[Idx++]));
187}
188
Douglas Gregor2a491792009-04-13 22:49:25 +0000189void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
190 VisitDecl(AD);
191 // FIXME: read asm string
192}
193
194void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
195 VisitDecl(BD);
196 unsigned NumParams = Record[Idx++];
197 llvm::SmallVector<ParmVarDecl *, 16> Params;
198 Params.reserve(NumParams);
199 for (unsigned I = 0; I != NumParams; ++I)
200 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
201 BD->setParams(Reader.getContext(), &Params[0], NumParams);
202}
203
Douglas Gregorc34897d2009-04-09 22:27:44 +0000204std::pair<uint64_t, uint64_t>
205PCHDeclReader::VisitDeclContext(DeclContext *DC) {
206 uint64_t LexicalOffset = Record[Idx++];
207 uint64_t VisibleOffset = 0;
208 if (DC->getPrimaryContext() == DC)
209 VisibleOffset = Record[Idx++];
210 return std::make_pair(LexicalOffset, VisibleOffset);
211}
212
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000213//===----------------------------------------------------------------------===//
214// Statement/expression deserialization
215//===----------------------------------------------------------------------===//
216namespace {
217 class VISIBILITY_HIDDEN PCHStmtReader
Douglas Gregora151ba42009-04-14 23:32:43 +0000218 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000219 PCHReader &Reader;
220 const PCHReader::RecordData &Record;
221 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000222 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000223
224 public:
225 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000226 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
227 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000228
Douglas Gregora151ba42009-04-14 23:32:43 +0000229 // Each of the Visit* functions reads in part of the expression
230 // from the given record and the current expression stack, then
231 // return the total number of operands that it read from the
232 // expression stack.
233
234 unsigned VisitExpr(Expr *E);
235 unsigned VisitPredefinedExpr(PredefinedExpr *E);
236 unsigned VisitDeclRefExpr(DeclRefExpr *E);
237 unsigned VisitIntegerLiteral(IntegerLiteral *E);
238 unsigned VisitFloatingLiteral(FloatingLiteral *E);
239 unsigned VisitCharacterLiteral(CharacterLiteral *E);
240 unsigned VisitCastExpr(CastExpr *E);
241 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000242 };
243}
244
Douglas Gregora151ba42009-04-14 23:32:43 +0000245unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000246 E->setType(Reader.GetType(Record[Idx++]));
247 E->setTypeDependent(Record[Idx++]);
248 E->setValueDependent(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000249 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000250}
251
Douglas Gregora151ba42009-04-14 23:32:43 +0000252unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000253 VisitExpr(E);
254 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
255 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000256 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000257}
258
Douglas Gregora151ba42009-04-14 23:32:43 +0000259unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000260 VisitExpr(E);
261 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
262 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000263 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000264}
265
Douglas Gregora151ba42009-04-14 23:32:43 +0000266unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000267 VisitExpr(E);
268 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
269 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000270 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000271}
272
Douglas Gregora151ba42009-04-14 23:32:43 +0000273unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000274 VisitExpr(E);
275 E->setValue(Reader.ReadAPFloat(Record, Idx));
276 E->setExact(Record[Idx++]);
277 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000278 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000279}
280
Douglas Gregora151ba42009-04-14 23:32:43 +0000281unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000282 VisitExpr(E);
283 E->setValue(Record[Idx++]);
284 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
285 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000286 return 0;
287}
288
289unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
290 VisitExpr(E);
291 E->setSubExpr(ExprStack.back());
292 return 1;
293}
294
295unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
296 VisitCastExpr(E);
297 E->setLvalueCast(Record[Idx++]);
298 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000299}
300
Douglas Gregorc34897d2009-04-09 22:27:44 +0000301// FIXME: use the diagnostics machinery
302static bool Error(const char *Str) {
303 std::fprintf(stderr, "%s\n", Str);
304 return true;
305}
306
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000307/// \brief Check the contents of the predefines buffer against the
308/// contents of the predefines buffer used to build the PCH file.
309///
310/// The contents of the two predefines buffers should be the same. If
311/// not, then some command-line option changed the preprocessor state
312/// and we must reject the PCH file.
313///
314/// \param PCHPredef The start of the predefines buffer in the PCH
315/// file.
316///
317/// \param PCHPredefLen The length of the predefines buffer in the PCH
318/// file.
319///
320/// \param PCHBufferID The FileID for the PCH predefines buffer.
321///
322/// \returns true if there was a mismatch (in which case the PCH file
323/// should be ignored), or false otherwise.
324bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
325 unsigned PCHPredefLen,
326 FileID PCHBufferID) {
327 const char *Predef = PP.getPredefines().c_str();
328 unsigned PredefLen = PP.getPredefines().size();
329
330 // If the two predefines buffers compare equal, we're done!.
331 if (PredefLen == PCHPredefLen &&
332 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
333 return false;
334
335 // The predefines buffers are different. Produce a reasonable
336 // diagnostic showing where they are different.
337
338 // The source locations (potentially in the two different predefines
339 // buffers)
340 SourceLocation Loc1, Loc2;
341 SourceManager &SourceMgr = PP.getSourceManager();
342
343 // Create a source buffer for our predefines string, so
344 // that we can build a diagnostic that points into that
345 // source buffer.
346 FileID BufferID;
347 if (Predef && Predef[0]) {
348 llvm::MemoryBuffer *Buffer
349 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
350 "<built-in>");
351 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
352 }
353
354 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
355 std::pair<const char *, const char *> Locations
356 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
357
358 if (Locations.first != Predef + MinLen) {
359 // We found the location in the two buffers where there is a
360 // difference. Form source locations to point there (in both
361 // buffers).
362 unsigned Offset = Locations.first - Predef;
363 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
364 .getFileLocWithOffset(Offset);
365 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
366 .getFileLocWithOffset(Offset);
367 } else if (PredefLen > PCHPredefLen) {
368 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
369 .getFileLocWithOffset(MinLen);
370 } else {
371 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
372 .getFileLocWithOffset(MinLen);
373 }
374
375 Diag(Loc1, diag::warn_pch_preprocessor);
376 if (Loc2.isValid())
377 Diag(Loc2, diag::note_predef_in_pch);
378 Diag(diag::note_ignoring_pch) << FileName;
379 return true;
380}
381
Douglas Gregor635f97f2009-04-13 16:31:14 +0000382/// \brief Read the line table in the source manager block.
383/// \returns true if ther was an error.
384static bool ParseLineTable(SourceManager &SourceMgr,
385 llvm::SmallVectorImpl<uint64_t> &Record) {
386 unsigned Idx = 0;
387 LineTableInfo &LineTable = SourceMgr.getLineTable();
388
389 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000390 std::map<int, int> FileIDs;
391 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000392 // Extract the file name
393 unsigned FilenameLen = Record[Idx++];
394 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
395 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000396 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
397 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000398 }
399
400 // Parse the line entries
401 std::vector<LineEntry> Entries;
402 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000403 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000404
405 // Extract the line entries
406 unsigned NumEntries = Record[Idx++];
407 Entries.clear();
408 Entries.reserve(NumEntries);
409 for (unsigned I = 0; I != NumEntries; ++I) {
410 unsigned FileOffset = Record[Idx++];
411 unsigned LineNo = Record[Idx++];
412 int FilenameID = Record[Idx++];
413 SrcMgr::CharacteristicKind FileKind
414 = (SrcMgr::CharacteristicKind)Record[Idx++];
415 unsigned IncludeOffset = Record[Idx++];
416 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
417 FileKind, IncludeOffset));
418 }
419 LineTable.AddEntry(FID, Entries);
420 }
421
422 return false;
423}
424
Douglas Gregorab1cef72009-04-10 03:52:48 +0000425/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000426PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000427 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000428 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
429 Error("Malformed source manager block record");
430 return Failure;
431 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000432
433 SourceManager &SourceMgr = Context.getSourceManager();
434 RecordData Record;
435 while (true) {
436 unsigned Code = Stream.ReadCode();
437 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000438 if (Stream.ReadBlockEnd()) {
439 Error("Error at end of Source Manager block");
440 return Failure;
441 }
442
443 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000444 }
445
446 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
447 // No known subblocks, always skip them.
448 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000449 if (Stream.SkipBlock()) {
450 Error("Malformed block record");
451 return Failure;
452 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000453 continue;
454 }
455
456 if (Code == llvm::bitc::DEFINE_ABBREV) {
457 Stream.ReadAbbrevRecord();
458 continue;
459 }
460
461 // Read a record.
462 const char *BlobStart;
463 unsigned BlobLen;
464 Record.clear();
465 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
466 default: // Default behavior: ignore.
467 break;
468
469 case pch::SM_SLOC_FILE_ENTRY: {
470 // FIXME: We would really like to delay the creation of this
471 // FileEntry until it is actually required, e.g., when producing
472 // a diagnostic with a source location in this file.
473 const FileEntry *File
474 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
475 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000476 FileID ID = SourceMgr.createFileID(File,
477 SourceLocation::getFromRawEncoding(Record[1]),
478 (CharacteristicKind)Record[2]);
479 if (Record[3])
480 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
481 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000482 break;
483 }
484
485 case pch::SM_SLOC_BUFFER_ENTRY: {
486 const char *Name = BlobStart;
487 unsigned Code = Stream.ReadCode();
488 Record.clear();
489 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
490 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000491 llvm::MemoryBuffer *Buffer
492 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
493 BlobStart + BlobLen - 1,
494 Name);
495 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
496
497 if (strcmp(Name, "<built-in>") == 0
498 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
499 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000500 break;
501 }
502
503 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
504 SourceLocation SpellingLoc
505 = SourceLocation::getFromRawEncoding(Record[1]);
506 SourceMgr.createInstantiationLoc(
507 SpellingLoc,
508 SourceLocation::getFromRawEncoding(Record[2]),
509 SourceLocation::getFromRawEncoding(Record[3]),
510 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000511 SourceMgr,
512 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000513 break;
514 }
515
Chris Lattnere1be6022009-04-14 23:22:57 +0000516 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000517 if (ParseLineTable(SourceMgr, Record))
518 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000519 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000520 }
521 }
522}
523
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000524bool PCHReader::ReadPreprocessorBlock() {
525 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
526 return Error("Malformed preprocessor block record");
527
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000528 RecordData Record;
529 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
530 MacroInfo *LastMacro = 0;
531
532 while (true) {
533 unsigned Code = Stream.ReadCode();
534 switch (Code) {
535 case llvm::bitc::END_BLOCK:
536 if (Stream.ReadBlockEnd())
537 return Error("Error at end of preprocessor block");
538 return false;
539
540 case llvm::bitc::ENTER_SUBBLOCK:
541 // No known subblocks, always skip them.
542 Stream.ReadSubBlockID();
543 if (Stream.SkipBlock())
544 return Error("Malformed block record");
545 continue;
546
547 case llvm::bitc::DEFINE_ABBREV:
548 Stream.ReadAbbrevRecord();
549 continue;
550 default: break;
551 }
552
553 // Read a record.
554 Record.clear();
555 pch::PreprocessorRecordTypes RecType =
556 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
557 switch (RecType) {
558 default: // Default behavior: ignore unknown records.
559 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000560 case pch::PP_COUNTER_VALUE:
561 if (!Record.empty())
562 PP.setCounterValue(Record[0]);
563 break;
564
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000565 case pch::PP_MACRO_OBJECT_LIKE:
566 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000567 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
568 if (II == 0)
569 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000570 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
571 bool isUsed = Record[2];
572
573 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
574 MI->setIsUsed(isUsed);
575
576 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
577 // Decode function-like macro info.
578 bool isC99VarArgs = Record[3];
579 bool isGNUVarArgs = Record[4];
580 MacroArgs.clear();
581 unsigned NumArgs = Record[5];
582 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000583 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000584
585 // Install function-like macro info.
586 MI->setIsFunctionLike();
587 if (isC99VarArgs) MI->setIsC99Varargs();
588 if (isGNUVarArgs) MI->setIsGNUVarargs();
589 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
590 PP.getPreprocessorAllocator());
591 }
592
593 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000594 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000595
596 // Remember that we saw this macro last so that we add the tokens that
597 // form its body to it.
598 LastMacro = MI;
599 break;
600 }
601
602 case pch::PP_TOKEN: {
603 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
604 // pretend we didn't see this.
605 if (LastMacro == 0) break;
606
607 Token Tok;
608 Tok.startToken();
609 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
610 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000611 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
612 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000613 Tok.setKind((tok::TokenKind)Record[3]);
614 Tok.setFlag((Token::TokenFlags)Record[4]);
615 LastMacro->AddTokenToBody(Tok);
616 break;
617 }
618 }
619 }
620}
621
Douglas Gregor179cfb12009-04-10 20:39:37 +0000622PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
623 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
624 Error("Malformed block record");
625 return Failure;
626 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000627
Chris Lattner29241862009-04-11 21:15:38 +0000628 uint64_t PreprocessorBlockBit = 0;
629
Douglas Gregorc34897d2009-04-09 22:27:44 +0000630 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000631 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000632 while (!Stream.AtEndOfStream()) {
633 unsigned Code = Stream.ReadCode();
634 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000635 // If we saw the preprocessor block, read it now.
636 if (PreprocessorBlockBit) {
637 uint64_t SavedPos = Stream.GetCurrentBitNo();
638 Stream.JumpToBit(PreprocessorBlockBit);
639 if (ReadPreprocessorBlock()) {
640 Error("Malformed preprocessor block");
641 return Failure;
642 }
643 Stream.JumpToBit(SavedPos);
644 }
645
Douglas Gregor179cfb12009-04-10 20:39:37 +0000646 if (Stream.ReadBlockEnd()) {
647 Error("Error at end of module block");
648 return Failure;
649 }
Chris Lattner29241862009-04-11 21:15:38 +0000650
Douglas Gregor179cfb12009-04-10 20:39:37 +0000651 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000652 }
653
654 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
655 switch (Stream.ReadSubBlockID()) {
656 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
657 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
658 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000659 if (Stream.SkipBlock()) {
660 Error("Malformed block record");
661 return Failure;
662 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000663 break;
664
Chris Lattner29241862009-04-11 21:15:38 +0000665 case pch::PREPROCESSOR_BLOCK_ID:
666 // Skip the preprocessor block for now, but remember where it is. We
667 // want to read it in after the identifier table.
668 if (PreprocessorBlockBit) {
669 Error("Multiple preprocessor blocks found.");
670 return Failure;
671 }
672 PreprocessorBlockBit = Stream.GetCurrentBitNo();
673 if (Stream.SkipBlock()) {
674 Error("Malformed block record");
675 return Failure;
676 }
677 break;
678
Douglas Gregorab1cef72009-04-10 03:52:48 +0000679 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000680 switch (ReadSourceManagerBlock()) {
681 case Success:
682 break;
683
684 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000685 Error("Malformed source manager block");
686 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000687
688 case IgnorePCH:
689 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000690 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000691 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000692 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000693 continue;
694 }
695
696 if (Code == llvm::bitc::DEFINE_ABBREV) {
697 Stream.ReadAbbrevRecord();
698 continue;
699 }
700
701 // Read and process a record.
702 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000703 const char *BlobStart = 0;
704 unsigned BlobLen = 0;
705 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
706 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000707 default: // Default behavior: ignore.
708 break;
709
710 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000711 if (!TypeOffsets.empty()) {
712 Error("Duplicate TYPE_OFFSET record in PCH file");
713 return Failure;
714 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000715 TypeOffsets.swap(Record);
716 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
717 break;
718
719 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000720 if (!DeclOffsets.empty()) {
721 Error("Duplicate DECL_OFFSET record in PCH file");
722 return Failure;
723 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000724 DeclOffsets.swap(Record);
725 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
726 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000727
728 case pch::LANGUAGE_OPTIONS:
729 if (ParseLanguageOptions(Record))
730 return IgnorePCH;
731 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000732
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000733 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000734 std::string TargetTriple(BlobStart, BlobLen);
735 if (TargetTriple != Context.Target.getTargetTriple()) {
736 Diag(diag::warn_pch_target_triple)
737 << TargetTriple << Context.Target.getTargetTriple();
738 Diag(diag::note_ignoring_pch) << FileName;
739 return IgnorePCH;
740 }
741 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000742 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000743
744 case pch::IDENTIFIER_TABLE:
745 IdentifierTable = BlobStart;
746 break;
747
748 case pch::IDENTIFIER_OFFSET:
749 if (!IdentifierData.empty()) {
750 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
751 return Failure;
752 }
753 IdentifierData.swap(Record);
754#ifndef NDEBUG
755 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
756 if ((IdentifierData[I] & 0x01) == 0) {
757 Error("Malformed identifier table in the precompiled header");
758 return Failure;
759 }
760 }
761#endif
762 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000763
764 case pch::EXTERNAL_DEFINITIONS:
765 if (!ExternalDefinitions.empty()) {
766 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
767 return Failure;
768 }
769 ExternalDefinitions.swap(Record);
770 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000771 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000772 }
773
Douglas Gregor179cfb12009-04-10 20:39:37 +0000774 Error("Premature end of bitstream");
775 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000776}
777
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000778PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000779 // Set the PCH file name.
780 this->FileName = FileName;
781
Douglas Gregorc34897d2009-04-09 22:27:44 +0000782 // Open the PCH file.
783 std::string ErrStr;
784 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000785 if (!Buffer) {
786 Error(ErrStr.c_str());
787 return IgnorePCH;
788 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000789
790 // Initialize the stream
791 Stream.init((const unsigned char *)Buffer->getBufferStart(),
792 (const unsigned char *)Buffer->getBufferEnd());
793
794 // Sniff for the signature.
795 if (Stream.Read(8) != 'C' ||
796 Stream.Read(8) != 'P' ||
797 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000798 Stream.Read(8) != 'H') {
799 Error("Not a PCH file");
800 return IgnorePCH;
801 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000802
803 // We expect a number of well-defined blocks, though we don't necessarily
804 // need to understand them all.
805 while (!Stream.AtEndOfStream()) {
806 unsigned Code = Stream.ReadCode();
807
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000808 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
809 Error("Invalid record at top-level");
810 return Failure;
811 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000812
813 unsigned BlockID = Stream.ReadSubBlockID();
814
815 // We only know the PCH subblock ID.
816 switch (BlockID) {
817 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000818 if (Stream.ReadBlockInfoBlock()) {
819 Error("Malformed BlockInfoBlock");
820 return Failure;
821 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000822 break;
823 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000824 switch (ReadPCHBlock()) {
825 case Success:
826 break;
827
828 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000829 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000830
831 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000832 // FIXME: We could consider reading through to the end of this
833 // PCH block, skipping subblocks, to see if there are other
834 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000835 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000836 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000837 break;
838 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000839 if (Stream.SkipBlock()) {
840 Error("Malformed block record");
841 return Failure;
842 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000843 break;
844 }
845 }
846
847 // Load the translation unit declaration
848 ReadDeclRecord(DeclOffsets[0], 0);
849
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000850 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000851}
852
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000853namespace {
854 /// \brief Helper class that saves the current stream position and
855 /// then restores it when destroyed.
856 struct VISIBILITY_HIDDEN SavedStreamPosition {
857 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
858 : Stream(Stream), Offset(Stream.GetCurrentBitNo()),
859 EndOfStream(Stream.AtEndOfStream()){ }
860
861 ~SavedStreamPosition() {
862 if (!EndOfStream)
863 Stream.JumpToBit(Offset);
864 }
865
866 private:
867 llvm::BitstreamReader &Stream;
868 uint64_t Offset;
869 bool EndOfStream;
870 };
871}
872
Douglas Gregor179cfb12009-04-10 20:39:37 +0000873/// \brief Parse the record that corresponds to a LangOptions data
874/// structure.
875///
876/// This routine compares the language options used to generate the
877/// PCH file against the language options set for the current
878/// compilation. For each option, we classify differences between the
879/// two compiler states as either "benign" or "important". Benign
880/// differences don't matter, and we accept them without complaint
881/// (and without modifying the language options). Differences between
882/// the states for important options cause the PCH file to be
883/// unusable, so we emit a warning and return true to indicate that
884/// there was an error.
885///
886/// \returns true if the PCH file is unacceptable, false otherwise.
887bool PCHReader::ParseLanguageOptions(
888 const llvm::SmallVectorImpl<uint64_t> &Record) {
889 const LangOptions &LangOpts = Context.getLangOptions();
890#define PARSE_LANGOPT_BENIGN(Option) ++Idx
891#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
892 if (Record[Idx] != LangOpts.Option) { \
893 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
894 Diag(diag::note_ignoring_pch) << FileName; \
895 return true; \
896 } \
897 ++Idx
898
899 unsigned Idx = 0;
900 PARSE_LANGOPT_BENIGN(Trigraphs);
901 PARSE_LANGOPT_BENIGN(BCPLComment);
902 PARSE_LANGOPT_BENIGN(DollarIdents);
903 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
904 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
905 PARSE_LANGOPT_BENIGN(ImplicitInt);
906 PARSE_LANGOPT_BENIGN(Digraphs);
907 PARSE_LANGOPT_BENIGN(HexFloats);
908 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
909 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
910 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
911 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
912 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
913 PARSE_LANGOPT_BENIGN(CXXOperatorName);
914 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
915 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
916 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
917 PARSE_LANGOPT_BENIGN(PascalStrings);
918 PARSE_LANGOPT_BENIGN(Boolean);
919 PARSE_LANGOPT_BENIGN(WritableStrings);
920 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
921 diag::warn_pch_lax_vector_conversions);
922 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
923 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
924 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
925 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
926 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
927 diag::warn_pch_thread_safe_statics);
928 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
929 PARSE_LANGOPT_BENIGN(EmitAllDecls);
930 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
931 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
932 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
933 diag::warn_pch_heinous_extensions);
934 // FIXME: Most of the options below are benign if the macro wasn't
935 // used. Unfortunately, this means that a PCH compiled without
936 // optimization can't be used with optimization turned on, even
937 // though the only thing that changes is whether __OPTIMIZE__ was
938 // defined... but if __OPTIMIZE__ never showed up in the header, it
939 // doesn't matter. We could consider making this some special kind
940 // of check.
941 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
942 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
943 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
944 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
945 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
946 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
947 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
948 Diag(diag::warn_pch_gc_mode)
949 << (unsigned)Record[Idx] << LangOpts.getGCMode();
950 Diag(diag::note_ignoring_pch) << FileName;
951 return true;
952 }
953 ++Idx;
954 PARSE_LANGOPT_BENIGN(getVisibilityMode());
955 PARSE_LANGOPT_BENIGN(InstantiationDepth);
956#undef PARSE_LANGOPT_IRRELEVANT
957#undef PARSE_LANGOPT_BENIGN
958
959 return false;
960}
961
Douglas Gregorc34897d2009-04-09 22:27:44 +0000962/// \brief Read and return the type at the given offset.
963///
964/// This routine actually reads the record corresponding to the type
965/// at the given offset in the bitstream. It is a helper routine for
966/// GetType, which deals with reading type IDs.
967QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000968 // Keep track of where we are in the stream, then jump back there
969 // after reading this type.
970 SavedStreamPosition SavedPosition(Stream);
971
Douglas Gregorc34897d2009-04-09 22:27:44 +0000972 Stream.JumpToBit(Offset);
973 RecordData Record;
974 unsigned Code = Stream.ReadCode();
975 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000976 case pch::TYPE_EXT_QUAL:
977 // FIXME: Deserialize ExtQualType
978 assert(false && "Cannot deserialize qualified types yet");
979 return QualType();
980
Douglas Gregorc34897d2009-04-09 22:27:44 +0000981 case pch::TYPE_FIXED_WIDTH_INT: {
982 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
983 return Context.getFixedWidthIntType(Record[0], Record[1]);
984 }
985
986 case pch::TYPE_COMPLEX: {
987 assert(Record.size() == 1 && "Incorrect encoding of complex type");
988 QualType ElemType = GetType(Record[0]);
989 return Context.getComplexType(ElemType);
990 }
991
992 case pch::TYPE_POINTER: {
993 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
994 QualType PointeeType = GetType(Record[0]);
995 return Context.getPointerType(PointeeType);
996 }
997
998 case pch::TYPE_BLOCK_POINTER: {
999 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1000 QualType PointeeType = GetType(Record[0]);
1001 return Context.getBlockPointerType(PointeeType);
1002 }
1003
1004 case pch::TYPE_LVALUE_REFERENCE: {
1005 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1006 QualType PointeeType = GetType(Record[0]);
1007 return Context.getLValueReferenceType(PointeeType);
1008 }
1009
1010 case pch::TYPE_RVALUE_REFERENCE: {
1011 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1012 QualType PointeeType = GetType(Record[0]);
1013 return Context.getRValueReferenceType(PointeeType);
1014 }
1015
1016 case pch::TYPE_MEMBER_POINTER: {
1017 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1018 QualType PointeeType = GetType(Record[0]);
1019 QualType ClassType = GetType(Record[1]);
1020 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1021 }
1022
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001023 case pch::TYPE_CONSTANT_ARRAY: {
1024 QualType ElementType = GetType(Record[0]);
1025 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1026 unsigned IndexTypeQuals = Record[2];
1027 unsigned Idx = 3;
1028 llvm::APInt Size = ReadAPInt(Record, Idx);
1029 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1030 }
1031
1032 case pch::TYPE_INCOMPLETE_ARRAY: {
1033 QualType ElementType = GetType(Record[0]);
1034 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1035 unsigned IndexTypeQuals = Record[2];
1036 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1037 }
1038
1039 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001040 QualType ElementType = GetType(Record[0]);
1041 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1042 unsigned IndexTypeQuals = Record[2];
1043 return Context.getVariableArrayType(ElementType, ReadExpr(),
1044 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001045 }
1046
1047 case pch::TYPE_VECTOR: {
1048 if (Record.size() != 2) {
1049 Error("Incorrect encoding of vector type in PCH file");
1050 return QualType();
1051 }
1052
1053 QualType ElementType = GetType(Record[0]);
1054 unsigned NumElements = Record[1];
1055 return Context.getVectorType(ElementType, NumElements);
1056 }
1057
1058 case pch::TYPE_EXT_VECTOR: {
1059 if (Record.size() != 2) {
1060 Error("Incorrect encoding of extended vector type in PCH file");
1061 return QualType();
1062 }
1063
1064 QualType ElementType = GetType(Record[0]);
1065 unsigned NumElements = Record[1];
1066 return Context.getExtVectorType(ElementType, NumElements);
1067 }
1068
1069 case pch::TYPE_FUNCTION_NO_PROTO: {
1070 if (Record.size() != 1) {
1071 Error("Incorrect encoding of no-proto function type");
1072 return QualType();
1073 }
1074 QualType ResultType = GetType(Record[0]);
1075 return Context.getFunctionNoProtoType(ResultType);
1076 }
1077
1078 case pch::TYPE_FUNCTION_PROTO: {
1079 QualType ResultType = GetType(Record[0]);
1080 unsigned Idx = 1;
1081 unsigned NumParams = Record[Idx++];
1082 llvm::SmallVector<QualType, 16> ParamTypes;
1083 for (unsigned I = 0; I != NumParams; ++I)
1084 ParamTypes.push_back(GetType(Record[Idx++]));
1085 bool isVariadic = Record[Idx++];
1086 unsigned Quals = Record[Idx++];
1087 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1088 isVariadic, Quals);
1089 }
1090
1091 case pch::TYPE_TYPEDEF:
1092 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1093 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1094
1095 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001096 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001097
1098 case pch::TYPE_TYPEOF: {
1099 if (Record.size() != 1) {
1100 Error("Incorrect encoding of typeof(type) in PCH file");
1101 return QualType();
1102 }
1103 QualType UnderlyingType = GetType(Record[0]);
1104 return Context.getTypeOfType(UnderlyingType);
1105 }
1106
1107 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001108 assert(Record.size() == 1 && "Incorrect encoding of record type");
1109 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001110
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001111 case pch::TYPE_ENUM:
1112 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1113 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1114
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001115 case pch::TYPE_OBJC_INTERFACE:
1116 // FIXME: Deserialize ObjCInterfaceType
1117 assert(false && "Cannot de-serialize ObjC interface types yet");
1118 return QualType();
1119
1120 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1121 // FIXME: Deserialize ObjCQualifiedInterfaceType
1122 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1123 return QualType();
1124
1125 case pch::TYPE_OBJC_QUALIFIED_ID:
1126 // FIXME: Deserialize ObjCQualifiedIdType
1127 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1128 return QualType();
1129
1130 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1131 // FIXME: Deserialize ObjCQualifiedClassType
1132 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1133 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001134 }
1135
1136 // Suppress a GCC warning
1137 return QualType();
1138}
1139
1140/// \brief Note that we have loaded the declaration with the given
1141/// Index.
1142///
1143/// This routine notes that this declaration has already been loaded,
1144/// so that future GetDecl calls will return this declaration rather
1145/// than trying to load a new declaration.
1146inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1147 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1148 DeclAlreadyLoaded[Index] = true;
1149 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1150}
1151
1152/// \brief Read the declaration at the given offset from the PCH file.
1153Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001154 // Keep track of where we are in the stream, then jump back there
1155 // after reading this declaration.
1156 SavedStreamPosition SavedPosition(Stream);
1157
Douglas Gregorc34897d2009-04-09 22:27:44 +00001158 Decl *D = 0;
1159 Stream.JumpToBit(Offset);
1160 RecordData Record;
1161 unsigned Code = Stream.ReadCode();
1162 unsigned Idx = 0;
1163 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001164
Douglas Gregorc34897d2009-04-09 22:27:44 +00001165 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1166 case pch::DECL_TRANSLATION_UNIT:
1167 assert(Index == 0 && "Translation unit must be at index 0");
1168 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1169 D = Context.getTranslationUnitDecl();
1170 LoadedDecl(Index, D);
1171 break;
1172
1173 case pch::DECL_TYPEDEF: {
1174 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1175 0, QualType());
1176 LoadedDecl(Index, Typedef);
1177 Reader.VisitTypedefDecl(Typedef);
1178 D = Typedef;
1179 break;
1180 }
1181
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001182 case pch::DECL_ENUM: {
1183 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1184 LoadedDecl(Index, Enum);
1185 Reader.VisitEnumDecl(Enum);
1186 D = Enum;
1187 break;
1188 }
1189
Douglas Gregor982365e2009-04-13 21:20:57 +00001190 case pch::DECL_RECORD: {
1191 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1192 0, SourceLocation(), 0, 0);
1193 LoadedDecl(Index, Record);
1194 Reader.VisitRecordDecl(Record);
1195 D = Record;
1196 break;
1197 }
1198
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001199 case pch::DECL_ENUM_CONSTANT: {
1200 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1201 SourceLocation(), 0,
1202 QualType(), 0,
1203 llvm::APSInt());
1204 LoadedDecl(Index, ECD);
1205 Reader.VisitEnumConstantDecl(ECD);
1206 D = ECD;
1207 break;
1208 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001209
1210 case pch::DECL_FUNCTION: {
1211 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1212 DeclarationName(),
1213 QualType());
1214 LoadedDecl(Index, Function);
1215 Reader.VisitFunctionDecl(Function);
1216 D = Function;
1217 break;
1218 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001219
Douglas Gregor982365e2009-04-13 21:20:57 +00001220 case pch::DECL_FIELD: {
1221 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1222 QualType(), 0, false);
1223 LoadedDecl(Index, Field);
1224 Reader.VisitFieldDecl(Field);
1225 D = Field;
1226 break;
1227 }
1228
Douglas Gregorc34897d2009-04-09 22:27:44 +00001229 case pch::DECL_VAR: {
1230 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1231 VarDecl::None, SourceLocation());
1232 LoadedDecl(Index, Var);
1233 Reader.VisitVarDecl(Var);
1234 D = Var;
1235 break;
1236 }
1237
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001238 case pch::DECL_PARM_VAR: {
1239 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1240 QualType(), VarDecl::None, 0);
1241 LoadedDecl(Index, Parm);
1242 Reader.VisitParmVarDecl(Parm);
1243 D = Parm;
1244 break;
1245 }
1246
1247 case pch::DECL_ORIGINAL_PARM_VAR: {
1248 OriginalParmVarDecl *Parm
1249 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1250 QualType(), QualType(), VarDecl::None,
1251 0);
1252 LoadedDecl(Index, Parm);
1253 Reader.VisitOriginalParmVarDecl(Parm);
1254 D = Parm;
1255 break;
1256 }
1257
Douglas Gregor2a491792009-04-13 22:49:25 +00001258 case pch::DECL_FILE_SCOPE_ASM: {
1259 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1260 SourceLocation(), 0);
1261 LoadedDecl(Index, Asm);
1262 Reader.VisitFileScopeAsmDecl(Asm);
1263 D = Asm;
1264 break;
1265 }
1266
1267 case pch::DECL_BLOCK: {
1268 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1269 LoadedDecl(Index, Block);
1270 Reader.VisitBlockDecl(Block);
1271 D = Block;
1272 break;
1273 }
1274
Douglas Gregorc34897d2009-04-09 22:27:44 +00001275 default:
1276 assert(false && "Cannot de-serialize this kind of declaration");
1277 break;
1278 }
1279
1280 // If this declaration is also a declaration context, get the
1281 // offsets for its tables of lexical and visible declarations.
1282 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1283 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1284 if (Offsets.first || Offsets.second) {
1285 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1286 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1287 DeclContextOffsets[DC] = Offsets;
1288 }
1289 }
1290 assert(Idx == Record.size());
1291
1292 return D;
1293}
1294
Douglas Gregorac8f2802009-04-10 17:25:41 +00001295QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001296 unsigned Quals = ID & 0x07;
1297 unsigned Index = ID >> 3;
1298
1299 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1300 QualType T;
1301 switch ((pch::PredefinedTypeIDs)Index) {
1302 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1303 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1304 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1305
1306 case pch::PREDEF_TYPE_CHAR_U_ID:
1307 case pch::PREDEF_TYPE_CHAR_S_ID:
1308 // FIXME: Check that the signedness of CharTy is correct!
1309 T = Context.CharTy;
1310 break;
1311
1312 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1313 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1314 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1315 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1316 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1317 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1318 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1319 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1320 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1321 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1322 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1323 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1324 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1325 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1326 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1327 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1328 }
1329
1330 assert(!T.isNull() && "Unknown predefined type");
1331 return T.getQualifiedType(Quals);
1332 }
1333
1334 Index -= pch::NUM_PREDEF_TYPE_IDS;
1335 if (!TypeAlreadyLoaded[Index]) {
1336 // Load the type from the PCH file.
1337 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1338 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1339 TypeAlreadyLoaded[Index] = true;
1340 }
1341
1342 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1343}
1344
Douglas Gregorac8f2802009-04-10 17:25:41 +00001345Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001346 if (ID == 0)
1347 return 0;
1348
1349 unsigned Index = ID - 1;
1350 if (DeclAlreadyLoaded[Index])
1351 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1352
1353 // Load the declaration from the PCH file.
1354 return ReadDeclRecord(DeclOffsets[Index], Index);
1355}
1356
1357bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001358 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001359 assert(DC->hasExternalLexicalStorage() &&
1360 "DeclContext has no lexical decls in storage");
1361 uint64_t Offset = DeclContextOffsets[DC].first;
1362 assert(Offset && "DeclContext has no lexical decls in storage");
1363
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001364 // Keep track of where we are in the stream, then jump back there
1365 // after reading this context.
1366 SavedStreamPosition SavedPosition(Stream);
1367
Douglas Gregorc34897d2009-04-09 22:27:44 +00001368 // Load the record containing all of the declarations lexically in
1369 // this context.
1370 Stream.JumpToBit(Offset);
1371 RecordData Record;
1372 unsigned Code = Stream.ReadCode();
1373 unsigned RecCode = Stream.ReadRecord(Code, Record);
1374 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1375
1376 // Load all of the declaration IDs
1377 Decls.clear();
1378 Decls.insert(Decls.end(), Record.begin(), Record.end());
1379 return false;
1380}
1381
1382bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1383 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1384 assert(DC->hasExternalVisibleStorage() &&
1385 "DeclContext has no visible decls in storage");
1386 uint64_t Offset = DeclContextOffsets[DC].second;
1387 assert(Offset && "DeclContext has no visible decls in storage");
1388
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001389 // Keep track of where we are in the stream, then jump back there
1390 // after reading this context.
1391 SavedStreamPosition SavedPosition(Stream);
1392
Douglas Gregorc34897d2009-04-09 22:27:44 +00001393 // Load the record containing all of the declarations visible in
1394 // this context.
1395 Stream.JumpToBit(Offset);
1396 RecordData Record;
1397 unsigned Code = Stream.ReadCode();
1398 unsigned RecCode = Stream.ReadRecord(Code, Record);
1399 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1400 if (Record.size() == 0)
1401 return false;
1402
1403 Decls.clear();
1404
1405 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001406 while (Idx < Record.size()) {
1407 Decls.push_back(VisibleDeclaration());
1408 Decls.back().Name = ReadDeclarationName(Record, Idx);
1409
Douglas Gregorc34897d2009-04-09 22:27:44 +00001410 unsigned Size = Record[Idx++];
1411 llvm::SmallVector<unsigned, 4> & LoadedDecls
1412 = Decls.back().Declarations;
1413 LoadedDecls.reserve(Size);
1414 for (unsigned I = 0; I < Size; ++I)
1415 LoadedDecls.push_back(Record[Idx++]);
1416 }
1417
1418 return false;
1419}
1420
Douglas Gregor631f6c62009-04-14 00:24:19 +00001421void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1422 if (!Consumer)
1423 return;
1424
1425 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1426 Decl *D = GetDecl(ExternalDefinitions[I]);
1427 DeclGroupRef DG(D);
1428 Consumer->HandleTopLevelDecl(DG);
1429 }
1430}
1431
Douglas Gregorc34897d2009-04-09 22:27:44 +00001432void PCHReader::PrintStats() {
1433 std::fprintf(stderr, "*** PCH Statistics:\n");
1434
1435 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1436 TypeAlreadyLoaded.end(),
1437 true);
1438 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1439 DeclAlreadyLoaded.end(),
1440 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001441 unsigned NumIdentifiersLoaded = 0;
1442 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1443 if ((IdentifierData[I] & 0x01) == 0)
1444 ++NumIdentifiersLoaded;
1445 }
1446
Douglas Gregorc34897d2009-04-09 22:27:44 +00001447 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1448 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001449 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001450 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1451 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001452 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1453 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1454 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1455 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001456 std::fprintf(stderr, "\n");
1457}
1458
Chris Lattner29241862009-04-11 21:15:38 +00001459IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001460 if (ID == 0)
1461 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001462
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001463 if (!IdentifierTable || IdentifierData.empty()) {
1464 Error("No identifier table in PCH file");
1465 return 0;
1466 }
Chris Lattner29241862009-04-11 21:15:38 +00001467
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001468 if (IdentifierData[ID - 1] & 0x01) {
1469 uint64_t Offset = IdentifierData[ID - 1];
1470 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001471 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001472 }
Chris Lattner29241862009-04-11 21:15:38 +00001473
1474 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001475}
1476
1477DeclarationName
1478PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1479 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1480 switch (Kind) {
1481 case DeclarationName::Identifier:
1482 return DeclarationName(GetIdentifierInfo(Record, Idx));
1483
1484 case DeclarationName::ObjCZeroArgSelector:
1485 case DeclarationName::ObjCOneArgSelector:
1486 case DeclarationName::ObjCMultiArgSelector:
1487 assert(false && "Unable to de-serialize Objective-C selectors");
1488 break;
1489
1490 case DeclarationName::CXXConstructorName:
1491 return Context.DeclarationNames.getCXXConstructorName(
1492 GetType(Record[Idx++]));
1493
1494 case DeclarationName::CXXDestructorName:
1495 return Context.DeclarationNames.getCXXDestructorName(
1496 GetType(Record[Idx++]));
1497
1498 case DeclarationName::CXXConversionFunctionName:
1499 return Context.DeclarationNames.getCXXConversionFunctionName(
1500 GetType(Record[Idx++]));
1501
1502 case DeclarationName::CXXOperatorName:
1503 return Context.DeclarationNames.getCXXOperatorName(
1504 (OverloadedOperatorKind)Record[Idx++]);
1505
1506 case DeclarationName::CXXUsingDirective:
1507 return DeclarationName::getUsingDirectiveName();
1508 }
1509
1510 // Required to silence GCC warning
1511 return DeclarationName();
1512}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001513
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001514/// \brief Read an integral value
1515llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1516 unsigned BitWidth = Record[Idx++];
1517 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1518 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1519 Idx += NumWords;
1520 return Result;
1521}
1522
1523/// \brief Read a signed integral value
1524llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1525 bool isUnsigned = Record[Idx++];
1526 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1527}
1528
Douglas Gregore2f37202009-04-14 21:55:33 +00001529/// \brief Read a floating-point value
1530llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1531 // FIXME: is this really correct?
1532 return llvm::APFloat(ReadAPInt(Record, Idx));
1533}
1534
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001535Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001536 // Within the bitstream, expressions are stored in Reverse Polish
1537 // Notation, with each of the subexpressions preceding the
1538 // expression they are stored in. To evaluate expressions, we
1539 // continue reading expressions and placing them on the stack, with
1540 // expressions having operands removing those operands from the
1541 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1542 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001543 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001544 unsigned Idx;
1545 llvm::SmallVector<Expr *, 16> ExprStack;
1546 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001547 Stmt::EmptyShell Empty;
1548
Douglas Gregora151ba42009-04-14 23:32:43 +00001549 while (true) {
1550 unsigned Code = Stream.ReadCode();
1551 if (Code == llvm::bitc::END_BLOCK) {
1552 if (Stream.ReadBlockEnd()) {
1553 Error("Error at end of Source Manager block");
1554 return 0;
1555 }
1556 break;
1557 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001558
Douglas Gregora151ba42009-04-14 23:32:43 +00001559 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1560 // No known subblocks, always skip them.
1561 Stream.ReadSubBlockID();
1562 if (Stream.SkipBlock()) {
1563 Error("Malformed block record");
1564 return 0;
1565 }
1566 continue;
1567 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001568
Douglas Gregora151ba42009-04-14 23:32:43 +00001569 if (Code == llvm::bitc::DEFINE_ABBREV) {
1570 Stream.ReadAbbrevRecord();
1571 continue;
1572 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001573
Douglas Gregora151ba42009-04-14 23:32:43 +00001574 Expr *E = 0;
1575 Idx = 0;
1576 Record.clear();
1577 bool Finished = false;
1578 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1579 case pch::EXPR_STOP:
1580 Finished = true;
1581 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001582
Douglas Gregora151ba42009-04-14 23:32:43 +00001583 case pch::EXPR_NULL:
1584 E = 0;
1585 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001586
Douglas Gregora151ba42009-04-14 23:32:43 +00001587 case pch::EXPR_PREDEFINED:
1588 // FIXME: untested (until we can serialize function bodies).
1589 E = new (Context) PredefinedExpr(Empty);
1590 break;
1591
1592 case pch::EXPR_DECL_REF:
1593 E = new (Context) DeclRefExpr(Empty);
1594 break;
1595
1596 case pch::EXPR_INTEGER_LITERAL:
1597 E = new (Context) IntegerLiteral(Empty);
1598 break;
1599
1600 case pch::EXPR_FLOATING_LITERAL:
1601 E = new (Context) FloatingLiteral(Empty);
1602 break;
1603
1604 case pch::EXPR_CHARACTER_LITERAL:
1605 E = new (Context) CharacterLiteral(Empty);
1606 break;
1607
1608 case pch::EXPR_IMPLICIT_CAST:
1609 E = new (Context) ImplicitCastExpr(Empty);
1610 break;
1611 }
1612
1613 // We hit an EXPR_STOP, so we're done with this expression.
1614 if (Finished)
1615 break;
1616
1617 if (E) {
1618 unsigned NumSubExprs = Reader.Visit(E);
1619 while (NumSubExprs > 0) {
1620 ExprStack.pop_back();
1621 --NumSubExprs;
1622 }
1623 }
1624
1625 assert(Idx == Record.size() && "Invalid deserialization of expression");
1626 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001627 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001628 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1629 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001630}
1631
Douglas Gregor179cfb12009-04-10 20:39:37 +00001632DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001633 return Diag(SourceLocation(), DiagID);
1634}
1635
1636DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1637 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001638 Context.getSourceManager()),
1639 DiagID);
1640}