blob: 0bc059ed66499efaff843a2d1450e8b9f57e6dc9 [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++]);
Douglas Gregor1c507882009-04-15 21:30:51 +000077 if (Record[Idx++])
78 D->addAttr(Reader.ReadAttributes());
Douglas Gregorc34897d2009-04-09 22:27:44 +000079 D->setImplicit(Record[Idx++]);
80 D->setAccess((AccessSpecifier)Record[Idx++]);
81}
82
83void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
84 VisitDecl(TU);
85}
86
87void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
88 VisitDecl(ND);
89 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
90}
91
92void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
93 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000094 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
95}
96
97void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000098 // Note that we cannot use VisitTypeDecl here, because we need to
99 // set the underlying type of the typedef *before* we try to read
100 // the type associated with the TypedefDecl.
101 VisitNamedDecl(TD);
102 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
103 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
104 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000105}
106
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000107void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
108 VisitTypeDecl(TD);
109 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
110 TD->setDefinition(Record[Idx++]);
111 TD->setTypedefForAnonDecl(
112 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
113}
114
115void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
116 VisitTagDecl(ED);
117 ED->setIntegerType(Reader.GetType(Record[Idx++]));
118}
119
Douglas Gregor982365e2009-04-13 21:20:57 +0000120void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
121 VisitTagDecl(RD);
122 RD->setHasFlexibleArrayMember(Record[Idx++]);
123 RD->setAnonymousStructOrUnion(Record[Idx++]);
124}
125
Douglas Gregorc34897d2009-04-09 22:27:44 +0000126void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
127 VisitNamedDecl(VD);
128 VD->setType(Reader.GetType(Record[Idx++]));
129}
130
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000131void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
132 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000133 if (Record[Idx++])
134 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000135 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
136}
137
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000138void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
139 VisitValueDecl(FD);
140 // FIXME: function body
141 FD->setPreviousDeclaration(
142 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
143 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
144 FD->setInline(Record[Idx++]);
145 FD->setVirtual(Record[Idx++]);
146 FD->setPure(Record[Idx++]);
147 FD->setInheritedPrototype(Record[Idx++]);
148 FD->setHasPrototype(Record[Idx++]);
149 FD->setDeleted(Record[Idx++]);
150 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
151 unsigned NumParams = Record[Idx++];
152 llvm::SmallVector<ParmVarDecl *, 16> Params;
153 Params.reserve(NumParams);
154 for (unsigned I = 0; I != NumParams; ++I)
155 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
156 FD->setParams(Reader.getContext(), &Params[0], NumParams);
157}
158
Douglas Gregor982365e2009-04-13 21:20:57 +0000159void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
160 VisitValueDecl(FD);
161 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000162 if (Record[Idx++])
163 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000164}
165
Douglas Gregorc34897d2009-04-09 22:27:44 +0000166void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
167 VisitValueDecl(VD);
168 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
169 VD->setThreadSpecified(Record[Idx++]);
170 VD->setCXXDirectInitializer(Record[Idx++]);
171 VD->setDeclaredInCondition(Record[Idx++]);
172 VD->setPreviousDeclaration(
173 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
174 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000175 if (Record[Idx++])
176 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000177}
178
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000179void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
180 VisitVarDecl(PD);
181 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000182 // FIXME: default argument (C++ only)
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000183}
184
185void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
186 VisitParmVarDecl(PD);
187 PD->setOriginalType(Reader.GetType(Record[Idx++]));
188}
189
Douglas Gregor2a491792009-04-13 22:49:25 +0000190void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
191 VisitDecl(AD);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000192 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000193}
194
195void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
196 VisitDecl(BD);
197 unsigned NumParams = Record[Idx++];
198 llvm::SmallVector<ParmVarDecl *, 16> Params;
199 Params.reserve(NumParams);
200 for (unsigned I = 0; I != NumParams; ++I)
201 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
202 BD->setParams(Reader.getContext(), &Params[0], NumParams);
203}
204
Douglas Gregorc34897d2009-04-09 22:27:44 +0000205std::pair<uint64_t, uint64_t>
206PCHDeclReader::VisitDeclContext(DeclContext *DC) {
207 uint64_t LexicalOffset = Record[Idx++];
208 uint64_t VisibleOffset = 0;
209 if (DC->getPrimaryContext() == DC)
210 VisibleOffset = Record[Idx++];
211 return std::make_pair(LexicalOffset, VisibleOffset);
212}
213
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000214//===----------------------------------------------------------------------===//
215// Statement/expression deserialization
216//===----------------------------------------------------------------------===//
217namespace {
218 class VISIBILITY_HIDDEN PCHStmtReader
Douglas Gregora151ba42009-04-14 23:32:43 +0000219 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000220 PCHReader &Reader;
221 const PCHReader::RecordData &Record;
222 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000223 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000224
225 public:
226 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000227 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
228 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000229
Douglas Gregor596e0932009-04-15 16:35:07 +0000230 /// \brief The number of record fields required for the Expr class
231 /// itself.
232 static const unsigned NumExprFields = 3;
233
Douglas Gregora151ba42009-04-14 23:32:43 +0000234 // Each of the Visit* functions reads in part of the expression
235 // from the given record and the current expression stack, then
236 // return the total number of operands that it read from the
237 // expression stack.
238
239 unsigned VisitExpr(Expr *E);
240 unsigned VisitPredefinedExpr(PredefinedExpr *E);
241 unsigned VisitDeclRefExpr(DeclRefExpr *E);
242 unsigned VisitIntegerLiteral(IntegerLiteral *E);
243 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000244 unsigned VisitImaginaryLiteral(ImaginaryLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000245 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000246 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000247 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000248 unsigned VisitUnaryOperator(UnaryOperator *E);
249 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000250 unsigned VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000251 unsigned VisitCallExpr(CallExpr *E);
252 unsigned VisitMemberExpr(MemberExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000253 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000254 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregorc599bbf2009-04-15 22:40:36 +0000255 unsigned VisitCompoundAssignOperator(CompoundAssignOperator *E);
256 unsigned VisitConditionalOperator(ConditionalOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000257 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000258 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
259 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorb70b48f2009-04-16 02:33:48 +0000260 unsigned VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Douglas Gregorec0b8292009-04-15 23:02:49 +0000261 unsigned VisitExtVectorElementExpr(ExtVectorElementExpr *E);
Douglas Gregor6710a3c2009-04-16 00:55:48 +0000262 unsigned VisitInitListExpr(InitListExpr *E);
263 unsigned VisitDesignatedInitExpr(DesignatedInitExpr *E);
264 unsigned VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Douglas Gregorec0b8292009-04-15 23:02:49 +0000265 unsigned VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor209d4622009-04-15 23:33:31 +0000266 unsigned VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
267 unsigned VisitChooseExpr(ChooseExpr *E);
268 unsigned VisitGNUNullExpr(GNUNullExpr *E);
Douglas Gregor725e94b2009-04-16 00:01:45 +0000269 unsigned VisitShuffleVectorExpr(ShuffleVectorExpr *E);
270 unsigned VisitBlockDeclRefExpr(BlockDeclRefExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000271 };
272}
273
Douglas Gregora151ba42009-04-14 23:32:43 +0000274unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000275 E->setType(Reader.GetType(Record[Idx++]));
276 E->setTypeDependent(Record[Idx++]);
277 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000278 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000279 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000280}
281
Douglas Gregora151ba42009-04-14 23:32:43 +0000282unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000283 VisitExpr(E);
284 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
285 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000286 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000287}
288
Douglas Gregora151ba42009-04-14 23:32:43 +0000289unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000290 VisitExpr(E);
291 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
292 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000293 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000294}
295
Douglas Gregora151ba42009-04-14 23:32:43 +0000296unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000297 VisitExpr(E);
298 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
299 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000300 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000301}
302
Douglas Gregora151ba42009-04-14 23:32:43 +0000303unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000304 VisitExpr(E);
305 E->setValue(Reader.ReadAPFloat(Record, Idx));
306 E->setExact(Record[Idx++]);
307 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000308 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000309}
310
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000311unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) {
312 VisitExpr(E);
313 E->setSubExpr(ExprStack.back());
314 return 1;
315}
316
Douglas Gregor596e0932009-04-15 16:35:07 +0000317unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
318 VisitExpr(E);
319 unsigned Len = Record[Idx++];
320 assert(Record[Idx] == E->getNumConcatenated() &&
321 "Wrong number of concatenated tokens!");
322 ++Idx;
323 E->setWide(Record[Idx++]);
324
325 // Read string data
326 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
327 E->setStrData(Reader.getContext(), &Str[0], Len);
328 Idx += Len;
329
330 // Read source locations
331 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
332 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
333
334 return 0;
335}
336
Douglas Gregora151ba42009-04-14 23:32:43 +0000337unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000338 VisitExpr(E);
339 E->setValue(Record[Idx++]);
340 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
341 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000342 return 0;
343}
344
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000345unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
346 VisitExpr(E);
347 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
348 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
349 E->setSubExpr(ExprStack.back());
350 return 1;
351}
352
Douglas Gregor12d74052009-04-15 15:58:59 +0000353unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
354 VisitExpr(E);
355 E->setSubExpr(ExprStack.back());
356 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
357 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
358 return 1;
359}
360
361unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
362 VisitExpr(E);
363 E->setSizeof(Record[Idx++]);
364 if (Record[Idx] == 0) {
365 E->setArgument(ExprStack.back());
366 ++Idx;
367 } else {
368 E->setArgument(Reader.GetType(Record[Idx++]));
369 }
370 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
371 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
372 return E->isArgumentType()? 0 : 1;
373}
374
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000375unsigned PCHStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
376 VisitExpr(E);
377 E->setLHS(ExprStack[ExprStack.size() - 2]);
378 E->setRHS(ExprStack[ExprStack.size() - 2]);
379 E->setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
380 return 2;
381}
382
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000383unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
384 VisitExpr(E);
385 E->setNumArgs(Reader.getContext(), Record[Idx++]);
386 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
387 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
388 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
389 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
390 return E->getNumArgs() + 1;
391}
392
393unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
394 VisitExpr(E);
395 E->setBase(ExprStack.back());
396 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
397 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
398 E->setArrow(Record[Idx++]);
399 return 1;
400}
401
Douglas Gregora151ba42009-04-14 23:32:43 +0000402unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
403 VisitExpr(E);
404 E->setSubExpr(ExprStack.back());
405 return 1;
406}
407
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000408unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
409 VisitExpr(E);
410 E->setLHS(ExprStack.end()[-2]);
411 E->setRHS(ExprStack.end()[-1]);
412 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
413 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
414 return 2;
415}
416
Douglas Gregorc599bbf2009-04-15 22:40:36 +0000417unsigned PCHStmtReader::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
418 VisitBinaryOperator(E);
419 E->setComputationLHSType(Reader.GetType(Record[Idx++]));
420 E->setComputationResultType(Reader.GetType(Record[Idx++]));
421 return 2;
422}
423
424unsigned PCHStmtReader::VisitConditionalOperator(ConditionalOperator *E) {
425 VisitExpr(E);
426 E->setCond(ExprStack[ExprStack.size() - 3]);
427 E->setLHS(ExprStack[ExprStack.size() - 2]);
428 E->setRHS(ExprStack[ExprStack.size() - 1]);
429 return 3;
430}
431
Douglas Gregora151ba42009-04-14 23:32:43 +0000432unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
433 VisitCastExpr(E);
434 E->setLvalueCast(Record[Idx++]);
435 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000436}
437
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000438unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
439 VisitCastExpr(E);
440 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
441 return 1;
442}
443
444unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
445 VisitExplicitCastExpr(E);
446 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
447 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
448 return 1;
449}
450
Douglas Gregorb70b48f2009-04-16 02:33:48 +0000451unsigned PCHStmtReader::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
452 VisitExpr(E);
453 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
454 E->setInitializer(ExprStack.back());
455 E->setFileScope(Record[Idx++]);
456 return 1;
457}
458
Douglas Gregorec0b8292009-04-15 23:02:49 +0000459unsigned PCHStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) {
460 VisitExpr(E);
461 E->setBase(ExprStack.back());
462 E->setAccessor(Reader.GetIdentifierInfo(Record, Idx));
463 E->setAccessorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
464 return 1;
465}
466
Douglas Gregor6710a3c2009-04-16 00:55:48 +0000467unsigned PCHStmtReader::VisitInitListExpr(InitListExpr *E) {
468 VisitExpr(E);
469 unsigned NumInits = Record[Idx++];
470 E->reserveInits(NumInits);
471 for (unsigned I = 0; I != NumInits; ++I)
472 E->updateInit(I, ExprStack[ExprStack.size() - NumInits - 1 + I]);
473 E->setSyntacticForm(cast_or_null<InitListExpr>(ExprStack.back()));
474 E->setLBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
475 E->setRBraceLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
476 E->setInitializedFieldInUnion(
477 cast_or_null<FieldDecl>(Reader.GetDecl(Record[Idx++])));
478 E->sawArrayRangeDesignator(Record[Idx++]);
479 return NumInits + 1;
480}
481
482unsigned PCHStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
483 typedef DesignatedInitExpr::Designator Designator;
484
485 VisitExpr(E);
486 unsigned NumSubExprs = Record[Idx++];
487 assert(NumSubExprs == E->getNumSubExprs() && "Wrong number of subexprs");
488 for (unsigned I = 0; I != NumSubExprs; ++I)
489 E->setSubExpr(I, ExprStack[ExprStack.size() - NumSubExprs + I]);
490 E->setEqualOrColonLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
491 E->setGNUSyntax(Record[Idx++]);
492
493 llvm::SmallVector<Designator, 4> Designators;
494 while (Idx < Record.size()) {
495 switch ((pch::DesignatorTypes)Record[Idx++]) {
496 case pch::DESIG_FIELD_DECL: {
497 FieldDecl *Field = cast<FieldDecl>(Reader.GetDecl(Record[Idx++]));
498 SourceLocation DotLoc
499 = SourceLocation::getFromRawEncoding(Record[Idx++]);
500 SourceLocation FieldLoc
501 = SourceLocation::getFromRawEncoding(Record[Idx++]);
502 Designators.push_back(Designator(Field->getIdentifier(), DotLoc,
503 FieldLoc));
504 Designators.back().setField(Field);
505 break;
506 }
507
508 case pch::DESIG_FIELD_NAME: {
509 const IdentifierInfo *Name = Reader.GetIdentifierInfo(Record, Idx);
510 SourceLocation DotLoc
511 = SourceLocation::getFromRawEncoding(Record[Idx++]);
512 SourceLocation FieldLoc
513 = SourceLocation::getFromRawEncoding(Record[Idx++]);
514 Designators.push_back(Designator(Name, DotLoc, FieldLoc));
515 break;
516 }
517
518 case pch::DESIG_ARRAY: {
519 unsigned Index = Record[Idx++];
520 SourceLocation LBracketLoc
521 = SourceLocation::getFromRawEncoding(Record[Idx++]);
522 SourceLocation RBracketLoc
523 = SourceLocation::getFromRawEncoding(Record[Idx++]);
524 Designators.push_back(Designator(Index, LBracketLoc, RBracketLoc));
525 break;
526 }
527
528 case pch::DESIG_ARRAY_RANGE: {
529 unsigned Index = Record[Idx++];
530 SourceLocation LBracketLoc
531 = SourceLocation::getFromRawEncoding(Record[Idx++]);
532 SourceLocation EllipsisLoc
533 = SourceLocation::getFromRawEncoding(Record[Idx++]);
534 SourceLocation RBracketLoc
535 = SourceLocation::getFromRawEncoding(Record[Idx++]);
536 Designators.push_back(Designator(Index, LBracketLoc, EllipsisLoc,
537 RBracketLoc));
538 break;
539 }
540 }
541 }
542 E->setDesignators(&Designators[0], Designators.size());
543
544 return NumSubExprs;
545}
546
547unsigned PCHStmtReader::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
548 VisitExpr(E);
549 return 0;
550}
551
Douglas Gregorec0b8292009-04-15 23:02:49 +0000552unsigned PCHStmtReader::VisitVAArgExpr(VAArgExpr *E) {
553 VisitExpr(E);
554 E->setSubExpr(ExprStack.back());
555 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
556 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
557 return 1;
558}
559
Douglas Gregor209d4622009-04-15 23:33:31 +0000560unsigned PCHStmtReader::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
561 VisitExpr(E);
562 E->setArgType1(Reader.GetType(Record[Idx++]));
563 E->setArgType2(Reader.GetType(Record[Idx++]));
564 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
565 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
566 return 0;
567}
568
569unsigned PCHStmtReader::VisitChooseExpr(ChooseExpr *E) {
570 VisitExpr(E);
571 E->setCond(ExprStack[ExprStack.size() - 3]);
572 E->setLHS(ExprStack[ExprStack.size() - 2]);
573 E->setRHS(ExprStack[ExprStack.size() - 1]);
574 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
575 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
576 return 3;
577}
578
579unsigned PCHStmtReader::VisitGNUNullExpr(GNUNullExpr *E) {
580 VisitExpr(E);
581 E->setTokenLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
582 return 0;
583}
Douglas Gregorec0b8292009-04-15 23:02:49 +0000584
Douglas Gregor725e94b2009-04-16 00:01:45 +0000585unsigned PCHStmtReader::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
586 VisitExpr(E);
587 unsigned NumExprs = Record[Idx++];
588 E->setExprs(&ExprStack[ExprStack.size() - NumExprs], NumExprs);
589 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
590 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
591 return NumExprs;
592}
593
594unsigned PCHStmtReader::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
595 VisitExpr(E);
596 E->setDecl(cast<ValueDecl>(Reader.GetDecl(Record[Idx++])));
597 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
598 E->setByRef(Record[Idx++]);
599 return 0;
600}
601
Douglas Gregorc34897d2009-04-09 22:27:44 +0000602// FIXME: use the diagnostics machinery
603static bool Error(const char *Str) {
604 std::fprintf(stderr, "%s\n", Str);
605 return true;
606}
607
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000608/// \brief Check the contents of the predefines buffer against the
609/// contents of the predefines buffer used to build the PCH file.
610///
611/// The contents of the two predefines buffers should be the same. If
612/// not, then some command-line option changed the preprocessor state
613/// and we must reject the PCH file.
614///
615/// \param PCHPredef The start of the predefines buffer in the PCH
616/// file.
617///
618/// \param PCHPredefLen The length of the predefines buffer in the PCH
619/// file.
620///
621/// \param PCHBufferID The FileID for the PCH predefines buffer.
622///
623/// \returns true if there was a mismatch (in which case the PCH file
624/// should be ignored), or false otherwise.
625bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
626 unsigned PCHPredefLen,
627 FileID PCHBufferID) {
628 const char *Predef = PP.getPredefines().c_str();
629 unsigned PredefLen = PP.getPredefines().size();
630
631 // If the two predefines buffers compare equal, we're done!.
632 if (PredefLen == PCHPredefLen &&
633 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
634 return false;
635
636 // The predefines buffers are different. Produce a reasonable
637 // diagnostic showing where they are different.
638
639 // The source locations (potentially in the two different predefines
640 // buffers)
641 SourceLocation Loc1, Loc2;
642 SourceManager &SourceMgr = PP.getSourceManager();
643
644 // Create a source buffer for our predefines string, so
645 // that we can build a diagnostic that points into that
646 // source buffer.
647 FileID BufferID;
648 if (Predef && Predef[0]) {
649 llvm::MemoryBuffer *Buffer
650 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
651 "<built-in>");
652 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
653 }
654
655 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
656 std::pair<const char *, const char *> Locations
657 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
658
659 if (Locations.first != Predef + MinLen) {
660 // We found the location in the two buffers where there is a
661 // difference. Form source locations to point there (in both
662 // buffers).
663 unsigned Offset = Locations.first - Predef;
664 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
665 .getFileLocWithOffset(Offset);
666 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
667 .getFileLocWithOffset(Offset);
668 } else if (PredefLen > PCHPredefLen) {
669 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
670 .getFileLocWithOffset(MinLen);
671 } else {
672 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
673 .getFileLocWithOffset(MinLen);
674 }
675
676 Diag(Loc1, diag::warn_pch_preprocessor);
677 if (Loc2.isValid())
678 Diag(Loc2, diag::note_predef_in_pch);
679 Diag(diag::note_ignoring_pch) << FileName;
680 return true;
681}
682
Douglas Gregor635f97f2009-04-13 16:31:14 +0000683/// \brief Read the line table in the source manager block.
684/// \returns true if ther was an error.
685static bool ParseLineTable(SourceManager &SourceMgr,
686 llvm::SmallVectorImpl<uint64_t> &Record) {
687 unsigned Idx = 0;
688 LineTableInfo &LineTable = SourceMgr.getLineTable();
689
690 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000691 std::map<int, int> FileIDs;
692 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000693 // Extract the file name
694 unsigned FilenameLen = Record[Idx++];
695 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
696 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000697 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
698 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000699 }
700
701 // Parse the line entries
702 std::vector<LineEntry> Entries;
703 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000704 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000705
706 // Extract the line entries
707 unsigned NumEntries = Record[Idx++];
708 Entries.clear();
709 Entries.reserve(NumEntries);
710 for (unsigned I = 0; I != NumEntries; ++I) {
711 unsigned FileOffset = Record[Idx++];
712 unsigned LineNo = Record[Idx++];
713 int FilenameID = Record[Idx++];
714 SrcMgr::CharacteristicKind FileKind
715 = (SrcMgr::CharacteristicKind)Record[Idx++];
716 unsigned IncludeOffset = Record[Idx++];
717 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
718 FileKind, IncludeOffset));
719 }
720 LineTable.AddEntry(FID, Entries);
721 }
722
723 return false;
724}
725
Douglas Gregorab1cef72009-04-10 03:52:48 +0000726/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000727PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000728 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000729 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
730 Error("Malformed source manager block record");
731 return Failure;
732 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000733
734 SourceManager &SourceMgr = Context.getSourceManager();
735 RecordData Record;
736 while (true) {
737 unsigned Code = Stream.ReadCode();
738 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000739 if (Stream.ReadBlockEnd()) {
740 Error("Error at end of Source Manager block");
741 return Failure;
742 }
743
744 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000745 }
746
747 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
748 // No known subblocks, always skip them.
749 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000750 if (Stream.SkipBlock()) {
751 Error("Malformed block record");
752 return Failure;
753 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000754 continue;
755 }
756
757 if (Code == llvm::bitc::DEFINE_ABBREV) {
758 Stream.ReadAbbrevRecord();
759 continue;
760 }
761
762 // Read a record.
763 const char *BlobStart;
764 unsigned BlobLen;
765 Record.clear();
766 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
767 default: // Default behavior: ignore.
768 break;
769
770 case pch::SM_SLOC_FILE_ENTRY: {
771 // FIXME: We would really like to delay the creation of this
772 // FileEntry until it is actually required, e.g., when producing
773 // a diagnostic with a source location in this file.
774 const FileEntry *File
775 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
776 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000777 FileID ID = SourceMgr.createFileID(File,
778 SourceLocation::getFromRawEncoding(Record[1]),
779 (CharacteristicKind)Record[2]);
780 if (Record[3])
781 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
782 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000783 break;
784 }
785
786 case pch::SM_SLOC_BUFFER_ENTRY: {
787 const char *Name = BlobStart;
788 unsigned Code = Stream.ReadCode();
789 Record.clear();
790 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
791 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000792 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000793 llvm::MemoryBuffer *Buffer
794 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
795 BlobStart + BlobLen - 1,
796 Name);
797 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
798
799 if (strcmp(Name, "<built-in>") == 0
800 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
801 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000802 break;
803 }
804
805 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
806 SourceLocation SpellingLoc
807 = SourceLocation::getFromRawEncoding(Record[1]);
808 SourceMgr.createInstantiationLoc(
809 SpellingLoc,
810 SourceLocation::getFromRawEncoding(Record[2]),
811 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000812 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000813 break;
814 }
815
Chris Lattnere1be6022009-04-14 23:22:57 +0000816 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000817 if (ParseLineTable(SourceMgr, Record))
818 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000819 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000820 }
821 }
822}
823
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000824bool PCHReader::ReadPreprocessorBlock() {
825 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
826 return Error("Malformed preprocessor block record");
827
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000828 RecordData Record;
829 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
830 MacroInfo *LastMacro = 0;
831
832 while (true) {
833 unsigned Code = Stream.ReadCode();
834 switch (Code) {
835 case llvm::bitc::END_BLOCK:
836 if (Stream.ReadBlockEnd())
837 return Error("Error at end of preprocessor block");
838 return false;
839
840 case llvm::bitc::ENTER_SUBBLOCK:
841 // No known subblocks, always skip them.
842 Stream.ReadSubBlockID();
843 if (Stream.SkipBlock())
844 return Error("Malformed block record");
845 continue;
846
847 case llvm::bitc::DEFINE_ABBREV:
848 Stream.ReadAbbrevRecord();
849 continue;
850 default: break;
851 }
852
853 // Read a record.
854 Record.clear();
855 pch::PreprocessorRecordTypes RecType =
856 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
857 switch (RecType) {
858 default: // Default behavior: ignore unknown records.
859 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000860 case pch::PP_COUNTER_VALUE:
861 if (!Record.empty())
862 PP.setCounterValue(Record[0]);
863 break;
864
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000865 case pch::PP_MACRO_OBJECT_LIKE:
866 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000867 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
868 if (II == 0)
869 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000870 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
871 bool isUsed = Record[2];
872
873 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
874 MI->setIsUsed(isUsed);
875
876 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
877 // Decode function-like macro info.
878 bool isC99VarArgs = Record[3];
879 bool isGNUVarArgs = Record[4];
880 MacroArgs.clear();
881 unsigned NumArgs = Record[5];
882 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000883 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000884
885 // Install function-like macro info.
886 MI->setIsFunctionLike();
887 if (isC99VarArgs) MI->setIsC99Varargs();
888 if (isGNUVarArgs) MI->setIsGNUVarargs();
889 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
890 PP.getPreprocessorAllocator());
891 }
892
893 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000894 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000895
896 // Remember that we saw this macro last so that we add the tokens that
897 // form its body to it.
898 LastMacro = MI;
899 break;
900 }
901
902 case pch::PP_TOKEN: {
903 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
904 // pretend we didn't see this.
905 if (LastMacro == 0) break;
906
907 Token Tok;
908 Tok.startToken();
909 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
910 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000911 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
912 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000913 Tok.setKind((tok::TokenKind)Record[3]);
914 Tok.setFlag((Token::TokenFlags)Record[4]);
915 LastMacro->AddTokenToBody(Tok);
916 break;
917 }
918 }
919 }
920}
921
Douglas Gregor179cfb12009-04-10 20:39:37 +0000922PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
923 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
924 Error("Malformed block record");
925 return Failure;
926 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000927
Chris Lattner29241862009-04-11 21:15:38 +0000928 uint64_t PreprocessorBlockBit = 0;
929
Douglas Gregorc34897d2009-04-09 22:27:44 +0000930 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000931 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000932 while (!Stream.AtEndOfStream()) {
933 unsigned Code = Stream.ReadCode();
934 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000935 // If we saw the preprocessor block, read it now.
936 if (PreprocessorBlockBit) {
937 uint64_t SavedPos = Stream.GetCurrentBitNo();
938 Stream.JumpToBit(PreprocessorBlockBit);
939 if (ReadPreprocessorBlock()) {
940 Error("Malformed preprocessor block");
941 return Failure;
942 }
943 Stream.JumpToBit(SavedPos);
944 }
945
Douglas Gregor179cfb12009-04-10 20:39:37 +0000946 if (Stream.ReadBlockEnd()) {
947 Error("Error at end of module block");
948 return Failure;
949 }
Chris Lattner29241862009-04-11 21:15:38 +0000950
Douglas Gregor179cfb12009-04-10 20:39:37 +0000951 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000952 }
953
954 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
955 switch (Stream.ReadSubBlockID()) {
956 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
957 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
958 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000959 if (Stream.SkipBlock()) {
960 Error("Malformed block record");
961 return Failure;
962 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000963 break;
964
Chris Lattner29241862009-04-11 21:15:38 +0000965 case pch::PREPROCESSOR_BLOCK_ID:
966 // Skip the preprocessor block for now, but remember where it is. We
967 // want to read it in after the identifier table.
968 if (PreprocessorBlockBit) {
969 Error("Multiple preprocessor blocks found.");
970 return Failure;
971 }
972 PreprocessorBlockBit = Stream.GetCurrentBitNo();
973 if (Stream.SkipBlock()) {
974 Error("Malformed block record");
975 return Failure;
976 }
977 break;
978
Douglas Gregorab1cef72009-04-10 03:52:48 +0000979 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000980 switch (ReadSourceManagerBlock()) {
981 case Success:
982 break;
983
984 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000985 Error("Malformed source manager block");
986 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000987
988 case IgnorePCH:
989 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000990 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000991 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000992 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000993 continue;
994 }
995
996 if (Code == llvm::bitc::DEFINE_ABBREV) {
997 Stream.ReadAbbrevRecord();
998 continue;
999 }
1000
1001 // Read and process a record.
1002 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +00001003 const char *BlobStart = 0;
1004 unsigned BlobLen = 0;
1005 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1006 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001007 default: // Default behavior: ignore.
1008 break;
1009
1010 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001011 if (!TypeOffsets.empty()) {
1012 Error("Duplicate TYPE_OFFSET record in PCH file");
1013 return Failure;
1014 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001015 TypeOffsets.swap(Record);
1016 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
1017 break;
1018
1019 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001020 if (!DeclOffsets.empty()) {
1021 Error("Duplicate DECL_OFFSET record in PCH file");
1022 return Failure;
1023 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001024 DeclOffsets.swap(Record);
1025 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
1026 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001027
1028 case pch::LANGUAGE_OPTIONS:
1029 if (ParseLanguageOptions(Record))
1030 return IgnorePCH;
1031 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001032
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001033 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +00001034 std::string TargetTriple(BlobStart, BlobLen);
1035 if (TargetTriple != Context.Target.getTargetTriple()) {
1036 Diag(diag::warn_pch_target_triple)
1037 << TargetTriple << Context.Target.getTargetTriple();
1038 Diag(diag::note_ignoring_pch) << FileName;
1039 return IgnorePCH;
1040 }
1041 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001042 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001043
1044 case pch::IDENTIFIER_TABLE:
1045 IdentifierTable = BlobStart;
1046 break;
1047
1048 case pch::IDENTIFIER_OFFSET:
1049 if (!IdentifierData.empty()) {
1050 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1051 return Failure;
1052 }
1053 IdentifierData.swap(Record);
1054#ifndef NDEBUG
1055 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
1056 if ((IdentifierData[I] & 0x01) == 0) {
1057 Error("Malformed identifier table in the precompiled header");
1058 return Failure;
1059 }
1060 }
1061#endif
1062 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001063
1064 case pch::EXTERNAL_DEFINITIONS:
1065 if (!ExternalDefinitions.empty()) {
1066 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1067 return Failure;
1068 }
1069 ExternalDefinitions.swap(Record);
1070 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001071 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001072 }
1073
Douglas Gregor179cfb12009-04-10 20:39:37 +00001074 Error("Premature end of bitstream");
1075 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001076}
1077
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001078PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001079 // Set the PCH file name.
1080 this->FileName = FileName;
1081
Douglas Gregorc34897d2009-04-09 22:27:44 +00001082 // Open the PCH file.
1083 std::string ErrStr;
1084 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001085 if (!Buffer) {
1086 Error(ErrStr.c_str());
1087 return IgnorePCH;
1088 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001089
1090 // Initialize the stream
1091 Stream.init((const unsigned char *)Buffer->getBufferStart(),
1092 (const unsigned char *)Buffer->getBufferEnd());
1093
1094 // Sniff for the signature.
1095 if (Stream.Read(8) != 'C' ||
1096 Stream.Read(8) != 'P' ||
1097 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001098 Stream.Read(8) != 'H') {
1099 Error("Not a PCH file");
1100 return IgnorePCH;
1101 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001102
1103 // We expect a number of well-defined blocks, though we don't necessarily
1104 // need to understand them all.
1105 while (!Stream.AtEndOfStream()) {
1106 unsigned Code = Stream.ReadCode();
1107
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001108 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1109 Error("Invalid record at top-level");
1110 return Failure;
1111 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001112
1113 unsigned BlockID = Stream.ReadSubBlockID();
1114
1115 // We only know the PCH subblock ID.
1116 switch (BlockID) {
1117 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001118 if (Stream.ReadBlockInfoBlock()) {
1119 Error("Malformed BlockInfoBlock");
1120 return Failure;
1121 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001122 break;
1123 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001124 switch (ReadPCHBlock()) {
1125 case Success:
1126 break;
1127
1128 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001129 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001130
1131 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001132 // FIXME: We could consider reading through to the end of this
1133 // PCH block, skipping subblocks, to see if there are other
1134 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001135 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001136 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001137 break;
1138 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001139 if (Stream.SkipBlock()) {
1140 Error("Malformed block record");
1141 return Failure;
1142 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001143 break;
1144 }
1145 }
1146
1147 // Load the translation unit declaration
1148 ReadDeclRecord(DeclOffsets[0], 0);
1149
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001150 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001151}
1152
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001153namespace {
1154 /// \brief Helper class that saves the current stream position and
1155 /// then restores it when destroyed.
1156 struct VISIBILITY_HIDDEN SavedStreamPosition {
1157 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001158 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001159
1160 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001161 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001162 }
1163
1164 private:
1165 llvm::BitstreamReader &Stream;
1166 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001167 };
1168}
1169
Douglas Gregor179cfb12009-04-10 20:39:37 +00001170/// \brief Parse the record that corresponds to a LangOptions data
1171/// structure.
1172///
1173/// This routine compares the language options used to generate the
1174/// PCH file against the language options set for the current
1175/// compilation. For each option, we classify differences between the
1176/// two compiler states as either "benign" or "important". Benign
1177/// differences don't matter, and we accept them without complaint
1178/// (and without modifying the language options). Differences between
1179/// the states for important options cause the PCH file to be
1180/// unusable, so we emit a warning and return true to indicate that
1181/// there was an error.
1182///
1183/// \returns true if the PCH file is unacceptable, false otherwise.
1184bool PCHReader::ParseLanguageOptions(
1185 const llvm::SmallVectorImpl<uint64_t> &Record) {
1186 const LangOptions &LangOpts = Context.getLangOptions();
1187#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1188#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1189 if (Record[Idx] != LangOpts.Option) { \
1190 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1191 Diag(diag::note_ignoring_pch) << FileName; \
1192 return true; \
1193 } \
1194 ++Idx
1195
1196 unsigned Idx = 0;
1197 PARSE_LANGOPT_BENIGN(Trigraphs);
1198 PARSE_LANGOPT_BENIGN(BCPLComment);
1199 PARSE_LANGOPT_BENIGN(DollarIdents);
1200 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1201 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1202 PARSE_LANGOPT_BENIGN(ImplicitInt);
1203 PARSE_LANGOPT_BENIGN(Digraphs);
1204 PARSE_LANGOPT_BENIGN(HexFloats);
1205 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1206 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1207 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1208 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1209 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1210 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1211 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1212 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1213 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1214 PARSE_LANGOPT_BENIGN(PascalStrings);
1215 PARSE_LANGOPT_BENIGN(Boolean);
1216 PARSE_LANGOPT_BENIGN(WritableStrings);
1217 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1218 diag::warn_pch_lax_vector_conversions);
1219 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1220 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1221 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1222 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1223 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1224 diag::warn_pch_thread_safe_statics);
1225 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1226 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1227 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1228 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1229 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1230 diag::warn_pch_heinous_extensions);
1231 // FIXME: Most of the options below are benign if the macro wasn't
1232 // used. Unfortunately, this means that a PCH compiled without
1233 // optimization can't be used with optimization turned on, even
1234 // though the only thing that changes is whether __OPTIMIZE__ was
1235 // defined... but if __OPTIMIZE__ never showed up in the header, it
1236 // doesn't matter. We could consider making this some special kind
1237 // of check.
1238 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1239 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1240 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1241 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1242 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1243 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1244 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1245 Diag(diag::warn_pch_gc_mode)
1246 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1247 Diag(diag::note_ignoring_pch) << FileName;
1248 return true;
1249 }
1250 ++Idx;
1251 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1252 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1253#undef PARSE_LANGOPT_IRRELEVANT
1254#undef PARSE_LANGOPT_BENIGN
1255
1256 return false;
1257}
1258
Douglas Gregorc34897d2009-04-09 22:27:44 +00001259/// \brief Read and return the type at the given offset.
1260///
1261/// This routine actually reads the record corresponding to the type
1262/// at the given offset in the bitstream. It is a helper routine for
1263/// GetType, which deals with reading type IDs.
1264QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001265 // Keep track of where we are in the stream, then jump back there
1266 // after reading this type.
1267 SavedStreamPosition SavedPosition(Stream);
1268
Douglas Gregorc34897d2009-04-09 22:27:44 +00001269 Stream.JumpToBit(Offset);
1270 RecordData Record;
1271 unsigned Code = Stream.ReadCode();
1272 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001273 case pch::TYPE_EXT_QUAL: {
1274 assert(Record.size() == 3 &&
1275 "Incorrect encoding of extended qualifier type");
1276 QualType Base = GetType(Record[0]);
1277 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1278 unsigned AddressSpace = Record[2];
1279
1280 QualType T = Base;
1281 if (GCAttr != QualType::GCNone)
1282 T = Context.getObjCGCQualType(T, GCAttr);
1283 if (AddressSpace)
1284 T = Context.getAddrSpaceQualType(T, AddressSpace);
1285 return T;
1286 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001287
Douglas Gregorc34897d2009-04-09 22:27:44 +00001288 case pch::TYPE_FIXED_WIDTH_INT: {
1289 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1290 return Context.getFixedWidthIntType(Record[0], Record[1]);
1291 }
1292
1293 case pch::TYPE_COMPLEX: {
1294 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1295 QualType ElemType = GetType(Record[0]);
1296 return Context.getComplexType(ElemType);
1297 }
1298
1299 case pch::TYPE_POINTER: {
1300 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1301 QualType PointeeType = GetType(Record[0]);
1302 return Context.getPointerType(PointeeType);
1303 }
1304
1305 case pch::TYPE_BLOCK_POINTER: {
1306 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1307 QualType PointeeType = GetType(Record[0]);
1308 return Context.getBlockPointerType(PointeeType);
1309 }
1310
1311 case pch::TYPE_LVALUE_REFERENCE: {
1312 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1313 QualType PointeeType = GetType(Record[0]);
1314 return Context.getLValueReferenceType(PointeeType);
1315 }
1316
1317 case pch::TYPE_RVALUE_REFERENCE: {
1318 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1319 QualType PointeeType = GetType(Record[0]);
1320 return Context.getRValueReferenceType(PointeeType);
1321 }
1322
1323 case pch::TYPE_MEMBER_POINTER: {
1324 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1325 QualType PointeeType = GetType(Record[0]);
1326 QualType ClassType = GetType(Record[1]);
1327 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1328 }
1329
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001330 case pch::TYPE_CONSTANT_ARRAY: {
1331 QualType ElementType = GetType(Record[0]);
1332 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1333 unsigned IndexTypeQuals = Record[2];
1334 unsigned Idx = 3;
1335 llvm::APInt Size = ReadAPInt(Record, Idx);
1336 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1337 }
1338
1339 case pch::TYPE_INCOMPLETE_ARRAY: {
1340 QualType ElementType = GetType(Record[0]);
1341 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1342 unsigned IndexTypeQuals = Record[2];
1343 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1344 }
1345
1346 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001347 QualType ElementType = GetType(Record[0]);
1348 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1349 unsigned IndexTypeQuals = Record[2];
1350 return Context.getVariableArrayType(ElementType, ReadExpr(),
1351 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001352 }
1353
1354 case pch::TYPE_VECTOR: {
1355 if (Record.size() != 2) {
1356 Error("Incorrect encoding of vector type in PCH file");
1357 return QualType();
1358 }
1359
1360 QualType ElementType = GetType(Record[0]);
1361 unsigned NumElements = Record[1];
1362 return Context.getVectorType(ElementType, NumElements);
1363 }
1364
1365 case pch::TYPE_EXT_VECTOR: {
1366 if (Record.size() != 2) {
1367 Error("Incorrect encoding of extended vector type in PCH file");
1368 return QualType();
1369 }
1370
1371 QualType ElementType = GetType(Record[0]);
1372 unsigned NumElements = Record[1];
1373 return Context.getExtVectorType(ElementType, NumElements);
1374 }
1375
1376 case pch::TYPE_FUNCTION_NO_PROTO: {
1377 if (Record.size() != 1) {
1378 Error("Incorrect encoding of no-proto function type");
1379 return QualType();
1380 }
1381 QualType ResultType = GetType(Record[0]);
1382 return Context.getFunctionNoProtoType(ResultType);
1383 }
1384
1385 case pch::TYPE_FUNCTION_PROTO: {
1386 QualType ResultType = GetType(Record[0]);
1387 unsigned Idx = 1;
1388 unsigned NumParams = Record[Idx++];
1389 llvm::SmallVector<QualType, 16> ParamTypes;
1390 for (unsigned I = 0; I != NumParams; ++I)
1391 ParamTypes.push_back(GetType(Record[Idx++]));
1392 bool isVariadic = Record[Idx++];
1393 unsigned Quals = Record[Idx++];
1394 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1395 isVariadic, Quals);
1396 }
1397
1398 case pch::TYPE_TYPEDEF:
1399 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1400 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1401
1402 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001403 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001404
1405 case pch::TYPE_TYPEOF: {
1406 if (Record.size() != 1) {
1407 Error("Incorrect encoding of typeof(type) in PCH file");
1408 return QualType();
1409 }
1410 QualType UnderlyingType = GetType(Record[0]);
1411 return Context.getTypeOfType(UnderlyingType);
1412 }
1413
1414 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001415 assert(Record.size() == 1 && "Incorrect encoding of record type");
1416 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001417
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001418 case pch::TYPE_ENUM:
1419 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1420 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1421
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001422 case pch::TYPE_OBJC_INTERFACE:
1423 // FIXME: Deserialize ObjCInterfaceType
1424 assert(false && "Cannot de-serialize ObjC interface types yet");
1425 return QualType();
1426
1427 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1428 // FIXME: Deserialize ObjCQualifiedInterfaceType
1429 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1430 return QualType();
1431
1432 case pch::TYPE_OBJC_QUALIFIED_ID:
1433 // FIXME: Deserialize ObjCQualifiedIdType
1434 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1435 return QualType();
1436
1437 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1438 // FIXME: Deserialize ObjCQualifiedClassType
1439 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1440 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001441 }
1442
1443 // Suppress a GCC warning
1444 return QualType();
1445}
1446
1447/// \brief Note that we have loaded the declaration with the given
1448/// Index.
1449///
1450/// This routine notes that this declaration has already been loaded,
1451/// so that future GetDecl calls will return this declaration rather
1452/// than trying to load a new declaration.
1453inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1454 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1455 DeclAlreadyLoaded[Index] = true;
1456 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1457}
1458
1459/// \brief Read the declaration at the given offset from the PCH file.
1460Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001461 // Keep track of where we are in the stream, then jump back there
1462 // after reading this declaration.
1463 SavedStreamPosition SavedPosition(Stream);
1464
Douglas Gregorc34897d2009-04-09 22:27:44 +00001465 Decl *D = 0;
1466 Stream.JumpToBit(Offset);
1467 RecordData Record;
1468 unsigned Code = Stream.ReadCode();
1469 unsigned Idx = 0;
1470 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001471
Douglas Gregorc34897d2009-04-09 22:27:44 +00001472 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001473 case pch::DECL_ATTR:
1474 case pch::DECL_CONTEXT_LEXICAL:
1475 case pch::DECL_CONTEXT_VISIBLE:
1476 assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1477 break;
1478
Douglas Gregorc34897d2009-04-09 22:27:44 +00001479 case pch::DECL_TRANSLATION_UNIT:
1480 assert(Index == 0 && "Translation unit must be at index 0");
1481 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1482 D = Context.getTranslationUnitDecl();
1483 LoadedDecl(Index, D);
1484 break;
1485
1486 case pch::DECL_TYPEDEF: {
1487 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1488 0, QualType());
1489 LoadedDecl(Index, Typedef);
1490 Reader.VisitTypedefDecl(Typedef);
1491 D = Typedef;
1492 break;
1493 }
1494
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001495 case pch::DECL_ENUM: {
1496 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1497 LoadedDecl(Index, Enum);
1498 Reader.VisitEnumDecl(Enum);
1499 D = Enum;
1500 break;
1501 }
1502
Douglas Gregor982365e2009-04-13 21:20:57 +00001503 case pch::DECL_RECORD: {
1504 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1505 0, SourceLocation(), 0, 0);
1506 LoadedDecl(Index, Record);
1507 Reader.VisitRecordDecl(Record);
1508 D = Record;
1509 break;
1510 }
1511
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001512 case pch::DECL_ENUM_CONSTANT: {
1513 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1514 SourceLocation(), 0,
1515 QualType(), 0,
1516 llvm::APSInt());
1517 LoadedDecl(Index, ECD);
1518 Reader.VisitEnumConstantDecl(ECD);
1519 D = ECD;
1520 break;
1521 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001522
1523 case pch::DECL_FUNCTION: {
1524 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1525 DeclarationName(),
1526 QualType());
1527 LoadedDecl(Index, Function);
1528 Reader.VisitFunctionDecl(Function);
1529 D = Function;
1530 break;
1531 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001532
Douglas Gregor982365e2009-04-13 21:20:57 +00001533 case pch::DECL_FIELD: {
1534 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1535 QualType(), 0, false);
1536 LoadedDecl(Index, Field);
1537 Reader.VisitFieldDecl(Field);
1538 D = Field;
1539 break;
1540 }
1541
Douglas Gregorc34897d2009-04-09 22:27:44 +00001542 case pch::DECL_VAR: {
1543 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1544 VarDecl::None, SourceLocation());
1545 LoadedDecl(Index, Var);
1546 Reader.VisitVarDecl(Var);
1547 D = Var;
1548 break;
1549 }
1550
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001551 case pch::DECL_PARM_VAR: {
1552 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1553 QualType(), VarDecl::None, 0);
1554 LoadedDecl(Index, Parm);
1555 Reader.VisitParmVarDecl(Parm);
1556 D = Parm;
1557 break;
1558 }
1559
1560 case pch::DECL_ORIGINAL_PARM_VAR: {
1561 OriginalParmVarDecl *Parm
1562 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1563 QualType(), QualType(), VarDecl::None,
1564 0);
1565 LoadedDecl(Index, Parm);
1566 Reader.VisitOriginalParmVarDecl(Parm);
1567 D = Parm;
1568 break;
1569 }
1570
Douglas Gregor2a491792009-04-13 22:49:25 +00001571 case pch::DECL_FILE_SCOPE_ASM: {
1572 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1573 SourceLocation(), 0);
1574 LoadedDecl(Index, Asm);
1575 Reader.VisitFileScopeAsmDecl(Asm);
1576 D = Asm;
1577 break;
1578 }
1579
1580 case pch::DECL_BLOCK: {
1581 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1582 LoadedDecl(Index, Block);
1583 Reader.VisitBlockDecl(Block);
1584 D = Block;
1585 break;
1586 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001587 }
1588
1589 // If this declaration is also a declaration context, get the
1590 // offsets for its tables of lexical and visible declarations.
1591 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1592 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1593 if (Offsets.first || Offsets.second) {
1594 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1595 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1596 DeclContextOffsets[DC] = Offsets;
1597 }
1598 }
1599 assert(Idx == Record.size());
1600
1601 return D;
1602}
1603
Douglas Gregorac8f2802009-04-10 17:25:41 +00001604QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001605 unsigned Quals = ID & 0x07;
1606 unsigned Index = ID >> 3;
1607
1608 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1609 QualType T;
1610 switch ((pch::PredefinedTypeIDs)Index) {
1611 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1612 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1613 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1614
1615 case pch::PREDEF_TYPE_CHAR_U_ID:
1616 case pch::PREDEF_TYPE_CHAR_S_ID:
1617 // FIXME: Check that the signedness of CharTy is correct!
1618 T = Context.CharTy;
1619 break;
1620
1621 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1622 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1623 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1624 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1625 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1626 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1627 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1628 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1629 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1630 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1631 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1632 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1633 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1634 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1635 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1636 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1637 }
1638
1639 assert(!T.isNull() && "Unknown predefined type");
1640 return T.getQualifiedType(Quals);
1641 }
1642
1643 Index -= pch::NUM_PREDEF_TYPE_IDS;
1644 if (!TypeAlreadyLoaded[Index]) {
1645 // Load the type from the PCH file.
1646 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1647 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1648 TypeAlreadyLoaded[Index] = true;
1649 }
1650
1651 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1652}
1653
Douglas Gregorac8f2802009-04-10 17:25:41 +00001654Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001655 if (ID == 0)
1656 return 0;
1657
1658 unsigned Index = ID - 1;
1659 if (DeclAlreadyLoaded[Index])
1660 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1661
1662 // Load the declaration from the PCH file.
1663 return ReadDeclRecord(DeclOffsets[Index], Index);
1664}
1665
1666bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001667 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001668 assert(DC->hasExternalLexicalStorage() &&
1669 "DeclContext has no lexical decls in storage");
1670 uint64_t Offset = DeclContextOffsets[DC].first;
1671 assert(Offset && "DeclContext has no lexical decls in storage");
1672
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001673 // Keep track of where we are in the stream, then jump back there
1674 // after reading this context.
1675 SavedStreamPosition SavedPosition(Stream);
1676
Douglas Gregorc34897d2009-04-09 22:27:44 +00001677 // Load the record containing all of the declarations lexically in
1678 // this context.
1679 Stream.JumpToBit(Offset);
1680 RecordData Record;
1681 unsigned Code = Stream.ReadCode();
1682 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001683 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001684 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1685
1686 // Load all of the declaration IDs
1687 Decls.clear();
1688 Decls.insert(Decls.end(), Record.begin(), Record.end());
1689 return false;
1690}
1691
1692bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1693 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1694 assert(DC->hasExternalVisibleStorage() &&
1695 "DeclContext has no visible decls in storage");
1696 uint64_t Offset = DeclContextOffsets[DC].second;
1697 assert(Offset && "DeclContext has no visible decls in storage");
1698
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001699 // Keep track of where we are in the stream, then jump back there
1700 // after reading this context.
1701 SavedStreamPosition SavedPosition(Stream);
1702
Douglas Gregorc34897d2009-04-09 22:27:44 +00001703 // Load the record containing all of the declarations visible in
1704 // this context.
1705 Stream.JumpToBit(Offset);
1706 RecordData Record;
1707 unsigned Code = Stream.ReadCode();
1708 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001709 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001710 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1711 if (Record.size() == 0)
1712 return false;
1713
1714 Decls.clear();
1715
1716 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001717 while (Idx < Record.size()) {
1718 Decls.push_back(VisibleDeclaration());
1719 Decls.back().Name = ReadDeclarationName(Record, Idx);
1720
Douglas Gregorc34897d2009-04-09 22:27:44 +00001721 unsigned Size = Record[Idx++];
1722 llvm::SmallVector<unsigned, 4> & LoadedDecls
1723 = Decls.back().Declarations;
1724 LoadedDecls.reserve(Size);
1725 for (unsigned I = 0; I < Size; ++I)
1726 LoadedDecls.push_back(Record[Idx++]);
1727 }
1728
1729 return false;
1730}
1731
Douglas Gregor631f6c62009-04-14 00:24:19 +00001732void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1733 if (!Consumer)
1734 return;
1735
1736 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1737 Decl *D = GetDecl(ExternalDefinitions[I]);
1738 DeclGroupRef DG(D);
1739 Consumer->HandleTopLevelDecl(DG);
1740 }
1741}
1742
Douglas Gregorc34897d2009-04-09 22:27:44 +00001743void PCHReader::PrintStats() {
1744 std::fprintf(stderr, "*** PCH Statistics:\n");
1745
1746 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1747 TypeAlreadyLoaded.end(),
1748 true);
1749 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1750 DeclAlreadyLoaded.end(),
1751 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001752 unsigned NumIdentifiersLoaded = 0;
1753 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1754 if ((IdentifierData[I] & 0x01) == 0)
1755 ++NumIdentifiersLoaded;
1756 }
1757
Douglas Gregorc34897d2009-04-09 22:27:44 +00001758 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1759 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001760 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001761 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1762 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001763 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1764 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1765 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1766 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001767 std::fprintf(stderr, "\n");
1768}
1769
Chris Lattner29241862009-04-11 21:15:38 +00001770IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001771 if (ID == 0)
1772 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001773
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001774 if (!IdentifierTable || IdentifierData.empty()) {
1775 Error("No identifier table in PCH file");
1776 return 0;
1777 }
Chris Lattner29241862009-04-11 21:15:38 +00001778
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001779 if (IdentifierData[ID - 1] & 0x01) {
1780 uint64_t Offset = IdentifierData[ID - 1];
1781 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001782 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001783 }
Chris Lattner29241862009-04-11 21:15:38 +00001784
1785 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001786}
1787
1788DeclarationName
1789PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1790 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1791 switch (Kind) {
1792 case DeclarationName::Identifier:
1793 return DeclarationName(GetIdentifierInfo(Record, Idx));
1794
1795 case DeclarationName::ObjCZeroArgSelector:
1796 case DeclarationName::ObjCOneArgSelector:
1797 case DeclarationName::ObjCMultiArgSelector:
1798 assert(false && "Unable to de-serialize Objective-C selectors");
1799 break;
1800
1801 case DeclarationName::CXXConstructorName:
1802 return Context.DeclarationNames.getCXXConstructorName(
1803 GetType(Record[Idx++]));
1804
1805 case DeclarationName::CXXDestructorName:
1806 return Context.DeclarationNames.getCXXDestructorName(
1807 GetType(Record[Idx++]));
1808
1809 case DeclarationName::CXXConversionFunctionName:
1810 return Context.DeclarationNames.getCXXConversionFunctionName(
1811 GetType(Record[Idx++]));
1812
1813 case DeclarationName::CXXOperatorName:
1814 return Context.DeclarationNames.getCXXOperatorName(
1815 (OverloadedOperatorKind)Record[Idx++]);
1816
1817 case DeclarationName::CXXUsingDirective:
1818 return DeclarationName::getUsingDirectiveName();
1819 }
1820
1821 // Required to silence GCC warning
1822 return DeclarationName();
1823}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001824
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001825/// \brief Read an integral value
1826llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1827 unsigned BitWidth = Record[Idx++];
1828 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1829 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1830 Idx += NumWords;
1831 return Result;
1832}
1833
1834/// \brief Read a signed integral value
1835llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1836 bool isUnsigned = Record[Idx++];
1837 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1838}
1839
Douglas Gregore2f37202009-04-14 21:55:33 +00001840/// \brief Read a floating-point value
1841llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00001842 return llvm::APFloat(ReadAPInt(Record, Idx));
1843}
1844
Douglas Gregor1c507882009-04-15 21:30:51 +00001845// \brief Read a string
1846std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
1847 unsigned Len = Record[Idx++];
1848 std::string Result(&Record[Idx], &Record[Idx] + Len);
1849 Idx += Len;
1850 return Result;
1851}
1852
1853/// \brief Reads attributes from the current stream position.
1854Attr *PCHReader::ReadAttributes() {
1855 unsigned Code = Stream.ReadCode();
1856 assert(Code == llvm::bitc::UNABBREV_RECORD &&
1857 "Expected unabbreviated record"); (void)Code;
1858
1859 RecordData Record;
1860 unsigned Idx = 0;
1861 unsigned RecCode = Stream.ReadRecord(Code, Record);
1862 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
1863 (void)RecCode;
1864
1865#define SIMPLE_ATTR(Name) \
1866 case Attr::Name: \
1867 New = ::new (Context) Name##Attr(); \
1868 break
1869
1870#define STRING_ATTR(Name) \
1871 case Attr::Name: \
1872 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
1873 break
1874
1875#define UNSIGNED_ATTR(Name) \
1876 case Attr::Name: \
1877 New = ::new (Context) Name##Attr(Record[Idx++]); \
1878 break
1879
1880 Attr *Attrs = 0;
1881 while (Idx < Record.size()) {
1882 Attr *New = 0;
1883 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
1884 bool IsInherited = Record[Idx++];
1885
1886 switch (Kind) {
1887 STRING_ATTR(Alias);
1888 UNSIGNED_ATTR(Aligned);
1889 SIMPLE_ATTR(AlwaysInline);
1890 SIMPLE_ATTR(AnalyzerNoReturn);
1891 STRING_ATTR(Annotate);
1892 STRING_ATTR(AsmLabel);
1893
1894 case Attr::Blocks:
1895 New = ::new (Context) BlocksAttr(
1896 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
1897 break;
1898
1899 case Attr::Cleanup:
1900 New = ::new (Context) CleanupAttr(
1901 cast<FunctionDecl>(GetDecl(Record[Idx++])));
1902 break;
1903
1904 SIMPLE_ATTR(Const);
1905 UNSIGNED_ATTR(Constructor);
1906 SIMPLE_ATTR(DLLExport);
1907 SIMPLE_ATTR(DLLImport);
1908 SIMPLE_ATTR(Deprecated);
1909 UNSIGNED_ATTR(Destructor);
1910 SIMPLE_ATTR(FastCall);
1911
1912 case Attr::Format: {
1913 std::string Type = ReadString(Record, Idx);
1914 unsigned FormatIdx = Record[Idx++];
1915 unsigned FirstArg = Record[Idx++];
1916 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
1917 break;
1918 }
1919
1920 SIMPLE_ATTR(GNUCInline);
1921
1922 case Attr::IBOutletKind:
1923 New = ::new (Context) IBOutletAttr();
1924 break;
1925
1926 SIMPLE_ATTR(NoReturn);
1927 SIMPLE_ATTR(NoThrow);
1928 SIMPLE_ATTR(Nodebug);
1929 SIMPLE_ATTR(Noinline);
1930
1931 case Attr::NonNull: {
1932 unsigned Size = Record[Idx++];
1933 llvm::SmallVector<unsigned, 16> ArgNums;
1934 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
1935 Idx += Size;
1936 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
1937 break;
1938 }
1939
1940 SIMPLE_ATTR(ObjCException);
1941 SIMPLE_ATTR(ObjCNSObject);
1942 SIMPLE_ATTR(Overloadable);
1943 UNSIGNED_ATTR(Packed);
1944 SIMPLE_ATTR(Pure);
1945 UNSIGNED_ATTR(Regparm);
1946 STRING_ATTR(Section);
1947 SIMPLE_ATTR(StdCall);
1948 SIMPLE_ATTR(TransparentUnion);
1949 SIMPLE_ATTR(Unavailable);
1950 SIMPLE_ATTR(Unused);
1951 SIMPLE_ATTR(Used);
1952
1953 case Attr::Visibility:
1954 New = ::new (Context) VisibilityAttr(
1955 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
1956 break;
1957
1958 SIMPLE_ATTR(WarnUnusedResult);
1959 SIMPLE_ATTR(Weak);
1960 SIMPLE_ATTR(WeakImport);
1961 }
1962
1963 assert(New && "Unable to decode attribute?");
1964 New->setInherited(IsInherited);
1965 New->setNext(Attrs);
1966 Attrs = New;
1967 }
1968#undef UNSIGNED_ATTR
1969#undef STRING_ATTR
1970#undef SIMPLE_ATTR
1971
1972 // The list of attributes was built backwards. Reverse the list
1973 // before returning it.
1974 Attr *PrevAttr = 0, *NextAttr = 0;
1975 while (Attrs) {
1976 NextAttr = Attrs->getNext();
1977 Attrs->setNext(PrevAttr);
1978 PrevAttr = Attrs;
1979 Attrs = NextAttr;
1980 }
1981
1982 return PrevAttr;
1983}
1984
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001985Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001986 // Within the bitstream, expressions are stored in Reverse Polish
1987 // Notation, with each of the subexpressions preceding the
1988 // expression they are stored in. To evaluate expressions, we
1989 // continue reading expressions and placing them on the stack, with
1990 // expressions having operands removing those operands from the
1991 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1992 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001993 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001994 unsigned Idx;
1995 llvm::SmallVector<Expr *, 16> ExprStack;
1996 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001997 Stmt::EmptyShell Empty;
1998
Douglas Gregora151ba42009-04-14 23:32:43 +00001999 while (true) {
2000 unsigned Code = Stream.ReadCode();
2001 if (Code == llvm::bitc::END_BLOCK) {
2002 if (Stream.ReadBlockEnd()) {
2003 Error("Error at end of Source Manager block");
2004 return 0;
2005 }
2006 break;
2007 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002008
Douglas Gregora151ba42009-04-14 23:32:43 +00002009 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2010 // No known subblocks, always skip them.
2011 Stream.ReadSubBlockID();
2012 if (Stream.SkipBlock()) {
2013 Error("Malformed block record");
2014 return 0;
2015 }
2016 continue;
2017 }
Douglas Gregore2f37202009-04-14 21:55:33 +00002018
Douglas Gregora151ba42009-04-14 23:32:43 +00002019 if (Code == llvm::bitc::DEFINE_ABBREV) {
2020 Stream.ReadAbbrevRecord();
2021 continue;
2022 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002023
Douglas Gregora151ba42009-04-14 23:32:43 +00002024 Expr *E = 0;
2025 Idx = 0;
2026 Record.clear();
2027 bool Finished = false;
2028 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
2029 case pch::EXPR_STOP:
2030 Finished = true;
2031 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002032
Douglas Gregora151ba42009-04-14 23:32:43 +00002033 case pch::EXPR_NULL:
2034 E = 0;
2035 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002036
Douglas Gregora151ba42009-04-14 23:32:43 +00002037 case pch::EXPR_PREDEFINED:
2038 // FIXME: untested (until we can serialize function bodies).
2039 E = new (Context) PredefinedExpr(Empty);
2040 break;
2041
2042 case pch::EXPR_DECL_REF:
2043 E = new (Context) DeclRefExpr(Empty);
2044 break;
2045
2046 case pch::EXPR_INTEGER_LITERAL:
2047 E = new (Context) IntegerLiteral(Empty);
2048 break;
2049
2050 case pch::EXPR_FLOATING_LITERAL:
2051 E = new (Context) FloatingLiteral(Empty);
2052 break;
2053
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00002054 case pch::EXPR_IMAGINARY_LITERAL:
2055 E = new (Context) ImaginaryLiteral(Empty);
2056 break;
2057
Douglas Gregor596e0932009-04-15 16:35:07 +00002058 case pch::EXPR_STRING_LITERAL:
2059 E = StringLiteral::CreateEmpty(Context,
2060 Record[PCHStmtReader::NumExprFields + 1]);
2061 break;
2062
Douglas Gregora151ba42009-04-14 23:32:43 +00002063 case pch::EXPR_CHARACTER_LITERAL:
2064 E = new (Context) CharacterLiteral(Empty);
2065 break;
2066
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00002067 case pch::EXPR_PAREN:
2068 E = new (Context) ParenExpr(Empty);
2069 break;
2070
Douglas Gregor12d74052009-04-15 15:58:59 +00002071 case pch::EXPR_UNARY_OPERATOR:
2072 E = new (Context) UnaryOperator(Empty);
2073 break;
2074
2075 case pch::EXPR_SIZEOF_ALIGN_OF:
2076 E = new (Context) SizeOfAlignOfExpr(Empty);
2077 break;
2078
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00002079 case pch::EXPR_ARRAY_SUBSCRIPT:
2080 E = new (Context) ArraySubscriptExpr(Empty);
2081 break;
2082
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00002083 case pch::EXPR_CALL:
2084 E = new (Context) CallExpr(Context, Empty);
2085 break;
2086
2087 case pch::EXPR_MEMBER:
2088 E = new (Context) MemberExpr(Empty);
2089 break;
2090
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00002091 case pch::EXPR_BINARY_OPERATOR:
2092 E = new (Context) BinaryOperator(Empty);
2093 break;
2094
Douglas Gregorc599bbf2009-04-15 22:40:36 +00002095 case pch::EXPR_COMPOUND_ASSIGN_OPERATOR:
2096 E = new (Context) CompoundAssignOperator(Empty);
2097 break;
2098
2099 case pch::EXPR_CONDITIONAL_OPERATOR:
2100 E = new (Context) ConditionalOperator(Empty);
2101 break;
2102
Douglas Gregora151ba42009-04-14 23:32:43 +00002103 case pch::EXPR_IMPLICIT_CAST:
2104 E = new (Context) ImplicitCastExpr(Empty);
2105 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00002106
2107 case pch::EXPR_CSTYLE_CAST:
2108 E = new (Context) CStyleCastExpr(Empty);
2109 break;
Douglas Gregorec0b8292009-04-15 23:02:49 +00002110
Douglas Gregorb70b48f2009-04-16 02:33:48 +00002111 case pch::EXPR_COMPOUND_LITERAL:
2112 E = new (Context) CompoundLiteralExpr(Empty);
2113 break;
2114
Douglas Gregorec0b8292009-04-15 23:02:49 +00002115 case pch::EXPR_EXT_VECTOR_ELEMENT:
2116 E = new (Context) ExtVectorElementExpr(Empty);
2117 break;
2118
Douglas Gregor6710a3c2009-04-16 00:55:48 +00002119 case pch::EXPR_INIT_LIST:
2120 E = new (Context) InitListExpr(Empty);
2121 break;
2122
2123 case pch::EXPR_DESIGNATED_INIT:
2124 E = DesignatedInitExpr::CreateEmpty(Context,
2125 Record[PCHStmtReader::NumExprFields] - 1);
2126
2127 break;
2128
2129 case pch::EXPR_IMPLICIT_VALUE_INIT:
2130 E = new (Context) ImplicitValueInitExpr(Empty);
2131 break;
2132
Douglas Gregorec0b8292009-04-15 23:02:49 +00002133 case pch::EXPR_VA_ARG:
2134 // FIXME: untested; we need function bodies first
2135 E = new (Context) VAArgExpr(Empty);
2136 break;
Douglas Gregor209d4622009-04-15 23:33:31 +00002137
2138 case pch::EXPR_TYPES_COMPATIBLE:
2139 E = new (Context) TypesCompatibleExpr(Empty);
2140 break;
2141
2142 case pch::EXPR_CHOOSE:
2143 E = new (Context) ChooseExpr(Empty);
2144 break;
2145
2146 case pch::EXPR_GNU_NULL:
2147 E = new (Context) GNUNullExpr(Empty);
2148 break;
Douglas Gregor725e94b2009-04-16 00:01:45 +00002149
2150 case pch::EXPR_SHUFFLE_VECTOR:
2151 E = new (Context) ShuffleVectorExpr(Empty);
2152 break;
2153
2154 case pch::EXPR_BLOCK_DECL_REF:
2155 // FIXME: untested until we have statement and block support
2156 E = new (Context) BlockDeclRefExpr(Empty);
2157 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00002158 }
2159
2160 // We hit an EXPR_STOP, so we're done with this expression.
2161 if (Finished)
2162 break;
2163
2164 if (E) {
2165 unsigned NumSubExprs = Reader.Visit(E);
2166 while (NumSubExprs > 0) {
2167 ExprStack.pop_back();
2168 --NumSubExprs;
2169 }
2170 }
2171
2172 assert(Idx == Record.size() && "Invalid deserialization of expression");
2173 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002174 }
Douglas Gregora151ba42009-04-14 23:32:43 +00002175 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
2176 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002177}
2178
Douglas Gregor179cfb12009-04-10 20:39:37 +00002179DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002180 return Diag(SourceLocation(), DiagID);
2181}
2182
2183DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2184 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00002185 Context.getSourceManager()),
2186 DiagID);
2187}