blob: ca7aa3260c62f105f926fbc0d8088d1c6d83d5b4 [file] [log] [blame]
Douglas Gregor2cf26342009-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//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbarc7162932009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000036#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000044// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
75 PARSE_LANGOPT_BENIGN(PascalStrings);
76 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000077 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000078 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000079 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000080 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
81 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
82 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
83 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000084 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000086 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000087 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
88 PARSE_LANGOPT_BENIGN(EmitAllDecls);
89 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
90 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_heinous_extensions);
93 // FIXME: Most of the options below are benign if the macro wasn't
94 // used. Unfortunately, this means that a PCH compiled without
95 // optimization can't be used with optimization turned on, even
96 // though the only thing that changes is whether __OPTIMIZE__ was
97 // defined... but if __OPTIMIZE__ never showed up in the header, it
98 // doesn't matter. We could consider making this some special kind
99 // of check.
100 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
101 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
102 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
103 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
104 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
105 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
106 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
107 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000108 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000109 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000110 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000111 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112 return true;
113 }
114 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000115 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000117 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000118 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000119 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000120#undef PARSE_LANGOPT_IRRELEVANT
121#undef PARSE_LANGOPT_BENIGN
122
123 return false;
124}
125
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000126bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
127 if (Triple == PP.getTargetInfo().getTriple().str())
128 return false;
129
130 Reader.Diag(diag::warn_pch_target_triple)
131 << Triple << PP.getTargetInfo().getTriple().str();
132 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000133}
134
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000135bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000136 FileID PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000137 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000138 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000139 // We are in the context of an implicit include, so the predefines buffer will
140 // have a #include entry for the PCH file itself (as normalized by the
141 // preprocessor initialization). Find it and skip over it in the checking
142 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000143 llvm::SmallString<256> PCHInclude;
144 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000145 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000146 PCHInclude += "\"\n";
147 std::pair<llvm::StringRef,llvm::StringRef> Split =
148 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
149 llvm::StringRef Left = Split.first, Right = Split.second;
150 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
151
152 // If the predefines is equal to the joined left and right halves, we're done!
153 if (Left.size() + Right.size() == PCHPredef.size() &&
154 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000155 return false;
156
157 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000159 // The predefines buffers are different. Determine what the differences are,
160 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000161 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
162 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
163
164 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
165 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
166 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000167
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000168 // Sort both sets of predefined buffer lines, since we allow some extra
169 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000170 std::sort(CmdLineLines.begin(), CmdLineLines.end());
171 std::sort(PCHLines.begin(), PCHLines.end());
172
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000173 // Determine which predefines that were used to build the PCH file are missing
174 // from the command line.
175 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000176 std::set_difference(PCHLines.begin(), PCHLines.end(),
177 CmdLineLines.begin(), CmdLineLines.end(),
178 std::back_inserter(MissingPredefines));
179
180 bool MissingDefines = false;
181 bool ConflictingDefines = false;
182 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000183 llvm::StringRef Missing = MissingPredefines[I];
184 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000185 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
186 return true;
187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000189 // This is a macro definition. Determine the name of the macro we're
190 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000191 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000192 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000193 = Missing.find_first_of("( \n\r", StartOfMacroName);
194 assert(EndOfMacroName != std::string::npos &&
195 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000196 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000197
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000198 // Determine whether this macro was given a different definition on the
199 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000200 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000201 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000202 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000203 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
204 MacroDefStart);
205 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000206 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000207 // Different macro; we're done.
208 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000209 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
212 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000213 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000214 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 (*ConflictPos)[MacroDefLen] != '(')
216 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000218 // We found a conflicting macro definition.
219 break;
220 }
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000222 if (ConflictPos != CmdLineLines.end()) {
223 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
224 << MacroName;
225
226 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000227 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
228 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
229 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
230 .getFileLocWithOffset(Offset);
231 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000232
233 ConflictingDefines = true;
234 continue;
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000237 // If the macro doesn't conflict, then we'll just pick up the macro
238 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000239 if (ConflictingDefines)
240 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000242 if (!MissingDefines) {
243 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
244 MissingDefines = true;
245 }
246
247 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000248 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
249 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
250 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000251 .getFileLocWithOffset(Offset);
252 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
253 }
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000255 if (ConflictingDefines)
256 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000258 // Determine what predefines were introduced based on command-line
259 // parameters that were not present when building the PCH
260 // file. Extra #defines are okay, so long as the identifiers being
261 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000262 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000263 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
264 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000265 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000266 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000267 llvm::StringRef &Extra = ExtraPredefines[I];
268 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000269 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
270 return true;
271 }
272
273 // This is an extra macro definition. Determine the name of the
274 // macro we're defining.
275 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000276 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000277 = Extra.find_first_of("( \n\r", StartOfMacroName);
278 assert(EndOfMacroName != std::string::npos &&
279 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000280 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000281
282 // Check whether this name was used somewhere in the PCH file. If
283 // so, defining it as a macro could change behavior, so we reject
284 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000285 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000286 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000287 return true;
288 }
289
290 // Add this definition to the suggested predefines buffer.
291 SuggestedPredefines += Extra;
292 SuggestedPredefines += '\n';
293 }
294
295 // If we get here, it's because the predefines buffer had compatible
296 // contents. Accept the PCH file.
297 return false;
298}
299
300void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
301 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
302}
303
304void PCHValidator::ReadCounter(unsigned Value) {
305 PP.setCounterValue(Value);
306}
307
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000309// PCH reader implementation
310//===----------------------------------------------------------------------===//
311
Mike Stump1eb44332009-09-09 15:08:12 +0000312PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
313 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000314 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
315 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000316 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000317 IdentifierTableData(0), IdentifierLookupTable(0),
318 IdentifierOffsets(0),
319 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
320 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000321 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000322 NumStatHits(0), NumStatMisses(0),
323 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000324 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000325 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000326 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000327 RelocatablePCH = false;
328}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000329
330PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000333 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000334 IdentifierTableData(0), IdentifierLookupTable(0),
335 IdentifierOffsets(0),
336 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
337 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000338 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000339 NumStatHits(0), NumStatMisses(0),
340 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000341 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000342 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000343 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000344 RelocatablePCH = false;
345}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000346
347PCHReader::~PCHReader() {}
348
Chris Lattnerda930612009-04-27 05:58:23 +0000349Expr *PCHReader::ReadDeclExpr() {
350 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
351}
352
353Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000354 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000355}
356
357
Douglas Gregor668c1a42009-04-21 22:25:48 +0000358namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000359class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
360 PCHReader &Reader;
361
362public:
363 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
364
365 typedef Selector external_key_type;
366 typedef external_key_type internal_key_type;
367
368 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000370 static bool EqualKey(const internal_key_type& a,
371 const internal_key_type& b) {
372 return a == b;
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000375 static unsigned ComputeHash(Selector Sel) {
376 unsigned N = Sel.getNumArgs();
377 if (N == 0)
378 ++N;
379 unsigned R = 5381;
380 for (unsigned I = 0; I != N; ++I)
381 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000382 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000383 return R;
384 }
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000386 // This hopefully will just get inlined and removed by the optimizer.
387 static const internal_key_type&
388 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000390 static std::pair<unsigned, unsigned>
391 ReadKeyDataLength(const unsigned char*& d) {
392 using namespace clang::io;
393 unsigned KeyLen = ReadUnalignedLE16(d);
394 unsigned DataLen = ReadUnalignedLE16(d);
395 return std::make_pair(KeyLen, DataLen);
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregor83941df2009-04-25 17:48:32 +0000398 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000399 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000400 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000401 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000402 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000403 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
404 if (N == 0)
405 return SelTable.getNullarySelector(FirstII);
406 else if (N == 1)
407 return SelTable.getUnarySelector(FirstII);
408
409 llvm::SmallVector<IdentifierInfo *, 16> Args;
410 Args.push_back(FirstII);
411 for (unsigned I = 1; I != N; ++I)
412 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
413
Douglas Gregor75fdb232009-05-22 22:45:36 +0000414 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000417 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
418 using namespace clang::io;
419 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
420 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
421
422 data_type Result;
423
424 // Load instance methods
425 ObjCMethodList *Prev = 0;
426 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000427 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000428 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
429 if (!Result.first.Method) {
430 // This is the first method, which is the easy case.
431 Result.first.Method = Method;
432 Prev = &Result.first;
433 continue;
434 }
435
436 Prev->Next = new ObjCMethodList(Method, 0);
437 Prev = Prev->Next;
438 }
439
440 // Load factory methods
441 Prev = 0;
442 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000443 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000444 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
445 if (!Result.second.Method) {
446 // This is the first method, which is the easy case.
447 Result.second.Method = Method;
448 Prev = &Result.second;
449 continue;
450 }
451
452 Prev->Next = new ObjCMethodList(Method, 0);
453 Prev = Prev->Next;
454 }
455
456 return Result;
457 }
458};
Mike Stump1eb44332009-09-09 15:08:12 +0000459
460} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000461
462/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000463typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000464 PCHMethodPoolLookupTable;
465
466namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000467class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
468 PCHReader &Reader;
469
470 // If we know the IdentifierInfo in advance, it is here and we will
471 // not build a new one. Used when deserializing information about an
472 // identifier that was constructed before the PCH file was read.
473 IdentifierInfo *KnownII;
474
475public:
476 typedef IdentifierInfo * data_type;
477
478 typedef const std::pair<const char*, unsigned> external_key_type;
479
480 typedef external_key_type internal_key_type;
481
Mike Stump1eb44332009-09-09 15:08:12 +0000482 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000483 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor668c1a42009-04-21 22:25:48 +0000485 static bool EqualKey(const internal_key_type& a,
486 const internal_key_type& b) {
487 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
488 : false;
489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Douglas Gregor668c1a42009-04-21 22:25:48 +0000491 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000492 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Douglas Gregor668c1a42009-04-21 22:25:48 +0000495 // This hopefully will just get inlined and removed by the optimizer.
496 static const internal_key_type&
497 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregor668c1a42009-04-21 22:25:48 +0000499 static std::pair<unsigned, unsigned>
500 ReadKeyDataLength(const unsigned char*& d) {
501 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000502 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000503 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000504 return std::make_pair(KeyLen, DataLen);
505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor668c1a42009-04-21 22:25:48 +0000507 static std::pair<const char*, unsigned>
508 ReadKey(const unsigned char* d, unsigned n) {
509 assert(n >= 2 && d[n-1] == '\0');
510 return std::make_pair((const char*) d, n-1);
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
513 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000514 const unsigned char* d,
515 unsigned DataLen) {
516 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000517 pch::IdentID ID = ReadUnalignedLE32(d);
518 bool IsInteresting = ID & 0x01;
519
520 // Wipe out the "is interesting" bit.
521 ID = ID >> 1;
522
523 if (!IsInteresting) {
524 // For unintersting identifiers, just build the IdentifierInfo
525 // and associate it with the persistent ID.
526 IdentifierInfo *II = KnownII;
527 if (!II)
528 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
529 k.first, k.first + k.second);
530 Reader.SetIdentifierInfo(ID, II);
531 return II;
532 }
533
Douglas Gregor5998da52009-04-28 21:32:13 +0000534 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000535 bool CPlusPlusOperatorKeyword = Bits & 0x01;
536 Bits >>= 1;
537 bool Poisoned = Bits & 0x01;
538 Bits >>= 1;
539 bool ExtensionToken = Bits & 0x01;
540 Bits >>= 1;
541 bool hasMacroDefinition = Bits & 0x01;
542 Bits >>= 1;
543 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
544 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Douglas Gregor2deaea32009-04-22 18:49:13 +0000546 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000547 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000548
549 // Build the IdentifierInfo itself and link the identifier ID with
550 // the new IdentifierInfo.
551 IdentifierInfo *II = KnownII;
552 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000553 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
554 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000555 Reader.SetIdentifierInfo(ID, II);
556
Douglas Gregor2deaea32009-04-22 18:49:13 +0000557 // Set or check the various bits in the IdentifierInfo structure.
558 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000559 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000560 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000561 "Incorrect extension token flag");
562 (void)ExtensionToken;
563 II->setIsPoisoned(Poisoned);
564 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
565 "Incorrect C++ operator keyword flag");
566 (void)CPlusPlusOperatorKeyword;
567
Douglas Gregor37e26842009-04-21 23:56:24 +0000568 // If this identifier is a macro, deserialize the macro
569 // definition.
570 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000571 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000572 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000573 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000574 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000575
576 // Read all of the declarations visible at global scope with this
577 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000578 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000579 if (DataLen > 0) {
580 llvm::SmallVector<uint32_t, 4> DeclIDs;
581 for (; DataLen > 0; DataLen -= 4)
582 DeclIDs.push_back(ReadUnalignedLE32(d));
583 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Douglas Gregor668c1a42009-04-21 22:25:48 +0000586 return II;
587 }
588};
Mike Stump1eb44332009-09-09 15:08:12 +0000589
590} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591
592/// \brief The on-disk hash table used to contain information about
593/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000594typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000595 PCHIdentifierLookupTable;
596
Douglas Gregora02b1472009-04-28 21:53:25 +0000597bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000598 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
599 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000600 return true;
601}
602
Douglas Gregore1d918e2009-04-10 23:10:45 +0000603/// \brief Check the contents of the predefines buffer against the
604/// contents of the predefines buffer used to build the PCH file.
605///
606/// The contents of the two predefines buffers should be the same. If
607/// not, then some command-line option changed the preprocessor state
608/// and we must reject the PCH file.
609///
610/// \param PCHPredef The start of the predefines buffer in the PCH
611/// file.
612///
613/// \param PCHPredefLen The length of the predefines buffer in the PCH
614/// file.
615///
616/// \param PCHBufferID The FileID for the PCH predefines buffer.
617///
618/// \returns true if there was a mismatch (in which case the PCH file
619/// should be ignored), or false otherwise.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000620bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000621 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000622 if (Listener)
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000623 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000624 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000625 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000626 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000627}
628
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000629//===----------------------------------------------------------------------===//
630// Source Manager Deserialization
631//===----------------------------------------------------------------------===//
632
Douglas Gregorbd945002009-04-13 16:31:14 +0000633/// \brief Read the line table in the source manager block.
634/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000635bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000636 unsigned Idx = 0;
637 LineTableInfo &LineTable = SourceMgr.getLineTable();
638
639 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000640 std::map<int, int> FileIDs;
641 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000642 // Extract the file name
643 unsigned FilenameLen = Record[Idx++];
644 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
645 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000646 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000647 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000648 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000649 }
650
651 // Parse the line entries
652 std::vector<LineEntry> Entries;
653 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000654 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000655
656 // Extract the line entries
657 unsigned NumEntries = Record[Idx++];
658 Entries.clear();
659 Entries.reserve(NumEntries);
660 for (unsigned I = 0; I != NumEntries; ++I) {
661 unsigned FileOffset = Record[Idx++];
662 unsigned LineNo = Record[Idx++];
663 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000664 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000665 = (SrcMgr::CharacteristicKind)Record[Idx++];
666 unsigned IncludeOffset = Record[Idx++];
667 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
668 FileKind, IncludeOffset));
669 }
670 LineTable.AddEntry(FID, Entries);
671 }
672
673 return false;
674}
675
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000676namespace {
677
678class VISIBILITY_HIDDEN PCHStatData {
679public:
680 const bool hasStat;
681 const ino_t ino;
682 const dev_t dev;
683 const mode_t mode;
684 const time_t mtime;
685 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000687 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000688 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
689
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000690 PCHStatData()
691 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
692};
693
694class VISIBILITY_HIDDEN PCHStatLookupTrait {
695 public:
696 typedef const char *external_key_type;
697 typedef const char *internal_key_type;
698
699 typedef PCHStatData data_type;
700
701 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000702 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000703 }
704
705 static internal_key_type GetInternalKey(const char *path) { return path; }
706
707 static bool EqualKey(internal_key_type a, internal_key_type b) {
708 return strcmp(a, b) == 0;
709 }
710
711 static std::pair<unsigned, unsigned>
712 ReadKeyDataLength(const unsigned char*& d) {
713 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
714 unsigned DataLen = (unsigned) *d++;
715 return std::make_pair(KeyLen + 1, DataLen);
716 }
717
718 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
719 return (const char *)d;
720 }
721
722 static data_type ReadData(const internal_key_type, const unsigned char *d,
723 unsigned /*DataLen*/) {
724 using namespace clang::io;
725
726 if (*d++ == 1)
727 return data_type();
728
729 ino_t ino = (ino_t) ReadUnalignedLE32(d);
730 dev_t dev = (dev_t) ReadUnalignedLE32(d);
731 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000732 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000733 off_t size = (off_t) ReadUnalignedLE64(d);
734 return data_type(ino, dev, mode, mtime, size);
735 }
736};
737
738/// \brief stat() cache for precompiled headers.
739///
740/// This cache is very similar to the stat cache used by pretokenized
741/// headers.
742class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
743 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
744 CacheTy *Cache;
745
746 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000747public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000748 PCHStatCache(const unsigned char *Buckets,
749 const unsigned char *Base,
750 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000751 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000752 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
753 Cache = CacheTy::Create(Buckets, Base);
754 }
755
756 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000758 int stat(const char *path, struct stat *buf) {
759 // Do the lookup for the file's data in the PCH file.
760 CacheTy::iterator I = Cache->find(path);
761
762 // If we don't get a hit in the PCH file just forward to 'stat'.
763 if (I == Cache->end()) {
764 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000765 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000768 ++NumStatHits;
769 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000771 if (!Data.hasStat)
772 return 1;
773
774 buf->st_ino = Data.ino;
775 buf->st_dev = Data.dev;
776 buf->st_mtime = Data.mtime;
777 buf->st_mode = Data.mode;
778 buf->st_size = Data.size;
779 return 0;
780 }
781};
782} // end anonymous namespace
783
784
Douglas Gregor14f79002009-04-10 03:52:48 +0000785/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000786PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000787 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000788
789 // Set the source-location entry cursor to the current position in
790 // the stream. This cursor will be used to read the contents of the
791 // source manager block initially, and then lazily read
792 // source-location entries as needed.
793 SLocEntryCursor = Stream;
794
795 // The stream itself is going to skip over the source manager block.
796 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000797 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000798 return Failure;
799 }
800
801 // Enter the source manager block.
802 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000803 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000804 return Failure;
805 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000806
Douglas Gregor14f79002009-04-10 03:52:48 +0000807 RecordData Record;
808 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000809 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000810 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000811 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000812 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000813 return Failure;
814 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000815 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor14f79002009-04-10 03:52:48 +0000818 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
819 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000820 SLocEntryCursor.ReadSubBlockID();
821 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000822 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000823 return Failure;
824 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000825 continue;
826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Douglas Gregor14f79002009-04-10 03:52:48 +0000828 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000829 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000830 continue;
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregor14f79002009-04-10 03:52:48 +0000833 // Read a record.
834 const char *BlobStart;
835 unsigned BlobLen;
836 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000837 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000838 default: // Default behavior: ignore.
839 break;
840
Chris Lattner2c78b872009-04-14 23:22:57 +0000841 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000842 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000843 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000844 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000845
846 case pch::SM_HEADER_FILE_INFO: {
847 HeaderFileInfo HFI;
848 HFI.isImport = Record[0];
849 HFI.DirInfo = Record[1];
850 HFI.NumIncludes = Record[2];
851 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000852 if (Listener)
853 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000854 break;
855 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000856
857 case pch::SM_SLOC_FILE_ENTRY:
858 case pch::SM_SLOC_BUFFER_ENTRY:
859 case pch::SM_SLOC_INSTANTIATION_ENTRY:
860 // Once we hit one of the source location entries, we're done.
861 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000862 }
863 }
864}
865
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000866/// \brief Read in the source location entry with the given ID.
867PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
868 if (ID == 0)
869 return Success;
870
871 if (ID > TotalNumSLocEntries) {
872 Error("source location entry ID out-of-range for PCH file");
873 return Failure;
874 }
875
876 ++NumSLocEntriesRead;
877 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
878 unsigned Code = SLocEntryCursor.ReadCode();
879 if (Code == llvm::bitc::END_BLOCK ||
880 Code == llvm::bitc::ENTER_SUBBLOCK ||
881 Code == llvm::bitc::DEFINE_ABBREV) {
882 Error("incorrectly-formatted source location entry in PCH file");
883 return Failure;
884 }
885
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000886 RecordData Record;
887 const char *BlobStart;
888 unsigned BlobLen;
889 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
890 default:
891 Error("incorrectly-formatted source location entry in PCH file");
892 return Failure;
893
894 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000895 std::string Filename(BlobStart, BlobStart + BlobLen);
896 MaybeAddSystemRootToFilename(Filename);
897 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000898 if (File == 0) {
899 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000900 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000901 ErrorStr += "' referenced by PCH file";
902 Error(ErrorStr.c_str());
903 return Failure;
904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000906 FileID FID = SourceMgr.createFileID(File,
907 SourceLocation::getFromRawEncoding(Record[1]),
908 (SrcMgr::CharacteristicKind)Record[2],
909 ID, Record[0]);
910 if (Record[3])
911 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
912 .setHasLineDirectives();
913
914 break;
915 }
916
917 case pch::SM_SLOC_BUFFER_ENTRY: {
918 const char *Name = BlobStart;
919 unsigned Offset = Record[0];
920 unsigned Code = SLocEntryCursor.ReadCode();
921 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000922 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000923 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
924 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
925 (void)RecCode;
926 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000927 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000928 BlobStart + BlobLen - 1,
929 Name);
930 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregor92b059e2009-04-28 20:33:11 +0000932 if (strcmp(Name, "<built-in>") == 0) {
933 PCHPredefinesBufferID = BufferID;
934 PCHPredefines = BlobStart;
935 PCHPredefinesLen = BlobLen - 1;
936 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000937
938 break;
939 }
940
941 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000942 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000943 = SourceLocation::getFromRawEncoding(Record[1]);
944 SourceMgr.createInstantiationLoc(SpellingLoc,
945 SourceLocation::getFromRawEncoding(Record[2]),
946 SourceLocation::getFromRawEncoding(Record[3]),
947 Record[4],
948 ID,
949 Record[0]);
950 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000951 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000952 }
953
954 return Success;
955}
956
Chris Lattner6367f6d2009-04-27 01:05:14 +0000957/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
958/// specified cursor. Read the abbreviations that are at the top of the block
959/// and then leave the cursor pointing into the block.
960bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
961 unsigned BlockID) {
962 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000963 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000964 return Failure;
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattner6367f6d2009-04-27 01:05:14 +0000967 while (true) {
968 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner6367f6d2009-04-27 01:05:14 +0000970 // We expect all abbrevs to be at the start of the block.
971 if (Code != llvm::bitc::DEFINE_ABBREV)
972 return false;
973 Cursor.ReadAbbrevRecord();
974 }
975}
976
Douglas Gregor37e26842009-04-21 23:56:24 +0000977void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000978 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor37e26842009-04-21 23:56:24 +0000980 // Keep track of where we are in the stream, then jump back there
981 // after reading this macro.
982 SavedStreamPosition SavedPosition(Stream);
983
984 Stream.JumpToBit(Offset);
985 RecordData Record;
986 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
987 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregor37e26842009-04-21 23:56:24 +0000989 while (true) {
990 unsigned Code = Stream.ReadCode();
991 switch (Code) {
992 case llvm::bitc::END_BLOCK:
993 return;
994
995 case llvm::bitc::ENTER_SUBBLOCK:
996 // No known subblocks, always skip them.
997 Stream.ReadSubBlockID();
998 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000999 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001000 return;
1001 }
1002 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregor37e26842009-04-21 23:56:24 +00001004 case llvm::bitc::DEFINE_ABBREV:
1005 Stream.ReadAbbrevRecord();
1006 continue;
1007 default: break;
1008 }
1009
1010 // Read a record.
1011 Record.clear();
1012 pch::PreprocessorRecordTypes RecType =
1013 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1014 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001015 case pch::PP_MACRO_OBJECT_LIKE:
1016 case pch::PP_MACRO_FUNCTION_LIKE: {
1017 // If we already have a macro, that means that we've hit the end
1018 // of the definition of the macro we were looking for. We're
1019 // done.
1020 if (Macro)
1021 return;
1022
1023 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1024 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001025 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001026 return;
1027 }
1028 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1029 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001031 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001032 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregor37e26842009-04-21 23:56:24 +00001034 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1035 // Decode function-like macro info.
1036 bool isC99VarArgs = Record[3];
1037 bool isGNUVarArgs = Record[4];
1038 MacroArgs.clear();
1039 unsigned NumArgs = Record[5];
1040 for (unsigned i = 0; i != NumArgs; ++i)
1041 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1042
1043 // Install function-like macro info.
1044 MI->setIsFunctionLike();
1045 if (isC99VarArgs) MI->setIsC99Varargs();
1046 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001047 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001048 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001049 }
1050
1051 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001052 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001053
1054 // Remember that we saw this macro last so that we add the tokens that
1055 // form its body to it.
1056 Macro = MI;
1057 ++NumMacrosRead;
1058 break;
1059 }
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Douglas Gregor37e26842009-04-21 23:56:24 +00001061 case pch::PP_TOKEN: {
1062 // If we see a TOKEN before a PP_MACRO_*, then the file is
1063 // erroneous, just pretend we didn't see this.
1064 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor37e26842009-04-21 23:56:24 +00001066 Token Tok;
1067 Tok.startToken();
1068 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1069 Tok.setLength(Record[1]);
1070 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1071 Tok.setIdentifierInfo(II);
1072 Tok.setKind((tok::TokenKind)Record[3]);
1073 Tok.setFlag((Token::TokenFlags)Record[4]);
1074 Macro->AddTokenToBody(Tok);
1075 break;
1076 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001077 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001078 }
1079}
1080
Douglas Gregore650c8c2009-07-07 00:12:59 +00001081/// \brief If we are loading a relocatable PCH file, and the filename is
1082/// not an absolute path, add the system root to the beginning of the file
1083/// name.
1084void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1085 // If this is not a relocatable PCH file, there's nothing to do.
1086 if (!RelocatablePCH)
1087 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregore650c8c2009-07-07 00:12:59 +00001089 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1090 return;
1091
1092 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Douglas Gregore650c8c2009-07-07 00:12:59 +00001094 if (isysroot == 0) {
1095 // If no system root was given, default to '/'
1096 Filename.insert(Filename.begin(), '/');
1097 return;
1098 }
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregore650c8c2009-07-07 00:12:59 +00001100 unsigned Length = strlen(isysroot);
1101 if (isysroot[Length - 1] != '/')
1102 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Douglas Gregore650c8c2009-07-07 00:12:59 +00001104 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1105}
1106
Mike Stump1eb44332009-09-09 15:08:12 +00001107PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001108PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001109 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001110 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001111 return Failure;
1112 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001113
1114 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001115 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001116 while (!Stream.AtEndOfStream()) {
1117 unsigned Code = Stream.ReadCode();
1118 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001119 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001120 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001121 return Failure;
1122 }
Chris Lattner7356a312009-04-11 21:15:38 +00001123
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001124 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001125 }
1126
1127 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1128 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001129 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001130 // We lazily load the decls block, but we want to set up the
1131 // DeclsCursor cursor to point into it. Clone our current bitcode
1132 // cursor to it, enter the block and read the abbrevs in that block.
1133 // With the main cursor, we just skip over it.
1134 DeclsCursor = Stream;
1135 if (Stream.SkipBlock() || // Skip with the main cursor.
1136 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001137 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001138 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001139 return Failure;
1140 }
1141 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner7356a312009-04-11 21:15:38 +00001143 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001144 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001145 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001146 return Failure;
1147 }
1148 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001149
Douglas Gregor14f79002009-04-10 03:52:48 +00001150 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001151 switch (ReadSourceManagerBlock()) {
1152 case Success:
1153 break;
1154
1155 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001156 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001157 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001158
1159 case IgnorePCH:
1160 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001161 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001162 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001163 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001164 continue;
1165 }
1166
1167 if (Code == llvm::bitc::DEFINE_ABBREV) {
1168 Stream.ReadAbbrevRecord();
1169 continue;
1170 }
1171
1172 // Read and process a record.
1173 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001174 const char *BlobStart = 0;
1175 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001176 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001177 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001178 default: // Default behavior: ignore.
1179 break;
1180
1181 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001182 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001183 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001184 return Failure;
1185 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001186 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001187 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001188 break;
1189
1190 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001191 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001192 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001193 return Failure;
1194 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001195 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001196 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001197 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001198
1199 case pch::LANGUAGE_OPTIONS:
1200 if (ParseLanguageOptions(Record))
1201 return IgnorePCH;
1202 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001203
Douglas Gregorab41e632009-04-27 22:23:34 +00001204 case pch::METADATA: {
1205 if (Record[0] != pch::VERSION_MAJOR) {
1206 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1207 : diag::warn_pch_version_too_new);
1208 return IgnorePCH;
1209 }
1210
Douglas Gregore650c8c2009-07-07 00:12:59 +00001211 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001212 if (Listener) {
1213 std::string TargetTriple(BlobStart, BlobLen);
1214 if (Listener->ReadTargetTriple(TargetTriple))
1215 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001216 }
1217 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001218 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001219
1220 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001221 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001222 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001223 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001224 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001225 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001226 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001227 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001228 if (PP)
1229 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001230 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001231 break;
1232
1233 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001234 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001235 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001236 return Failure;
1237 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001238 IdentifierOffsets = (const uint32_t *)BlobStart;
1239 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001240 if (PP)
1241 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001242 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001243
1244 case pch::EXTERNAL_DEFINITIONS:
1245 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001246 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001247 return Failure;
1248 }
1249 ExternalDefinitions.swap(Record);
1250 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001251
Douglas Gregorad1de002009-04-18 05:55:16 +00001252 case pch::SPECIAL_TYPES:
1253 SpecialTypes.swap(Record);
1254 break;
1255
Douglas Gregor3e1af842009-04-17 22:13:46 +00001256 case pch::STATISTICS:
1257 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001258 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001259 TotalLexicalDeclContexts = Record[2];
1260 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001261 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001262
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001263 case pch::TENTATIVE_DEFINITIONS:
1264 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001265 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001266 return Failure;
1267 }
1268 TentativeDefinitions.swap(Record);
1269 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001270
1271 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1272 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001273 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001274 return Failure;
1275 }
1276 LocallyScopedExternalDecls.swap(Record);
1277 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001278
Douglas Gregor83941df2009-04-25 17:48:32 +00001279 case pch::SELECTOR_OFFSETS:
1280 SelectorOffsets = (const uint32_t *)BlobStart;
1281 TotalNumSelectors = Record[0];
1282 SelectorsLoaded.resize(TotalNumSelectors);
1283 break;
1284
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001285 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001286 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1287 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001288 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001289 = PCHMethodPoolLookupTable::Create(
1290 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001291 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001292 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001293 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001294 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001295
1296 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001297 if (!Record.empty() && Listener)
1298 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001299 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001300
1301 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001302 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001303 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001304 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001305 break;
1306
1307 case pch::SOURCE_LOCATION_PRELOADS:
1308 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1309 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1310 if (Result != Success)
1311 return Result;
1312 }
1313 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001314
Douglas Gregor52e71082009-10-16 18:18:30 +00001315 case pch::STAT_CACHE: {
1316 PCHStatCache *MyStatCache =
1317 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1318 (const unsigned char *)BlobStart,
1319 NumStatHits, NumStatMisses);
1320 FileMgr.addStatCache(MyStatCache);
1321 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001322 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001323 }
1324
Douglas Gregorb81c1702009-04-27 20:06:05 +00001325 case pch::EXT_VECTOR_DECLS:
1326 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001327 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001328 return Failure;
1329 }
1330 ExtVectorDecls.swap(Record);
1331 break;
1332
Douglas Gregorb64c1932009-05-12 01:31:05 +00001333 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001334 ActualOriginalFileName.assign(BlobStart, BlobLen);
1335 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001336 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001337 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Douglas Gregor2e222532009-07-02 17:08:52 +00001339 case pch::COMMENT_RANGES:
1340 Comments = (SourceRange *)BlobStart;
1341 NumComments = BlobLen / sizeof(SourceRange);
1342 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001343
1344 case pch::SVN_BRANCH_REVISION: {
1345 unsigned CurRevision = getClangSubversionRevision();
1346 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1347 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1348 : diag::warn_pch_version_too_new);
1349 return IgnorePCH;
1350 }
1351
1352 const char *CurBranch = getClangSubversionPath();
1353 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1354 std::string PCHBranch(BlobStart, BlobLen);
1355 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1356 return IgnorePCH;
1357 }
1358 break;
1359 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001360 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001361 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001362 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001363 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001364}
1365
Douglas Gregore1d918e2009-04-10 23:10:45 +00001366PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001367 // Set the PCH file name.
1368 this->FileName = FileName;
1369
Douglas Gregor2cf26342009-04-09 22:27:44 +00001370 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001371 //
1372 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001373 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001374 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001375 if (!Buffer) {
1376 Error(ErrStr.c_str());
1377 return IgnorePCH;
1378 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001379
1380 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001381 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001382 (const unsigned char *)Buffer->getBufferEnd());
1383 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001384
1385 // Sniff for the signature.
1386 if (Stream.Read(8) != 'C' ||
1387 Stream.Read(8) != 'P' ||
1388 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001389 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001390 Diag(diag::err_not_a_pch_file) << FileName;
1391 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001392 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001393
Douglas Gregor2cf26342009-04-09 22:27:44 +00001394 while (!Stream.AtEndOfStream()) {
1395 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Douglas Gregore1d918e2009-04-10 23:10:45 +00001397 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001398 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001399 return Failure;
1400 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001401
1402 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001403
Douglas Gregor2cf26342009-04-09 22:27:44 +00001404 // We only know the PCH subblock ID.
1405 switch (BlockID) {
1406 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001407 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001408 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001409 return Failure;
1410 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001411 break;
1412 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001413 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001414 case Success:
1415 break;
1416
1417 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001418 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001419
1420 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001421 // FIXME: We could consider reading through to the end of this
1422 // PCH block, skipping subblocks, to see if there are other
1423 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001424
1425 // Clear out any preallocated source location entries, so that
1426 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001427 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001428
1429 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001430 if (StatCache)
1431 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001432
Douglas Gregore1d918e2009-04-10 23:10:45 +00001433 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001434 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001435 break;
1436 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001437 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001438 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001439 return Failure;
1440 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001441 break;
1442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443 }
1444
Douglas Gregor92b059e2009-04-28 20:33:11 +00001445 // Check the predefines buffer.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +00001446 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregor92b059e2009-04-28 20:33:11 +00001447 PCHPredefinesBufferID))
1448 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001450 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001451 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001452 // PCH file is read, so there may be some identifiers that were
1453 // loaded into the IdentifierTable before we intercepted the
1454 // creation of identifiers. Iterate through the list of known
1455 // identifiers and determine whether we have to establish
1456 // preprocessor definitions or top-level identifier declaration
1457 // chains for those identifiers.
1458 //
1459 // We copy the IdentifierInfo pointers to a small vector first,
1460 // since de-serializing declarations or macro definitions can add
1461 // new entries into the identifier table, invalidating the
1462 // iterators.
1463 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1464 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1465 IdEnd = PP->getIdentifierTable().end();
1466 Id != IdEnd; ++Id)
1467 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001468 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001469 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1470 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1471 IdentifierInfo *II = Identifiers[I];
1472 // Look in the on-disk hash table for an entry for
1473 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001474 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001475 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1476 if (Pos == IdTable->end())
1477 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001479 // Dereferencing the iterator has the effect of populating the
1480 // IdentifierInfo node with the various declarations it needs.
1481 (void)*Pos;
1482 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001483 }
1484
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001485 if (Context)
1486 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001487
Douglas Gregor668c1a42009-04-21 22:25:48 +00001488 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001489}
1490
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001491void PCHReader::InitializeContext(ASTContext &Ctx) {
1492 Context = &Ctx;
1493 assert(Context && "Passed null context!");
1494
1495 assert(PP && "Forgot to set Preprocessor ?");
1496 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1497 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001499 // Load the translation unit declaration
1500 ReadDeclRecord(DeclOffsets[0], 0);
1501
1502 // Load the special types.
1503 Context->setBuiltinVaListType(
1504 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1505 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1506 Context->setObjCIdType(GetType(Id));
1507 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1508 Context->setObjCSelType(GetType(Sel));
1509 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1510 Context->setObjCProtoType(GetType(Proto));
1511 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1512 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001513
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001514 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1515 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001516 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001517 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1518 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001519 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1520 QualType FileType = GetType(File);
1521 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001522 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001523 Context->setFILEDecl(Typedef->getDecl());
1524 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001525 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001526 assert(Tag && "Invalid FILE type in PCH file");
1527 Context->setFILEDecl(Tag->getDecl());
1528 }
1529 }
Mike Stump782fa302009-07-28 02:25:19 +00001530 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1531 QualType Jmp_bufType = GetType(Jmp_buf);
1532 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001533 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001534 Context->setjmp_bufDecl(Typedef->getDecl());
1535 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001536 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001537 assert(Tag && "Invalid jmp_bug type in PCH file");
1538 Context->setjmp_bufDecl(Tag->getDecl());
1539 }
1540 }
1541 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1542 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1543 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001544 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001545 Context->setsigjmp_bufDecl(Typedef->getDecl());
1546 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001547 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001548 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1549 Context->setsigjmp_bufDecl(Tag->getDecl());
1550 }
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001553 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1554 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001555 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001556 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1557 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001558 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1559 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001560 if (unsigned String
1561 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1562 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001563}
1564
Douglas Gregorb64c1932009-05-12 01:31:05 +00001565/// \brief Retrieve the name of the original source file name
1566/// directly from the PCH file, without actually loading the PCH
1567/// file.
1568std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1569 // Open the PCH file.
1570 std::string ErrStr;
1571 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1572 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1573 if (!Buffer) {
1574 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1575 return std::string();
1576 }
1577
1578 // Initialize the stream
1579 llvm::BitstreamReader StreamFile;
1580 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001581 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001582 (const unsigned char *)Buffer->getBufferEnd());
1583 Stream.init(StreamFile);
1584
1585 // Sniff for the signature.
1586 if (Stream.Read(8) != 'C' ||
1587 Stream.Read(8) != 'P' ||
1588 Stream.Read(8) != 'C' ||
1589 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001590 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001591 "error: '%s' does not appear to be a precompiled header file\n",
1592 PCHFileName.c_str());
1593 return std::string();
1594 }
1595
1596 RecordData Record;
1597 while (!Stream.AtEndOfStream()) {
1598 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Douglas Gregorb64c1932009-05-12 01:31:05 +00001600 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1601 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Douglas Gregorb64c1932009-05-12 01:31:05 +00001603 // We only know the PCH subblock ID.
1604 switch (BlockID) {
1605 case pch::PCH_BLOCK_ID:
1606 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1607 fprintf(stderr, "error: malformed block record in PCH file\n");
1608 return std::string();
1609 }
1610 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregorb64c1932009-05-12 01:31:05 +00001612 default:
1613 if (Stream.SkipBlock()) {
1614 fprintf(stderr, "error: malformed block record in PCH file\n");
1615 return std::string();
1616 }
1617 break;
1618 }
1619 continue;
1620 }
1621
1622 if (Code == llvm::bitc::END_BLOCK) {
1623 if (Stream.ReadBlockEnd()) {
1624 fprintf(stderr, "error: error at end of module block in PCH file\n");
1625 return std::string();
1626 }
1627 continue;
1628 }
1629
1630 if (Code == llvm::bitc::DEFINE_ABBREV) {
1631 Stream.ReadAbbrevRecord();
1632 continue;
1633 }
1634
1635 Record.clear();
1636 const char *BlobStart = 0;
1637 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001638 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001639 == pch::ORIGINAL_FILE_NAME)
1640 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001641 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001642
1643 return std::string();
1644}
1645
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001646/// \brief Parse the record that corresponds to a LangOptions data
1647/// structure.
1648///
1649/// This routine compares the language options used to generate the
1650/// PCH file against the language options set for the current
1651/// compilation. For each option, we classify differences between the
1652/// two compiler states as either "benign" or "important". Benign
1653/// differences don't matter, and we accept them without complaint
1654/// (and without modifying the language options). Differences between
1655/// the states for important options cause the PCH file to be
1656/// unusable, so we emit a warning and return true to indicate that
1657/// there was an error.
1658///
1659/// \returns true if the PCH file is unacceptable, false otherwise.
1660bool PCHReader::ParseLanguageOptions(
1661 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001662 if (Listener) {
1663 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001665 #define PARSE_LANGOPT(Option) \
1666 LangOpts.Option = Record[Idx]; \
1667 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001669 unsigned Idx = 0;
1670 PARSE_LANGOPT(Trigraphs);
1671 PARSE_LANGOPT(BCPLComment);
1672 PARSE_LANGOPT(DollarIdents);
1673 PARSE_LANGOPT(AsmPreprocessor);
1674 PARSE_LANGOPT(GNUMode);
1675 PARSE_LANGOPT(ImplicitInt);
1676 PARSE_LANGOPT(Digraphs);
1677 PARSE_LANGOPT(HexFloats);
1678 PARSE_LANGOPT(C99);
1679 PARSE_LANGOPT(Microsoft);
1680 PARSE_LANGOPT(CPlusPlus);
1681 PARSE_LANGOPT(CPlusPlus0x);
1682 PARSE_LANGOPT(CXXOperatorNames);
1683 PARSE_LANGOPT(ObjC1);
1684 PARSE_LANGOPT(ObjC2);
1685 PARSE_LANGOPT(ObjCNonFragileABI);
1686 PARSE_LANGOPT(PascalStrings);
1687 PARSE_LANGOPT(WritableStrings);
1688 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001689 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001690 PARSE_LANGOPT(Exceptions);
1691 PARSE_LANGOPT(NeXTRuntime);
1692 PARSE_LANGOPT(Freestanding);
1693 PARSE_LANGOPT(NoBuiltin);
1694 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001695 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001696 PARSE_LANGOPT(Blocks);
1697 PARSE_LANGOPT(EmitAllDecls);
1698 PARSE_LANGOPT(MathErrno);
1699 PARSE_LANGOPT(OverflowChecking);
1700 PARSE_LANGOPT(HeinousExtensions);
1701 PARSE_LANGOPT(Optimize);
1702 PARSE_LANGOPT(OptimizeSize);
1703 PARSE_LANGOPT(Static);
1704 PARSE_LANGOPT(PICLevel);
1705 PARSE_LANGOPT(GNUInline);
1706 PARSE_LANGOPT(NoInline);
1707 PARSE_LANGOPT(AccessControl);
1708 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001709 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001710 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1711 ++Idx;
1712 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1713 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001714 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1715 Record[Idx]);
1716 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001717 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001718 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001719 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001720
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001721 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001722 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001723
1724 return false;
1725}
1726
Douglas Gregor2e222532009-07-02 17:08:52 +00001727void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1728 Comments.resize(NumComments);
1729 std::copy(this->Comments, this->Comments + NumComments,
1730 Comments.begin());
1731}
1732
Douglas Gregor2cf26342009-04-09 22:27:44 +00001733/// \brief Read and return the type at the given offset.
1734///
1735/// This routine actually reads the record corresponding to the type
1736/// at the given offset in the bitstream. It is a helper routine for
1737/// GetType, which deals with reading type IDs.
1738QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001739 // Keep track of where we are in the stream, then jump back there
1740 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001741 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001742
Douglas Gregord89275b2009-07-06 18:54:52 +00001743 // Note that we are loading a type record.
1744 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001746 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001747 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001748 unsigned Code = DeclsCursor.ReadCode();
1749 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001750 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001751 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001752 "Incorrect encoding of extended qualifier type");
1753 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001754 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1755 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001756 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001757
Douglas Gregor2cf26342009-04-09 22:27:44 +00001758 case pch::TYPE_FIXED_WIDTH_INT: {
1759 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001760 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001761 }
1762
1763 case pch::TYPE_COMPLEX: {
1764 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1765 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001766 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767 }
1768
1769 case pch::TYPE_POINTER: {
1770 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1771 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001772 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773 }
1774
1775 case pch::TYPE_BLOCK_POINTER: {
1776 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1777 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001778 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001779 }
1780
1781 case pch::TYPE_LVALUE_REFERENCE: {
1782 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1783 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001784 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001785 }
1786
1787 case pch::TYPE_RVALUE_REFERENCE: {
1788 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1789 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001790 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791 }
1792
1793 case pch::TYPE_MEMBER_POINTER: {
1794 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1795 QualType PointeeType = GetType(Record[0]);
1796 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001797 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001798 }
1799
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001800 case pch::TYPE_CONSTANT_ARRAY: {
1801 QualType ElementType = GetType(Record[0]);
1802 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1803 unsigned IndexTypeQuals = Record[2];
1804 unsigned Idx = 3;
1805 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001806 return Context->getConstantArrayType(ElementType, Size,
1807 ASM, IndexTypeQuals);
1808 }
1809
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001810 case pch::TYPE_INCOMPLETE_ARRAY: {
1811 QualType ElementType = GetType(Record[0]);
1812 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1813 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001814 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001815 }
1816
1817 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001818 QualType ElementType = GetType(Record[0]);
1819 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1820 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001821 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1822 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001823 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001824 ASM, IndexTypeQuals,
1825 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001826 }
1827
1828 case pch::TYPE_VECTOR: {
1829 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001830 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001831 return QualType();
1832 }
1833
1834 QualType ElementType = GetType(Record[0]);
1835 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001836 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001837 }
1838
1839 case pch::TYPE_EXT_VECTOR: {
1840 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001841 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001842 return QualType();
1843 }
1844
1845 QualType ElementType = GetType(Record[0]);
1846 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001847 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001848 }
1849
1850 case pch::TYPE_FUNCTION_NO_PROTO: {
1851 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001852 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001853 return QualType();
1854 }
1855 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001856 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001857 }
1858
1859 case pch::TYPE_FUNCTION_PROTO: {
1860 QualType ResultType = GetType(Record[0]);
1861 unsigned Idx = 1;
1862 unsigned NumParams = Record[Idx++];
1863 llvm::SmallVector<QualType, 16> ParamTypes;
1864 for (unsigned I = 0; I != NumParams; ++I)
1865 ParamTypes.push_back(GetType(Record[Idx++]));
1866 bool isVariadic = Record[Idx++];
1867 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001868 bool hasExceptionSpec = Record[Idx++];
1869 bool hasAnyExceptionSpec = Record[Idx++];
1870 unsigned NumExceptions = Record[Idx++];
1871 llvm::SmallVector<QualType, 2> Exceptions;
1872 for (unsigned I = 0; I != NumExceptions; ++I)
1873 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001874 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001875 isVariadic, Quals, hasExceptionSpec,
1876 hasAnyExceptionSpec, NumExceptions,
1877 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001878 }
1879
1880 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001881 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001882 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001883
1884 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001885 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001886
1887 case pch::TYPE_TYPEOF: {
1888 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001889 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001890 return QualType();
1891 }
1892 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001893 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Anders Carlsson395b4752009-06-24 19:06:50 +00001896 case pch::TYPE_DECLTYPE:
1897 return Context->getDecltypeType(ReadTypeExpr());
1898
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001899 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001900 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001901 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001902
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001903 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001904 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001905 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001906
John McCall7da24312009-09-05 00:15:47 +00001907 case pch::TYPE_ELABORATED: {
1908 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1909 unsigned Tag = Record[1];
1910 return Context->getElaboratedType(GetType(Record[0]),
1911 (ElaboratedType::TagKind) Tag);
1912 }
1913
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001914 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001915 unsigned Idx = 0;
1916 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1917 unsigned NumProtos = Record[Idx++];
1918 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1919 for (unsigned I = 0; I != NumProtos; ++I)
1920 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001921 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001922 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001923
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001924 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001925 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001926 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001927 unsigned NumProtos = Record[Idx++];
1928 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1929 for (unsigned I = 0; I != NumProtos; ++I)
1930 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001931 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001932 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001933
John McCall49a832b2009-10-18 09:09:24 +00001934 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1935 unsigned Idx = 0;
1936 QualType Parm = GetType(Record[Idx++]);
1937 QualType Replacement = GetType(Record[Idx++]);
1938 return
1939 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1940 Replacement);
1941 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001942 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001943 // Suppress a GCC warning
1944 return QualType();
1945}
1946
John McCalla1ee0c52009-10-16 21:56:05 +00001947namespace {
1948
1949class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1950 PCHReader &Reader;
1951 const PCHReader::RecordData &Record;
1952 unsigned &Idx;
1953
1954public:
1955 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1956 unsigned &Idx)
1957 : Reader(Reader), Record(Record), Idx(Idx) { }
1958
John McCall51bd8032009-10-18 01:05:36 +00001959 // We want compile-time assurance that we've enumerated all of
1960 // these, so unfortunately we have to declare them first, then
1961 // define them out-of-line.
1962#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00001963#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00001964 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001965#include "clang/AST/TypeLocNodes.def"
1966
John McCall51bd8032009-10-18 01:05:36 +00001967 void VisitFunctionTypeLoc(FunctionTypeLoc);
1968 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001969};
1970
1971}
1972
John McCall51bd8032009-10-18 01:05:36 +00001973void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00001974 // nothing to do
1975}
John McCall51bd8032009-10-18 01:05:36 +00001976void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1977 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001978}
John McCall51bd8032009-10-18 01:05:36 +00001979void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1980 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001981}
John McCall51bd8032009-10-18 01:05:36 +00001982void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1983 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001984}
John McCall51bd8032009-10-18 01:05:36 +00001985void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1986 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001987}
John McCall51bd8032009-10-18 01:05:36 +00001988void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1989 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001990}
John McCall51bd8032009-10-18 01:05:36 +00001991void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1992 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001993}
John McCall51bd8032009-10-18 01:05:36 +00001994void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1995 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001996}
John McCall51bd8032009-10-18 01:05:36 +00001997void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1998 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001999}
John McCall51bd8032009-10-18 01:05:36 +00002000void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2001 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2002 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002003 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002004 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002005 else
John McCall51bd8032009-10-18 01:05:36 +00002006 TL.setSizeExpr(0);
2007}
2008void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2009 VisitArrayTypeLoc(TL);
2010}
2011void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2012 VisitArrayTypeLoc(TL);
2013}
2014void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2015 VisitArrayTypeLoc(TL);
2016}
2017void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2018 DependentSizedArrayTypeLoc TL) {
2019 VisitArrayTypeLoc(TL);
2020}
2021void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2022 DependentSizedExtVectorTypeLoc TL) {
2023 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2024}
2025void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2026 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2027}
2028void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2029 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2030}
2031void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2032 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2033 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2034 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002035 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002036 }
2037}
2038void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2039 VisitFunctionTypeLoc(TL);
2040}
2041void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2042 VisitFunctionTypeLoc(TL);
2043}
2044void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2045 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2046}
2047void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2048 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2049}
2050void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2051 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2052}
2053void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2054 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2055}
2056void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2057 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2058}
2059void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2060 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2061}
2062void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2063 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2064}
2065void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2066 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
John McCall49a832b2009-10-18 09:09:24 +00002068void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2069 SubstTemplateTypeParmTypeLoc TL) {
2070 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2071}
John McCall51bd8032009-10-18 01:05:36 +00002072void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2073 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002074 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2075 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2076 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2077 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2078 TL.setArgLocInfo(i,
2079 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2080 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002081}
2082void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2083 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2084}
2085void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2086 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2087}
2088void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2089 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002090 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2091 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2093 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002094}
John McCall54e14c42009-10-22 22:37:11 +00002095void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2096 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2099 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2100 TL.setHasProtocolsAsWritten(Record[Idx++]);
2101 if (TL.hasProtocolsAsWritten())
2102 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2103 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2104}
John McCalla1ee0c52009-10-16 21:56:05 +00002105
2106DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2107 unsigned &Idx) {
2108 QualType InfoTy = GetType(Record[Idx++]);
2109 if (InfoTy.isNull())
2110 return 0;
2111
2112 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2113 TypeLocReader TLR(*this, Record, Idx);
2114 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2115 TLR.Visit(TL);
2116 return DInfo;
2117}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002118
Douglas Gregor8038d512009-04-10 17:25:41 +00002119QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002120 unsigned FastQuals = ID & Qualifiers::FastMask;
2121 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002122
2123 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2124 QualType T;
2125 switch ((pch::PredefinedTypeIDs)Index) {
2126 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002127 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2128 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002129
2130 case pch::PREDEF_TYPE_CHAR_U_ID:
2131 case pch::PREDEF_TYPE_CHAR_S_ID:
2132 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002133 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002134 break;
2135
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002136 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2137 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2138 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2139 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2140 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002141 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002142 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2143 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2144 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2145 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2146 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2147 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002148 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002149 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2150 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2151 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2152 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2153 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002154 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002155 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2156 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002157 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2158 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002159 }
2160
2161 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002162 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002163 }
2164
2165 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002166 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002167 if (TypesLoaded[Index].isNull())
2168 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002169
John McCall0953e762009-09-24 19:53:00 +00002170 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002171}
2172
John McCall833ca992009-10-29 08:12:44 +00002173TemplateArgumentLocInfo
2174PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2175 const RecordData &Record,
2176 unsigned &Index) {
2177 switch (Kind) {
2178 case TemplateArgument::Expression:
2179 return ReadDeclExpr();
2180 case TemplateArgument::Type:
2181 return GetDeclaratorInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002182 case TemplateArgument::Template: {
2183 SourceLocation
2184 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2185 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2186 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2187 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2188 TemplateNameLoc);
2189 }
John McCall833ca992009-10-29 08:12:44 +00002190 case TemplateArgument::Null:
2191 case TemplateArgument::Integral:
2192 case TemplateArgument::Declaration:
2193 case TemplateArgument::Pack:
2194 return TemplateArgumentLocInfo();
2195 }
2196 llvm::llvm_unreachable("unexpected template argument loc");
2197 return TemplateArgumentLocInfo();
2198}
2199
Douglas Gregor8038d512009-04-10 17:25:41 +00002200Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002201 if (ID == 0)
2202 return 0;
2203
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002204 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002205 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002206 return 0;
2207 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002208
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002209 unsigned Index = ID - 1;
2210 if (!DeclsLoaded[Index])
2211 ReadDeclRecord(DeclOffsets[Index], Index);
2212
2213 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002214}
2215
Chris Lattner887e2b32009-04-27 05:46:25 +00002216/// \brief Resolve the offset of a statement into a statement.
2217///
2218/// This operation will read a new statement from the external
2219/// source each time it is called, and is meant to be used via a
2220/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2221Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002222 // Since we know tha this statement is part of a decl, make sure to use the
2223 // decl cursor to read it.
2224 DeclsCursor.JumpToBit(Offset);
2225 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002226}
2227
Douglas Gregor2cf26342009-04-09 22:27:44 +00002228bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002229 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002230 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002231 "DeclContext has no lexical decls in storage");
2232 uint64_t Offset = DeclContextOffsets[DC].first;
2233 assert(Offset && "DeclContext has no lexical decls in storage");
2234
Douglas Gregor0b748912009-04-14 21:18:50 +00002235 // Keep track of where we are in the stream, then jump back there
2236 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002237 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002238
Douglas Gregor2cf26342009-04-09 22:27:44 +00002239 // Load the record containing all of the declarations lexically in
2240 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002241 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002243 unsigned Code = DeclsCursor.ReadCode();
2244 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002245 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002246 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2247
2248 // Load all of the declaration IDs
2249 Decls.clear();
2250 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002251 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002252 return false;
2253}
2254
2255bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002256 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002257 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002258 "DeclContext has no visible decls in storage");
2259 uint64_t Offset = DeclContextOffsets[DC].second;
2260 assert(Offset && "DeclContext has no visible decls in storage");
2261
Douglas Gregor0b748912009-04-14 21:18:50 +00002262 // Keep track of where we are in the stream, then jump back there
2263 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002264 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002265
Douglas Gregor2cf26342009-04-09 22:27:44 +00002266 // Load the record containing all of the declarations visible in
2267 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002268 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002269 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002270 unsigned Code = DeclsCursor.ReadCode();
2271 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002272 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002273 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2274 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002275 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002276
2277 Decls.clear();
2278
2279 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002280 while (Idx < Record.size()) {
2281 Decls.push_back(VisibleDeclaration());
2282 Decls.back().Name = ReadDeclarationName(Record, Idx);
2283
Douglas Gregor2cf26342009-04-09 22:27:44 +00002284 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002285 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002286 LoadedDecls.reserve(Size);
2287 for (unsigned I = 0; I < Size; ++I)
2288 LoadedDecls.push_back(Record[Idx++]);
2289 }
2290
Douglas Gregor25123082009-04-22 22:34:57 +00002291 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002292 return false;
2293}
2294
Douglas Gregorfdd01722009-04-14 00:24:19 +00002295void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002296 this->Consumer = Consumer;
2297
Douglas Gregorfdd01722009-04-14 00:24:19 +00002298 if (!Consumer)
2299 return;
2300
2301 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002302 // Force deserialization of this decl, which will cause it to be passed to
2303 // the consumer (or queued).
2304 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002305 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002306
2307 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2308 DeclGroupRef DG(InterestingDecls[I]);
2309 Consumer->HandleTopLevelDecl(DG);
2310 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002311}
2312
Douglas Gregor2cf26342009-04-09 22:27:44 +00002313void PCHReader::PrintStats() {
2314 std::fprintf(stderr, "*** PCH Statistics:\n");
2315
Mike Stump1eb44332009-09-09 15:08:12 +00002316 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002317 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002318 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002319 unsigned NumDeclsLoaded
2320 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2321 (Decl *)0);
2322 unsigned NumIdentifiersLoaded
2323 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2324 IdentifiersLoaded.end(),
2325 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002326 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002327 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2328 SelectorsLoaded.end(),
2329 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002330
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002331 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2332 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002333 if (TotalNumSLocEntries)
2334 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2335 NumSLocEntriesRead, TotalNumSLocEntries,
2336 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002337 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002338 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002339 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2340 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2341 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002342 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002343 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2344 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002345 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002346 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002347 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2348 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002349 if (TotalNumSelectors)
2350 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2351 NumSelectorsLoaded, TotalNumSelectors,
2352 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2353 if (TotalNumStatements)
2354 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2355 NumStatementsRead, TotalNumStatements,
2356 ((float)NumStatementsRead/TotalNumStatements * 100));
2357 if (TotalNumMacros)
2358 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2359 NumMacrosRead, TotalNumMacros,
2360 ((float)NumMacrosRead/TotalNumMacros * 100));
2361 if (TotalLexicalDeclContexts)
2362 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2363 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2364 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2365 * 100));
2366 if (TotalVisibleDeclContexts)
2367 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2368 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2369 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2370 * 100));
2371 if (TotalSelectorsInMethodPool) {
2372 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2373 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2374 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2375 * 100));
2376 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2377 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002378 std::fprintf(stderr, "\n");
2379}
2380
Douglas Gregor668c1a42009-04-21 22:25:48 +00002381void PCHReader::InitializeSema(Sema &S) {
2382 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002383 S.ExternalSource = this;
2384
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002385 // Makes sure any declarations that were deserialized "too early"
2386 // still get added to the identifier's declaration chains.
2387 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2388 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2389 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002390 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002391 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002392
2393 // If there were any tentative definitions, deserialize them and add
2394 // them to Sema's table of tentative definitions.
2395 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2396 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2397 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002398 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002399 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002400
2401 // If there were any locally-scoped external declarations,
2402 // deserialize them and add them to Sema's table of locally-scoped
2403 // external declarations.
2404 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2405 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2406 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2407 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002408
2409 // If there were any ext_vector type declarations, deserialize them
2410 // and add them to Sema's vector of such declarations.
2411 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2412 SemaObj->ExtVectorDecls.push_back(
2413 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002414}
2415
2416IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2417 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002418 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002419 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2420 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2421 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2422 if (Pos == IdTable->end())
2423 return 0;
2424
2425 // Dereferencing the iterator has the effect of building the
2426 // IdentifierInfo node and populating it with the various
2427 // declarations it needs.
2428 return *Pos;
2429}
2430
Mike Stump1eb44332009-09-09 15:08:12 +00002431std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002432PCHReader::ReadMethodPool(Selector Sel) {
2433 if (!MethodPoolLookupTable)
2434 return std::pair<ObjCMethodList, ObjCMethodList>();
2435
2436 // Try to find this selector within our on-disk hash table.
2437 PCHMethodPoolLookupTable *PoolTable
2438 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2439 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002440 if (Pos == PoolTable->end()) {
2441 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002442 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002443 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002444
Douglas Gregor83941df2009-04-25 17:48:32 +00002445 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002446 return *Pos;
2447}
2448
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002449void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002450 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002451 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002452 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002453}
2454
Douglas Gregord89275b2009-07-06 18:54:52 +00002455/// \brief Set the globally-visible declarations associated with the given
2456/// identifier.
2457///
2458/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002459/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002460/// them.
2461///
2462/// \param II an IdentifierInfo that refers to one or more globally-visible
2463/// declarations.
2464///
2465/// \param DeclIDs the set of declaration IDs with the name @p II that are
2466/// visible at global scope.
2467///
2468/// \param Nonrecursive should be true to indicate that the caller knows that
2469/// this call is non-recursive, and therefore the globally-visible declarations
2470/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002471void
2472PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002473 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2474 bool Nonrecursive) {
2475 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2476 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2477 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2478 PII.II = II;
2479 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2480 PII.DeclIDs.push_back(DeclIDs[I]);
2481 return;
2482 }
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Douglas Gregord89275b2009-07-06 18:54:52 +00002484 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2485 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2486 if (SemaObj) {
2487 // Introduce this declaration into the translation-unit scope
2488 // and add it to the declaration chain for this identifier, so
2489 // that (unqualified) name lookup will find it.
2490 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2491 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2492 } else {
2493 // Queue this declaration so that it will be added to the
2494 // translation unit scope and identifier's declaration chain
2495 // once a Sema object is known.
2496 PreloadedDecls.push_back(D);
2497 }
2498 }
2499}
2500
Chris Lattner7356a312009-04-11 21:15:38 +00002501IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002502 if (ID == 0)
2503 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002505 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002506 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002507 return 0;
2508 }
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002510 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002511 if (!IdentifiersLoaded[ID - 1]) {
2512 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002513 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002514
Douglas Gregor02fc7512009-04-28 20:01:51 +00002515 // All of the strings in the PCH file are preceded by a 16-bit
2516 // length. Extract that 16-bit length to avoid having to execute
2517 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002518 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2519 // unsigned integers. This is important to avoid integer overflow when
2520 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002521 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002522 unsigned StrLen = (((unsigned) StrLenPtr[0])
2523 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002524 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002525 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002526 }
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002528 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002529}
2530
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002531void PCHReader::ReadSLocEntry(unsigned ID) {
2532 ReadSLocEntryRecord(ID);
2533}
2534
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002535Selector PCHReader::DecodeSelector(unsigned ID) {
2536 if (ID == 0)
2537 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Douglas Gregora02b1472009-04-28 21:53:25 +00002539 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002540 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002541
2542 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002543 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002544 return Selector();
2545 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002546
2547 unsigned Index = ID - 1;
2548 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2549 // Load this selector from the selector table.
2550 // FIXME: endianness portability issues with SelectorOffsets table
2551 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002552 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002553 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2554 }
2555
2556 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002557}
2558
Mike Stump1eb44332009-09-09 15:08:12 +00002559DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002560PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2561 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2562 switch (Kind) {
2563 case DeclarationName::Identifier:
2564 return DeclarationName(GetIdentifierInfo(Record, Idx));
2565
2566 case DeclarationName::ObjCZeroArgSelector:
2567 case DeclarationName::ObjCOneArgSelector:
2568 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002569 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002570
2571 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002572 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002573 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002574
2575 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002576 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002577 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002578
2579 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002580 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002581 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002582
2583 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002584 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002585 (OverloadedOperatorKind)Record[Idx++]);
2586
2587 case DeclarationName::CXXUsingDirective:
2588 return DeclarationName::getUsingDirectiveName();
2589 }
2590
2591 // Required to silence GCC warning
2592 return DeclarationName();
2593}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002594
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002595/// \brief Read an integral value
2596llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2597 unsigned BitWidth = Record[Idx++];
2598 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2599 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2600 Idx += NumWords;
2601 return Result;
2602}
2603
2604/// \brief Read a signed integral value
2605llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2606 bool isUnsigned = Record[Idx++];
2607 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2608}
2609
Douglas Gregor17fc2232009-04-14 21:55:33 +00002610/// \brief Read a floating-point value
2611llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002612 return llvm::APFloat(ReadAPInt(Record, Idx));
2613}
2614
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002615// \brief Read a string
2616std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2617 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002618 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002619 Idx += Len;
2620 return Result;
2621}
2622
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002623DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002624 return Diag(SourceLocation(), DiagID);
2625}
2626
2627DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002628 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002629}
Douglas Gregor025452f2009-04-17 00:04:06 +00002630
Douglas Gregor668c1a42009-04-21 22:25:48 +00002631/// \brief Retrieve the identifier table associated with the
2632/// preprocessor.
2633IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002634 assert(PP && "Forgot to set Preprocessor ?");
2635 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002636}
2637
Douglas Gregor025452f2009-04-17 00:04:06 +00002638/// \brief Record that the given ID maps to the given switch-case
2639/// statement.
2640void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2641 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2642 SwitchCaseStmts[ID] = SC;
2643}
2644
2645/// \brief Retrieve the switch-case statement with the given ID.
2646SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2647 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2648 return SwitchCaseStmts[ID];
2649}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002650
2651/// \brief Record that the given label statement has been
2652/// deserialized and has the given ID.
2653void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002654 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002655 "Deserialized label twice");
2656 LabelStmts[ID] = S;
2657
2658 // If we've already seen any goto statements that point to this
2659 // label, resolve them now.
2660 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2661 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2662 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2663 Goto->second->setLabel(S);
2664 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002665
2666 // If we've already seen any address-label statements that point to
2667 // this label, resolve them now.
2668 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002669 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002670 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002671 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002672 AddrLabel != AddrLabels.second; ++AddrLabel)
2673 AddrLabel->second->setLabel(S);
2674 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002675}
2676
2677/// \brief Set the label of the given statement to the label
2678/// identified by ID.
2679///
2680/// Depending on the order in which the label and other statements
2681/// referencing that label occur, this operation may complete
2682/// immediately (updating the statement) or it may queue the
2683/// statement to be back-patched later.
2684void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2685 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2686 if (Label != LabelStmts.end()) {
2687 // We've already seen this label, so set the label of the goto and
2688 // we're done.
2689 S->setLabel(Label->second);
2690 } else {
2691 // We haven't seen this label yet, so add this goto to the set of
2692 // unresolved goto statements.
2693 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2694 }
2695}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002696
2697/// \brief Set the label of the given expression to the label
2698/// identified by ID.
2699///
2700/// Depending on the order in which the label and other statements
2701/// referencing that label occur, this operation may complete
2702/// immediately (updating the statement) or it may queue the
2703/// statement to be back-patched later.
2704void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2705 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2706 if (Label != LabelStmts.end()) {
2707 // We've already seen this label, so set the label of the
2708 // label-address expression and we're done.
2709 S->setLabel(Label->second);
2710 } else {
2711 // We haven't seen this label yet, so add this label-address
2712 // expression to the set of unresolved label-address expressions.
2713 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2714 }
2715}
Douglas Gregord89275b2009-07-06 18:54:52 +00002716
2717
Mike Stump1eb44332009-09-09 15:08:12 +00002718PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002719 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2720 Reader.CurrentlyLoadingTypeOrDecl = this;
2721}
2722
2723PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2724 if (!Parent) {
2725 // If any identifiers with corresponding top-level declarations have
2726 // been loaded, load those declarations now.
2727 while (!Reader.PendingIdentifierInfos.empty()) {
2728 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2729 Reader.PendingIdentifierInfos.front().DeclIDs,
2730 true);
2731 Reader.PendingIdentifierInfos.pop_front();
2732 }
2733 }
2734
Mike Stump1eb44332009-09-09 15:08:12 +00002735 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002736}