blob: 2da21023c7747e823e129369a19dc89dccc88e92 [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 Gregor596e0932009-04-15 16:35:07 +0000229 /// \brief The number of record fields required for the Expr class
230 /// itself.
231 static const unsigned NumExprFields = 3;
232
Douglas Gregora151ba42009-04-14 23:32:43 +0000233 // Each of the Visit* functions reads in part of the expression
234 // from the given record and the current expression stack, then
235 // return the total number of operands that it read from the
236 // expression stack.
237
238 unsigned VisitExpr(Expr *E);
239 unsigned VisitPredefinedExpr(PredefinedExpr *E);
240 unsigned VisitDeclRefExpr(DeclRefExpr *E);
241 unsigned VisitIntegerLiteral(IntegerLiteral *E);
242 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000243 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000244 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000245 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000246 unsigned VisitUnaryOperator(UnaryOperator *E);
247 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000248 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000249 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000250 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000251 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
252 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000253 };
254}
255
Douglas Gregora151ba42009-04-14 23:32:43 +0000256unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000257 E->setType(Reader.GetType(Record[Idx++]));
258 E->setTypeDependent(Record[Idx++]);
259 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000260 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000261 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000262}
263
Douglas Gregora151ba42009-04-14 23:32:43 +0000264unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000265 VisitExpr(E);
266 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
267 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000268 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000269}
270
Douglas Gregora151ba42009-04-14 23:32:43 +0000271unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000272 VisitExpr(E);
273 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
274 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000275 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000276}
277
Douglas Gregora151ba42009-04-14 23:32:43 +0000278unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000279 VisitExpr(E);
280 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
281 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000282 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000283}
284
Douglas Gregora151ba42009-04-14 23:32:43 +0000285unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000286 VisitExpr(E);
287 E->setValue(Reader.ReadAPFloat(Record, Idx));
288 E->setExact(Record[Idx++]);
289 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000290 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000291}
292
Douglas Gregor596e0932009-04-15 16:35:07 +0000293unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
294 VisitExpr(E);
295 unsigned Len = Record[Idx++];
296 assert(Record[Idx] == E->getNumConcatenated() &&
297 "Wrong number of concatenated tokens!");
298 ++Idx;
299 E->setWide(Record[Idx++]);
300
301 // Read string data
302 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
303 E->setStrData(Reader.getContext(), &Str[0], Len);
304 Idx += Len;
305
306 // Read source locations
307 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
308 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
309
310 return 0;
311}
312
Douglas Gregora151ba42009-04-14 23:32:43 +0000313unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000314 VisitExpr(E);
315 E->setValue(Record[Idx++]);
316 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
317 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000318 return 0;
319}
320
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000321unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
322 VisitExpr(E);
323 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
324 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
325 E->setSubExpr(ExprStack.back());
326 return 1;
327}
328
Douglas Gregor12d74052009-04-15 15:58:59 +0000329unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
330 VisitExpr(E);
331 E->setSubExpr(ExprStack.back());
332 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
333 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
334 return 1;
335}
336
337unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
338 VisitExpr(E);
339 E->setSizeof(Record[Idx++]);
340 if (Record[Idx] == 0) {
341 E->setArgument(ExprStack.back());
342 ++Idx;
343 } else {
344 E->setArgument(Reader.GetType(Record[Idx++]));
345 }
346 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
347 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
348 return E->isArgumentType()? 0 : 1;
349}
350
Douglas Gregora151ba42009-04-14 23:32:43 +0000351unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
352 VisitExpr(E);
353 E->setSubExpr(ExprStack.back());
354 return 1;
355}
356
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000357unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
358 VisitExpr(E);
359 E->setLHS(ExprStack.end()[-2]);
360 E->setRHS(ExprStack.end()[-1]);
361 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
362 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
363 return 2;
364}
365
Douglas Gregora151ba42009-04-14 23:32:43 +0000366unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
367 VisitCastExpr(E);
368 E->setLvalueCast(Record[Idx++]);
369 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000370}
371
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000372unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
373 VisitCastExpr(E);
374 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
375 return 1;
376}
377
378unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
379 VisitExplicitCastExpr(E);
380 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
381 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
382 return 1;
383}
384
Douglas Gregorc34897d2009-04-09 22:27:44 +0000385// FIXME: use the diagnostics machinery
386static bool Error(const char *Str) {
387 std::fprintf(stderr, "%s\n", Str);
388 return true;
389}
390
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000391/// \brief Check the contents of the predefines buffer against the
392/// contents of the predefines buffer used to build the PCH file.
393///
394/// The contents of the two predefines buffers should be the same. If
395/// not, then some command-line option changed the preprocessor state
396/// and we must reject the PCH file.
397///
398/// \param PCHPredef The start of the predefines buffer in the PCH
399/// file.
400///
401/// \param PCHPredefLen The length of the predefines buffer in the PCH
402/// file.
403///
404/// \param PCHBufferID The FileID for the PCH predefines buffer.
405///
406/// \returns true if there was a mismatch (in which case the PCH file
407/// should be ignored), or false otherwise.
408bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
409 unsigned PCHPredefLen,
410 FileID PCHBufferID) {
411 const char *Predef = PP.getPredefines().c_str();
412 unsigned PredefLen = PP.getPredefines().size();
413
414 // If the two predefines buffers compare equal, we're done!.
415 if (PredefLen == PCHPredefLen &&
416 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
417 return false;
418
419 // The predefines buffers are different. Produce a reasonable
420 // diagnostic showing where they are different.
421
422 // The source locations (potentially in the two different predefines
423 // buffers)
424 SourceLocation Loc1, Loc2;
425 SourceManager &SourceMgr = PP.getSourceManager();
426
427 // Create a source buffer for our predefines string, so
428 // that we can build a diagnostic that points into that
429 // source buffer.
430 FileID BufferID;
431 if (Predef && Predef[0]) {
432 llvm::MemoryBuffer *Buffer
433 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
434 "<built-in>");
435 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
436 }
437
438 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
439 std::pair<const char *, const char *> Locations
440 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
441
442 if (Locations.first != Predef + MinLen) {
443 // We found the location in the two buffers where there is a
444 // difference. Form source locations to point there (in both
445 // buffers).
446 unsigned Offset = Locations.first - Predef;
447 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
448 .getFileLocWithOffset(Offset);
449 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
450 .getFileLocWithOffset(Offset);
451 } else if (PredefLen > PCHPredefLen) {
452 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
453 .getFileLocWithOffset(MinLen);
454 } else {
455 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
456 .getFileLocWithOffset(MinLen);
457 }
458
459 Diag(Loc1, diag::warn_pch_preprocessor);
460 if (Loc2.isValid())
461 Diag(Loc2, diag::note_predef_in_pch);
462 Diag(diag::note_ignoring_pch) << FileName;
463 return true;
464}
465
Douglas Gregor635f97f2009-04-13 16:31:14 +0000466/// \brief Read the line table in the source manager block.
467/// \returns true if ther was an error.
468static bool ParseLineTable(SourceManager &SourceMgr,
469 llvm::SmallVectorImpl<uint64_t> &Record) {
470 unsigned Idx = 0;
471 LineTableInfo &LineTable = SourceMgr.getLineTable();
472
473 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000474 std::map<int, int> FileIDs;
475 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000476 // Extract the file name
477 unsigned FilenameLen = Record[Idx++];
478 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
479 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000480 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
481 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000482 }
483
484 // Parse the line entries
485 std::vector<LineEntry> Entries;
486 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000487 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000488
489 // Extract the line entries
490 unsigned NumEntries = Record[Idx++];
491 Entries.clear();
492 Entries.reserve(NumEntries);
493 for (unsigned I = 0; I != NumEntries; ++I) {
494 unsigned FileOffset = Record[Idx++];
495 unsigned LineNo = Record[Idx++];
496 int FilenameID = Record[Idx++];
497 SrcMgr::CharacteristicKind FileKind
498 = (SrcMgr::CharacteristicKind)Record[Idx++];
499 unsigned IncludeOffset = Record[Idx++];
500 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
501 FileKind, IncludeOffset));
502 }
503 LineTable.AddEntry(FID, Entries);
504 }
505
506 return false;
507}
508
Douglas Gregorab1cef72009-04-10 03:52:48 +0000509/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000510PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000511 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000512 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
513 Error("Malformed source manager block record");
514 return Failure;
515 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000516
517 SourceManager &SourceMgr = Context.getSourceManager();
518 RecordData Record;
519 while (true) {
520 unsigned Code = Stream.ReadCode();
521 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000522 if (Stream.ReadBlockEnd()) {
523 Error("Error at end of Source Manager block");
524 return Failure;
525 }
526
527 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000528 }
529
530 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
531 // No known subblocks, always skip them.
532 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000533 if (Stream.SkipBlock()) {
534 Error("Malformed block record");
535 return Failure;
536 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000537 continue;
538 }
539
540 if (Code == llvm::bitc::DEFINE_ABBREV) {
541 Stream.ReadAbbrevRecord();
542 continue;
543 }
544
545 // Read a record.
546 const char *BlobStart;
547 unsigned BlobLen;
548 Record.clear();
549 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
550 default: // Default behavior: ignore.
551 break;
552
553 case pch::SM_SLOC_FILE_ENTRY: {
554 // FIXME: We would really like to delay the creation of this
555 // FileEntry until it is actually required, e.g., when producing
556 // a diagnostic with a source location in this file.
557 const FileEntry *File
558 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
559 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000560 FileID ID = SourceMgr.createFileID(File,
561 SourceLocation::getFromRawEncoding(Record[1]),
562 (CharacteristicKind)Record[2]);
563 if (Record[3])
564 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
565 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000566 break;
567 }
568
569 case pch::SM_SLOC_BUFFER_ENTRY: {
570 const char *Name = BlobStart;
571 unsigned Code = Stream.ReadCode();
572 Record.clear();
573 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
574 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000575 llvm::MemoryBuffer *Buffer
576 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
577 BlobStart + BlobLen - 1,
578 Name);
579 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
580
581 if (strcmp(Name, "<built-in>") == 0
582 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
583 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000584 break;
585 }
586
587 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
588 SourceLocation SpellingLoc
589 = SourceLocation::getFromRawEncoding(Record[1]);
590 SourceMgr.createInstantiationLoc(
591 SpellingLoc,
592 SourceLocation::getFromRawEncoding(Record[2]),
593 SourceLocation::getFromRawEncoding(Record[3]),
594 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000595 SourceMgr,
596 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000597 break;
598 }
599
Chris Lattnere1be6022009-04-14 23:22:57 +0000600 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000601 if (ParseLineTable(SourceMgr, Record))
602 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000603 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000604 }
605 }
606}
607
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000608bool PCHReader::ReadPreprocessorBlock() {
609 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
610 return Error("Malformed preprocessor block record");
611
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000612 RecordData Record;
613 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
614 MacroInfo *LastMacro = 0;
615
616 while (true) {
617 unsigned Code = Stream.ReadCode();
618 switch (Code) {
619 case llvm::bitc::END_BLOCK:
620 if (Stream.ReadBlockEnd())
621 return Error("Error at end of preprocessor block");
622 return false;
623
624 case llvm::bitc::ENTER_SUBBLOCK:
625 // No known subblocks, always skip them.
626 Stream.ReadSubBlockID();
627 if (Stream.SkipBlock())
628 return Error("Malformed block record");
629 continue;
630
631 case llvm::bitc::DEFINE_ABBREV:
632 Stream.ReadAbbrevRecord();
633 continue;
634 default: break;
635 }
636
637 // Read a record.
638 Record.clear();
639 pch::PreprocessorRecordTypes RecType =
640 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
641 switch (RecType) {
642 default: // Default behavior: ignore unknown records.
643 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000644 case pch::PP_COUNTER_VALUE:
645 if (!Record.empty())
646 PP.setCounterValue(Record[0]);
647 break;
648
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000649 case pch::PP_MACRO_OBJECT_LIKE:
650 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000651 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
652 if (II == 0)
653 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000654 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
655 bool isUsed = Record[2];
656
657 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
658 MI->setIsUsed(isUsed);
659
660 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
661 // Decode function-like macro info.
662 bool isC99VarArgs = Record[3];
663 bool isGNUVarArgs = Record[4];
664 MacroArgs.clear();
665 unsigned NumArgs = Record[5];
666 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000667 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000668
669 // Install function-like macro info.
670 MI->setIsFunctionLike();
671 if (isC99VarArgs) MI->setIsC99Varargs();
672 if (isGNUVarArgs) MI->setIsGNUVarargs();
673 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
674 PP.getPreprocessorAllocator());
675 }
676
677 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000678 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000679
680 // Remember that we saw this macro last so that we add the tokens that
681 // form its body to it.
682 LastMacro = MI;
683 break;
684 }
685
686 case pch::PP_TOKEN: {
687 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
688 // pretend we didn't see this.
689 if (LastMacro == 0) break;
690
691 Token Tok;
692 Tok.startToken();
693 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
694 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000695 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
696 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000697 Tok.setKind((tok::TokenKind)Record[3]);
698 Tok.setFlag((Token::TokenFlags)Record[4]);
699 LastMacro->AddTokenToBody(Tok);
700 break;
701 }
702 }
703 }
704}
705
Douglas Gregor179cfb12009-04-10 20:39:37 +0000706PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
707 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
708 Error("Malformed block record");
709 return Failure;
710 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000711
Chris Lattner29241862009-04-11 21:15:38 +0000712 uint64_t PreprocessorBlockBit = 0;
713
Douglas Gregorc34897d2009-04-09 22:27:44 +0000714 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000715 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000716 while (!Stream.AtEndOfStream()) {
717 unsigned Code = Stream.ReadCode();
718 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000719 // If we saw the preprocessor block, read it now.
720 if (PreprocessorBlockBit) {
721 uint64_t SavedPos = Stream.GetCurrentBitNo();
722 Stream.JumpToBit(PreprocessorBlockBit);
723 if (ReadPreprocessorBlock()) {
724 Error("Malformed preprocessor block");
725 return Failure;
726 }
727 Stream.JumpToBit(SavedPos);
728 }
729
Douglas Gregor179cfb12009-04-10 20:39:37 +0000730 if (Stream.ReadBlockEnd()) {
731 Error("Error at end of module block");
732 return Failure;
733 }
Chris Lattner29241862009-04-11 21:15:38 +0000734
Douglas Gregor179cfb12009-04-10 20:39:37 +0000735 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000736 }
737
738 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
739 switch (Stream.ReadSubBlockID()) {
740 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
741 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
742 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000743 if (Stream.SkipBlock()) {
744 Error("Malformed block record");
745 return Failure;
746 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000747 break;
748
Chris Lattner29241862009-04-11 21:15:38 +0000749 case pch::PREPROCESSOR_BLOCK_ID:
750 // Skip the preprocessor block for now, but remember where it is. We
751 // want to read it in after the identifier table.
752 if (PreprocessorBlockBit) {
753 Error("Multiple preprocessor blocks found.");
754 return Failure;
755 }
756 PreprocessorBlockBit = Stream.GetCurrentBitNo();
757 if (Stream.SkipBlock()) {
758 Error("Malformed block record");
759 return Failure;
760 }
761 break;
762
Douglas Gregorab1cef72009-04-10 03:52:48 +0000763 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000764 switch (ReadSourceManagerBlock()) {
765 case Success:
766 break;
767
768 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000769 Error("Malformed source manager block");
770 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000771
772 case IgnorePCH:
773 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000774 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000775 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000776 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000777 continue;
778 }
779
780 if (Code == llvm::bitc::DEFINE_ABBREV) {
781 Stream.ReadAbbrevRecord();
782 continue;
783 }
784
785 // Read and process a record.
786 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000787 const char *BlobStart = 0;
788 unsigned BlobLen = 0;
789 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
790 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000791 default: // Default behavior: ignore.
792 break;
793
794 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000795 if (!TypeOffsets.empty()) {
796 Error("Duplicate TYPE_OFFSET record in PCH file");
797 return Failure;
798 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000799 TypeOffsets.swap(Record);
800 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
801 break;
802
803 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000804 if (!DeclOffsets.empty()) {
805 Error("Duplicate DECL_OFFSET record in PCH file");
806 return Failure;
807 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000808 DeclOffsets.swap(Record);
809 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
810 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000811
812 case pch::LANGUAGE_OPTIONS:
813 if (ParseLanguageOptions(Record))
814 return IgnorePCH;
815 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000816
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000817 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000818 std::string TargetTriple(BlobStart, BlobLen);
819 if (TargetTriple != Context.Target.getTargetTriple()) {
820 Diag(diag::warn_pch_target_triple)
821 << TargetTriple << Context.Target.getTargetTriple();
822 Diag(diag::note_ignoring_pch) << FileName;
823 return IgnorePCH;
824 }
825 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000826 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000827
828 case pch::IDENTIFIER_TABLE:
829 IdentifierTable = BlobStart;
830 break;
831
832 case pch::IDENTIFIER_OFFSET:
833 if (!IdentifierData.empty()) {
834 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
835 return Failure;
836 }
837 IdentifierData.swap(Record);
838#ifndef NDEBUG
839 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
840 if ((IdentifierData[I] & 0x01) == 0) {
841 Error("Malformed identifier table in the precompiled header");
842 return Failure;
843 }
844 }
845#endif
846 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000847
848 case pch::EXTERNAL_DEFINITIONS:
849 if (!ExternalDefinitions.empty()) {
850 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
851 return Failure;
852 }
853 ExternalDefinitions.swap(Record);
854 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000855 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000856 }
857
Douglas Gregor179cfb12009-04-10 20:39:37 +0000858 Error("Premature end of bitstream");
859 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000860}
861
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000862PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000863 // Set the PCH file name.
864 this->FileName = FileName;
865
Douglas Gregorc34897d2009-04-09 22:27:44 +0000866 // Open the PCH file.
867 std::string ErrStr;
868 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000869 if (!Buffer) {
870 Error(ErrStr.c_str());
871 return IgnorePCH;
872 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000873
874 // Initialize the stream
875 Stream.init((const unsigned char *)Buffer->getBufferStart(),
876 (const unsigned char *)Buffer->getBufferEnd());
877
878 // Sniff for the signature.
879 if (Stream.Read(8) != 'C' ||
880 Stream.Read(8) != 'P' ||
881 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000882 Stream.Read(8) != 'H') {
883 Error("Not a PCH file");
884 return IgnorePCH;
885 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000886
887 // We expect a number of well-defined blocks, though we don't necessarily
888 // need to understand them all.
889 while (!Stream.AtEndOfStream()) {
890 unsigned Code = Stream.ReadCode();
891
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000892 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
893 Error("Invalid record at top-level");
894 return Failure;
895 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000896
897 unsigned BlockID = Stream.ReadSubBlockID();
898
899 // We only know the PCH subblock ID.
900 switch (BlockID) {
901 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000902 if (Stream.ReadBlockInfoBlock()) {
903 Error("Malformed BlockInfoBlock");
904 return Failure;
905 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000906 break;
907 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000908 switch (ReadPCHBlock()) {
909 case Success:
910 break;
911
912 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000913 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000914
915 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000916 // FIXME: We could consider reading through to the end of this
917 // PCH block, skipping subblocks, to see if there are other
918 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000919 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000920 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000921 break;
922 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000923 if (Stream.SkipBlock()) {
924 Error("Malformed block record");
925 return Failure;
926 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000927 break;
928 }
929 }
930
931 // Load the translation unit declaration
932 ReadDeclRecord(DeclOffsets[0], 0);
933
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000934 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000935}
936
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000937namespace {
938 /// \brief Helper class that saves the current stream position and
939 /// then restores it when destroyed.
940 struct VISIBILITY_HIDDEN SavedStreamPosition {
941 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000942 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000943
944 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000945 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000946 }
947
948 private:
949 llvm::BitstreamReader &Stream;
950 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000951 };
952}
953
Douglas Gregor179cfb12009-04-10 20:39:37 +0000954/// \brief Parse the record that corresponds to a LangOptions data
955/// structure.
956///
957/// This routine compares the language options used to generate the
958/// PCH file against the language options set for the current
959/// compilation. For each option, we classify differences between the
960/// two compiler states as either "benign" or "important". Benign
961/// differences don't matter, and we accept them without complaint
962/// (and without modifying the language options). Differences between
963/// the states for important options cause the PCH file to be
964/// unusable, so we emit a warning and return true to indicate that
965/// there was an error.
966///
967/// \returns true if the PCH file is unacceptable, false otherwise.
968bool PCHReader::ParseLanguageOptions(
969 const llvm::SmallVectorImpl<uint64_t> &Record) {
970 const LangOptions &LangOpts = Context.getLangOptions();
971#define PARSE_LANGOPT_BENIGN(Option) ++Idx
972#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
973 if (Record[Idx] != LangOpts.Option) { \
974 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
975 Diag(diag::note_ignoring_pch) << FileName; \
976 return true; \
977 } \
978 ++Idx
979
980 unsigned Idx = 0;
981 PARSE_LANGOPT_BENIGN(Trigraphs);
982 PARSE_LANGOPT_BENIGN(BCPLComment);
983 PARSE_LANGOPT_BENIGN(DollarIdents);
984 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
985 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
986 PARSE_LANGOPT_BENIGN(ImplicitInt);
987 PARSE_LANGOPT_BENIGN(Digraphs);
988 PARSE_LANGOPT_BENIGN(HexFloats);
989 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
990 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
991 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
992 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
993 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
994 PARSE_LANGOPT_BENIGN(CXXOperatorName);
995 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
996 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
997 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
998 PARSE_LANGOPT_BENIGN(PascalStrings);
999 PARSE_LANGOPT_BENIGN(Boolean);
1000 PARSE_LANGOPT_BENIGN(WritableStrings);
1001 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1002 diag::warn_pch_lax_vector_conversions);
1003 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1004 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1005 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1006 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1007 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1008 diag::warn_pch_thread_safe_statics);
1009 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1010 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1011 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1012 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1013 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1014 diag::warn_pch_heinous_extensions);
1015 // FIXME: Most of the options below are benign if the macro wasn't
1016 // used. Unfortunately, this means that a PCH compiled without
1017 // optimization can't be used with optimization turned on, even
1018 // though the only thing that changes is whether __OPTIMIZE__ was
1019 // defined... but if __OPTIMIZE__ never showed up in the header, it
1020 // doesn't matter. We could consider making this some special kind
1021 // of check.
1022 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1023 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1024 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1025 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1026 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1027 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1028 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1029 Diag(diag::warn_pch_gc_mode)
1030 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1031 Diag(diag::note_ignoring_pch) << FileName;
1032 return true;
1033 }
1034 ++Idx;
1035 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1036 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1037#undef PARSE_LANGOPT_IRRELEVANT
1038#undef PARSE_LANGOPT_BENIGN
1039
1040 return false;
1041}
1042
Douglas Gregorc34897d2009-04-09 22:27:44 +00001043/// \brief Read and return the type at the given offset.
1044///
1045/// This routine actually reads the record corresponding to the type
1046/// at the given offset in the bitstream. It is a helper routine for
1047/// GetType, which deals with reading type IDs.
1048QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001049 // Keep track of where we are in the stream, then jump back there
1050 // after reading this type.
1051 SavedStreamPosition SavedPosition(Stream);
1052
Douglas Gregorc34897d2009-04-09 22:27:44 +00001053 Stream.JumpToBit(Offset);
1054 RecordData Record;
1055 unsigned Code = Stream.ReadCode();
1056 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001057 case pch::TYPE_EXT_QUAL:
1058 // FIXME: Deserialize ExtQualType
1059 assert(false && "Cannot deserialize qualified types yet");
1060 return QualType();
1061
Douglas Gregorc34897d2009-04-09 22:27:44 +00001062 case pch::TYPE_FIXED_WIDTH_INT: {
1063 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1064 return Context.getFixedWidthIntType(Record[0], Record[1]);
1065 }
1066
1067 case pch::TYPE_COMPLEX: {
1068 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1069 QualType ElemType = GetType(Record[0]);
1070 return Context.getComplexType(ElemType);
1071 }
1072
1073 case pch::TYPE_POINTER: {
1074 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1075 QualType PointeeType = GetType(Record[0]);
1076 return Context.getPointerType(PointeeType);
1077 }
1078
1079 case pch::TYPE_BLOCK_POINTER: {
1080 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1081 QualType PointeeType = GetType(Record[0]);
1082 return Context.getBlockPointerType(PointeeType);
1083 }
1084
1085 case pch::TYPE_LVALUE_REFERENCE: {
1086 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1087 QualType PointeeType = GetType(Record[0]);
1088 return Context.getLValueReferenceType(PointeeType);
1089 }
1090
1091 case pch::TYPE_RVALUE_REFERENCE: {
1092 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1093 QualType PointeeType = GetType(Record[0]);
1094 return Context.getRValueReferenceType(PointeeType);
1095 }
1096
1097 case pch::TYPE_MEMBER_POINTER: {
1098 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1099 QualType PointeeType = GetType(Record[0]);
1100 QualType ClassType = GetType(Record[1]);
1101 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1102 }
1103
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001104 case pch::TYPE_CONSTANT_ARRAY: {
1105 QualType ElementType = GetType(Record[0]);
1106 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1107 unsigned IndexTypeQuals = Record[2];
1108 unsigned Idx = 3;
1109 llvm::APInt Size = ReadAPInt(Record, Idx);
1110 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1111 }
1112
1113 case pch::TYPE_INCOMPLETE_ARRAY: {
1114 QualType ElementType = GetType(Record[0]);
1115 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1116 unsigned IndexTypeQuals = Record[2];
1117 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1118 }
1119
1120 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001121 QualType ElementType = GetType(Record[0]);
1122 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1123 unsigned IndexTypeQuals = Record[2];
1124 return Context.getVariableArrayType(ElementType, ReadExpr(),
1125 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001126 }
1127
1128 case pch::TYPE_VECTOR: {
1129 if (Record.size() != 2) {
1130 Error("Incorrect encoding of vector type in PCH file");
1131 return QualType();
1132 }
1133
1134 QualType ElementType = GetType(Record[0]);
1135 unsigned NumElements = Record[1];
1136 return Context.getVectorType(ElementType, NumElements);
1137 }
1138
1139 case pch::TYPE_EXT_VECTOR: {
1140 if (Record.size() != 2) {
1141 Error("Incorrect encoding of extended vector type in PCH file");
1142 return QualType();
1143 }
1144
1145 QualType ElementType = GetType(Record[0]);
1146 unsigned NumElements = Record[1];
1147 return Context.getExtVectorType(ElementType, NumElements);
1148 }
1149
1150 case pch::TYPE_FUNCTION_NO_PROTO: {
1151 if (Record.size() != 1) {
1152 Error("Incorrect encoding of no-proto function type");
1153 return QualType();
1154 }
1155 QualType ResultType = GetType(Record[0]);
1156 return Context.getFunctionNoProtoType(ResultType);
1157 }
1158
1159 case pch::TYPE_FUNCTION_PROTO: {
1160 QualType ResultType = GetType(Record[0]);
1161 unsigned Idx = 1;
1162 unsigned NumParams = Record[Idx++];
1163 llvm::SmallVector<QualType, 16> ParamTypes;
1164 for (unsigned I = 0; I != NumParams; ++I)
1165 ParamTypes.push_back(GetType(Record[Idx++]));
1166 bool isVariadic = Record[Idx++];
1167 unsigned Quals = Record[Idx++];
1168 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1169 isVariadic, Quals);
1170 }
1171
1172 case pch::TYPE_TYPEDEF:
1173 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1174 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1175
1176 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001177 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001178
1179 case pch::TYPE_TYPEOF: {
1180 if (Record.size() != 1) {
1181 Error("Incorrect encoding of typeof(type) in PCH file");
1182 return QualType();
1183 }
1184 QualType UnderlyingType = GetType(Record[0]);
1185 return Context.getTypeOfType(UnderlyingType);
1186 }
1187
1188 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001189 assert(Record.size() == 1 && "Incorrect encoding of record type");
1190 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001191
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001192 case pch::TYPE_ENUM:
1193 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1194 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1195
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001196 case pch::TYPE_OBJC_INTERFACE:
1197 // FIXME: Deserialize ObjCInterfaceType
1198 assert(false && "Cannot de-serialize ObjC interface types yet");
1199 return QualType();
1200
1201 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1202 // FIXME: Deserialize ObjCQualifiedInterfaceType
1203 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1204 return QualType();
1205
1206 case pch::TYPE_OBJC_QUALIFIED_ID:
1207 // FIXME: Deserialize ObjCQualifiedIdType
1208 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1209 return QualType();
1210
1211 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1212 // FIXME: Deserialize ObjCQualifiedClassType
1213 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1214 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001215 }
1216
1217 // Suppress a GCC warning
1218 return QualType();
1219}
1220
1221/// \brief Note that we have loaded the declaration with the given
1222/// Index.
1223///
1224/// This routine notes that this declaration has already been loaded,
1225/// so that future GetDecl calls will return this declaration rather
1226/// than trying to load a new declaration.
1227inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1228 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1229 DeclAlreadyLoaded[Index] = true;
1230 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1231}
1232
1233/// \brief Read the declaration at the given offset from the PCH file.
1234Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001235 // Keep track of where we are in the stream, then jump back there
1236 // after reading this declaration.
1237 SavedStreamPosition SavedPosition(Stream);
1238
Douglas Gregorc34897d2009-04-09 22:27:44 +00001239 Decl *D = 0;
1240 Stream.JumpToBit(Offset);
1241 RecordData Record;
1242 unsigned Code = Stream.ReadCode();
1243 unsigned Idx = 0;
1244 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001245
Douglas Gregorc34897d2009-04-09 22:27:44 +00001246 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1247 case pch::DECL_TRANSLATION_UNIT:
1248 assert(Index == 0 && "Translation unit must be at index 0");
1249 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1250 D = Context.getTranslationUnitDecl();
1251 LoadedDecl(Index, D);
1252 break;
1253
1254 case pch::DECL_TYPEDEF: {
1255 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1256 0, QualType());
1257 LoadedDecl(Index, Typedef);
1258 Reader.VisitTypedefDecl(Typedef);
1259 D = Typedef;
1260 break;
1261 }
1262
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001263 case pch::DECL_ENUM: {
1264 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1265 LoadedDecl(Index, Enum);
1266 Reader.VisitEnumDecl(Enum);
1267 D = Enum;
1268 break;
1269 }
1270
Douglas Gregor982365e2009-04-13 21:20:57 +00001271 case pch::DECL_RECORD: {
1272 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1273 0, SourceLocation(), 0, 0);
1274 LoadedDecl(Index, Record);
1275 Reader.VisitRecordDecl(Record);
1276 D = Record;
1277 break;
1278 }
1279
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001280 case pch::DECL_ENUM_CONSTANT: {
1281 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1282 SourceLocation(), 0,
1283 QualType(), 0,
1284 llvm::APSInt());
1285 LoadedDecl(Index, ECD);
1286 Reader.VisitEnumConstantDecl(ECD);
1287 D = ECD;
1288 break;
1289 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001290
1291 case pch::DECL_FUNCTION: {
1292 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1293 DeclarationName(),
1294 QualType());
1295 LoadedDecl(Index, Function);
1296 Reader.VisitFunctionDecl(Function);
1297 D = Function;
1298 break;
1299 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001300
Douglas Gregor982365e2009-04-13 21:20:57 +00001301 case pch::DECL_FIELD: {
1302 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1303 QualType(), 0, false);
1304 LoadedDecl(Index, Field);
1305 Reader.VisitFieldDecl(Field);
1306 D = Field;
1307 break;
1308 }
1309
Douglas Gregorc34897d2009-04-09 22:27:44 +00001310 case pch::DECL_VAR: {
1311 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1312 VarDecl::None, SourceLocation());
1313 LoadedDecl(Index, Var);
1314 Reader.VisitVarDecl(Var);
1315 D = Var;
1316 break;
1317 }
1318
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001319 case pch::DECL_PARM_VAR: {
1320 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1321 QualType(), VarDecl::None, 0);
1322 LoadedDecl(Index, Parm);
1323 Reader.VisitParmVarDecl(Parm);
1324 D = Parm;
1325 break;
1326 }
1327
1328 case pch::DECL_ORIGINAL_PARM_VAR: {
1329 OriginalParmVarDecl *Parm
1330 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1331 QualType(), QualType(), VarDecl::None,
1332 0);
1333 LoadedDecl(Index, Parm);
1334 Reader.VisitOriginalParmVarDecl(Parm);
1335 D = Parm;
1336 break;
1337 }
1338
Douglas Gregor2a491792009-04-13 22:49:25 +00001339 case pch::DECL_FILE_SCOPE_ASM: {
1340 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1341 SourceLocation(), 0);
1342 LoadedDecl(Index, Asm);
1343 Reader.VisitFileScopeAsmDecl(Asm);
1344 D = Asm;
1345 break;
1346 }
1347
1348 case pch::DECL_BLOCK: {
1349 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1350 LoadedDecl(Index, Block);
1351 Reader.VisitBlockDecl(Block);
1352 D = Block;
1353 break;
1354 }
1355
Douglas Gregorc34897d2009-04-09 22:27:44 +00001356 default:
1357 assert(false && "Cannot de-serialize this kind of declaration");
1358 break;
1359 }
1360
1361 // If this declaration is also a declaration context, get the
1362 // offsets for its tables of lexical and visible declarations.
1363 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1364 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1365 if (Offsets.first || Offsets.second) {
1366 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1367 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1368 DeclContextOffsets[DC] = Offsets;
1369 }
1370 }
1371 assert(Idx == Record.size());
1372
1373 return D;
1374}
1375
Douglas Gregorac8f2802009-04-10 17:25:41 +00001376QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001377 unsigned Quals = ID & 0x07;
1378 unsigned Index = ID >> 3;
1379
1380 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1381 QualType T;
1382 switch ((pch::PredefinedTypeIDs)Index) {
1383 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1384 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1385 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1386
1387 case pch::PREDEF_TYPE_CHAR_U_ID:
1388 case pch::PREDEF_TYPE_CHAR_S_ID:
1389 // FIXME: Check that the signedness of CharTy is correct!
1390 T = Context.CharTy;
1391 break;
1392
1393 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1394 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1395 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1396 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1397 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1398 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1399 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1400 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1401 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1402 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1403 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1404 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1405 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1406 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1407 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1408 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1409 }
1410
1411 assert(!T.isNull() && "Unknown predefined type");
1412 return T.getQualifiedType(Quals);
1413 }
1414
1415 Index -= pch::NUM_PREDEF_TYPE_IDS;
1416 if (!TypeAlreadyLoaded[Index]) {
1417 // Load the type from the PCH file.
1418 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1419 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1420 TypeAlreadyLoaded[Index] = true;
1421 }
1422
1423 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1424}
1425
Douglas Gregorac8f2802009-04-10 17:25:41 +00001426Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001427 if (ID == 0)
1428 return 0;
1429
1430 unsigned Index = ID - 1;
1431 if (DeclAlreadyLoaded[Index])
1432 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1433
1434 // Load the declaration from the PCH file.
1435 return ReadDeclRecord(DeclOffsets[Index], Index);
1436}
1437
1438bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001439 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001440 assert(DC->hasExternalLexicalStorage() &&
1441 "DeclContext has no lexical decls in storage");
1442 uint64_t Offset = DeclContextOffsets[DC].first;
1443 assert(Offset && "DeclContext has no lexical decls in storage");
1444
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001445 // Keep track of where we are in the stream, then jump back there
1446 // after reading this context.
1447 SavedStreamPosition SavedPosition(Stream);
1448
Douglas Gregorc34897d2009-04-09 22:27:44 +00001449 // Load the record containing all of the declarations lexically in
1450 // this context.
1451 Stream.JumpToBit(Offset);
1452 RecordData Record;
1453 unsigned Code = Stream.ReadCode();
1454 unsigned RecCode = Stream.ReadRecord(Code, Record);
1455 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1456
1457 // Load all of the declaration IDs
1458 Decls.clear();
1459 Decls.insert(Decls.end(), Record.begin(), Record.end());
1460 return false;
1461}
1462
1463bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1464 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1465 assert(DC->hasExternalVisibleStorage() &&
1466 "DeclContext has no visible decls in storage");
1467 uint64_t Offset = DeclContextOffsets[DC].second;
1468 assert(Offset && "DeclContext has no visible decls in storage");
1469
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001470 // Keep track of where we are in the stream, then jump back there
1471 // after reading this context.
1472 SavedStreamPosition SavedPosition(Stream);
1473
Douglas Gregorc34897d2009-04-09 22:27:44 +00001474 // Load the record containing all of the declarations visible in
1475 // this context.
1476 Stream.JumpToBit(Offset);
1477 RecordData Record;
1478 unsigned Code = Stream.ReadCode();
1479 unsigned RecCode = Stream.ReadRecord(Code, Record);
1480 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1481 if (Record.size() == 0)
1482 return false;
1483
1484 Decls.clear();
1485
1486 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001487 while (Idx < Record.size()) {
1488 Decls.push_back(VisibleDeclaration());
1489 Decls.back().Name = ReadDeclarationName(Record, Idx);
1490
Douglas Gregorc34897d2009-04-09 22:27:44 +00001491 unsigned Size = Record[Idx++];
1492 llvm::SmallVector<unsigned, 4> & LoadedDecls
1493 = Decls.back().Declarations;
1494 LoadedDecls.reserve(Size);
1495 for (unsigned I = 0; I < Size; ++I)
1496 LoadedDecls.push_back(Record[Idx++]);
1497 }
1498
1499 return false;
1500}
1501
Douglas Gregor631f6c62009-04-14 00:24:19 +00001502void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1503 if (!Consumer)
1504 return;
1505
1506 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1507 Decl *D = GetDecl(ExternalDefinitions[I]);
1508 DeclGroupRef DG(D);
1509 Consumer->HandleTopLevelDecl(DG);
1510 }
1511}
1512
Douglas Gregorc34897d2009-04-09 22:27:44 +00001513void PCHReader::PrintStats() {
1514 std::fprintf(stderr, "*** PCH Statistics:\n");
1515
1516 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1517 TypeAlreadyLoaded.end(),
1518 true);
1519 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1520 DeclAlreadyLoaded.end(),
1521 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001522 unsigned NumIdentifiersLoaded = 0;
1523 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1524 if ((IdentifierData[I] & 0x01) == 0)
1525 ++NumIdentifiersLoaded;
1526 }
1527
Douglas Gregorc34897d2009-04-09 22:27:44 +00001528 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1529 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001530 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001531 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1532 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001533 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1534 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1535 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1536 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001537 std::fprintf(stderr, "\n");
1538}
1539
Chris Lattner29241862009-04-11 21:15:38 +00001540IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001541 if (ID == 0)
1542 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001543
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001544 if (!IdentifierTable || IdentifierData.empty()) {
1545 Error("No identifier table in PCH file");
1546 return 0;
1547 }
Chris Lattner29241862009-04-11 21:15:38 +00001548
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001549 if (IdentifierData[ID - 1] & 0x01) {
1550 uint64_t Offset = IdentifierData[ID - 1];
1551 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001552 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001553 }
Chris Lattner29241862009-04-11 21:15:38 +00001554
1555 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001556}
1557
1558DeclarationName
1559PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1560 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1561 switch (Kind) {
1562 case DeclarationName::Identifier:
1563 return DeclarationName(GetIdentifierInfo(Record, Idx));
1564
1565 case DeclarationName::ObjCZeroArgSelector:
1566 case DeclarationName::ObjCOneArgSelector:
1567 case DeclarationName::ObjCMultiArgSelector:
1568 assert(false && "Unable to de-serialize Objective-C selectors");
1569 break;
1570
1571 case DeclarationName::CXXConstructorName:
1572 return Context.DeclarationNames.getCXXConstructorName(
1573 GetType(Record[Idx++]));
1574
1575 case DeclarationName::CXXDestructorName:
1576 return Context.DeclarationNames.getCXXDestructorName(
1577 GetType(Record[Idx++]));
1578
1579 case DeclarationName::CXXConversionFunctionName:
1580 return Context.DeclarationNames.getCXXConversionFunctionName(
1581 GetType(Record[Idx++]));
1582
1583 case DeclarationName::CXXOperatorName:
1584 return Context.DeclarationNames.getCXXOperatorName(
1585 (OverloadedOperatorKind)Record[Idx++]);
1586
1587 case DeclarationName::CXXUsingDirective:
1588 return DeclarationName::getUsingDirectiveName();
1589 }
1590
1591 // Required to silence GCC warning
1592 return DeclarationName();
1593}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001594
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001595/// \brief Read an integral value
1596llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1597 unsigned BitWidth = Record[Idx++];
1598 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1599 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1600 Idx += NumWords;
1601 return Result;
1602}
1603
1604/// \brief Read a signed integral value
1605llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1606 bool isUnsigned = Record[Idx++];
1607 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1608}
1609
Douglas Gregore2f37202009-04-14 21:55:33 +00001610/// \brief Read a floating-point value
1611llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1612 // FIXME: is this really correct?
1613 return llvm::APFloat(ReadAPInt(Record, Idx));
1614}
1615
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001616Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001617 // Within the bitstream, expressions are stored in Reverse Polish
1618 // Notation, with each of the subexpressions preceding the
1619 // expression they are stored in. To evaluate expressions, we
1620 // continue reading expressions and placing them on the stack, with
1621 // expressions having operands removing those operands from the
1622 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1623 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001624 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001625 unsigned Idx;
1626 llvm::SmallVector<Expr *, 16> ExprStack;
1627 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001628 Stmt::EmptyShell Empty;
1629
Douglas Gregora151ba42009-04-14 23:32:43 +00001630 while (true) {
1631 unsigned Code = Stream.ReadCode();
1632 if (Code == llvm::bitc::END_BLOCK) {
1633 if (Stream.ReadBlockEnd()) {
1634 Error("Error at end of Source Manager block");
1635 return 0;
1636 }
1637 break;
1638 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001639
Douglas Gregora151ba42009-04-14 23:32:43 +00001640 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1641 // No known subblocks, always skip them.
1642 Stream.ReadSubBlockID();
1643 if (Stream.SkipBlock()) {
1644 Error("Malformed block record");
1645 return 0;
1646 }
1647 continue;
1648 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001649
Douglas Gregora151ba42009-04-14 23:32:43 +00001650 if (Code == llvm::bitc::DEFINE_ABBREV) {
1651 Stream.ReadAbbrevRecord();
1652 continue;
1653 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001654
Douglas Gregora151ba42009-04-14 23:32:43 +00001655 Expr *E = 0;
1656 Idx = 0;
1657 Record.clear();
1658 bool Finished = false;
1659 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1660 case pch::EXPR_STOP:
1661 Finished = true;
1662 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001663
Douglas Gregora151ba42009-04-14 23:32:43 +00001664 case pch::EXPR_NULL:
1665 E = 0;
1666 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001667
Douglas Gregora151ba42009-04-14 23:32:43 +00001668 case pch::EXPR_PREDEFINED:
1669 // FIXME: untested (until we can serialize function bodies).
1670 E = new (Context) PredefinedExpr(Empty);
1671 break;
1672
1673 case pch::EXPR_DECL_REF:
1674 E = new (Context) DeclRefExpr(Empty);
1675 break;
1676
1677 case pch::EXPR_INTEGER_LITERAL:
1678 E = new (Context) IntegerLiteral(Empty);
1679 break;
1680
1681 case pch::EXPR_FLOATING_LITERAL:
1682 E = new (Context) FloatingLiteral(Empty);
1683 break;
1684
Douglas Gregor596e0932009-04-15 16:35:07 +00001685 case pch::EXPR_STRING_LITERAL:
1686 E = StringLiteral::CreateEmpty(Context,
1687 Record[PCHStmtReader::NumExprFields + 1]);
1688 break;
1689
Douglas Gregora151ba42009-04-14 23:32:43 +00001690 case pch::EXPR_CHARACTER_LITERAL:
1691 E = new (Context) CharacterLiteral(Empty);
1692 break;
1693
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001694 case pch::EXPR_PAREN:
1695 E = new (Context) ParenExpr(Empty);
1696 break;
1697
Douglas Gregor12d74052009-04-15 15:58:59 +00001698 case pch::EXPR_UNARY_OPERATOR:
1699 E = new (Context) UnaryOperator(Empty);
1700 break;
1701
1702 case pch::EXPR_SIZEOF_ALIGN_OF:
1703 E = new (Context) SizeOfAlignOfExpr(Empty);
1704 break;
1705
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001706 case pch::EXPR_BINARY_OPERATOR:
1707 E = new (Context) BinaryOperator(Empty);
1708 break;
1709
Douglas Gregora151ba42009-04-14 23:32:43 +00001710 case pch::EXPR_IMPLICIT_CAST:
1711 E = new (Context) ImplicitCastExpr(Empty);
1712 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001713
1714 case pch::EXPR_CSTYLE_CAST:
1715 E = new (Context) CStyleCastExpr(Empty);
1716 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001717 }
1718
1719 // We hit an EXPR_STOP, so we're done with this expression.
1720 if (Finished)
1721 break;
1722
1723 if (E) {
1724 unsigned NumSubExprs = Reader.Visit(E);
1725 while (NumSubExprs > 0) {
1726 ExprStack.pop_back();
1727 --NumSubExprs;
1728 }
1729 }
1730
1731 assert(Idx == Record.size() && "Invalid deserialization of expression");
1732 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001733 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001734 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1735 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001736}
1737
Douglas Gregor179cfb12009-04-10 20:39:37 +00001738DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001739 return Diag(SourceLocation(), DiagID);
1740}
1741
1742DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1743 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001744 Context.getSourceManager()),
1745 DiagID);
1746}