blob: 40eb9ca536d711f536a7b2659d358d845966f90b [file] [log] [blame]
Douglas Gregoref84c4b2009-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 Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000036#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-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 Stump11289f42009-09-09 15:08:12 +000077 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000078 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000079 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-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 Stump11289f42009-09-09 15:08:12 +000084 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000085 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000086 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-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 Stump11289f42009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-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 Thompsoned4e2952009-11-05 20:14:16 +0000108 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000109 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000110 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000111 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112 return true;
113 }
114 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000115 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000117 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000118 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000119 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000120#undef PARSE_LANGOPT_IRRELEVANT
121#undef PARSE_LANGOPT_BENIGN
122
123 return false;
124}
125
Daniel Dunbar20a682d2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000133}
134
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000135bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000136 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000137 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000138 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-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 Dunbar000c4ff2009-11-11 05:29:04 +0000143 llvm::SmallString<256> PCHInclude;
144 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000145 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000155 return false;
156
157 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Daniel Dunbar8665c7e2009-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 Dunbar045f917e2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000167
Daniel Dunbar499baed2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000170 std::sort(CmdLineLines.begin(), CmdLineLines.end());
171 std::sort(PCHLines.begin(), PCHLines.end());
172
Daniel Dunbar499baed2009-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 Kyrtzidis366985d2009-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 Dunbar499baed2009-11-11 05:26:28 +0000183 llvm::StringRef Missing = MissingPredefines[I];
184 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000185 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
186 return true;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000189 // This is a macro definition. Determine the name of the macro we're
190 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000191 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000192 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-11-11 05:26:28 +0000196 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000197
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000198 // Determine whether this macro was given a different definition on the
199 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000200 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000201 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000202 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000203 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
204 MacroDefStart);
205 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000206 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000207 // Different macro; we're done.
208 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000209 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
212 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000213 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000214 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000215 (*ConflictPos)[MacroDefLen] != '(')
216 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000217
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000218 // We found a conflicting macro definition.
219 break;
220 }
Mike Stump11289f42009-09-09 15:08:12 +0000221
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000232
233 ConflictingDefines = true;
234 continue;
235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
Daniel Dunbar8665c7e2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000239 if (ConflictingDefines)
240 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000241
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000251 .getFileLocWithOffset(Offset);
252 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000255 if (ConflictingDefines)
256 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000257
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-11-11 05:26:28 +0000262 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000263 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
264 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000265 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000266 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000267 llvm::StringRef &Extra = ExtraPredefines[I];
268 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-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 Stump11289f42009-09-09 15:08:12 +0000276 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-11-11 05:26:28 +0000280 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-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 Dunbar499baed2009-11-11 05:26:28 +0000285 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000286 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000308//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000309// PCH reader implementation
310//===----------------------------------------------------------------------===//
311
Mike Stump11289f42009-09-09 15:08:12 +0000312PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
313 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000314 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
315 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000316 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000317 IdentifierTableData(0), IdentifierLookupTable(0),
318 IdentifierOffsets(0),
319 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
320 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000321 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000322 NumStatHits(0), NumStatMisses(0),
323 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000324 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000325 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000326 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000327 RelocatablePCH = false;
328}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000329
330PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000331 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000333 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000334 IdentifierTableData(0), IdentifierLookupTable(0),
335 IdentifierOffsets(0),
336 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
337 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000338 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000339 NumStatHits(0), NumStatMisses(0),
340 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000341 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000342 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000343 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000344 RelocatablePCH = false;
345}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000346
347PCHReader::~PCHReader() {}
348
Chris Lattner1de76db2009-04-27 05:58:23 +0000349Expr *PCHReader::ReadDeclExpr() {
350 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
351}
352
353Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000354 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000355}
356
357
Douglas Gregora868bbd2009-04-21 22:25:48 +0000358namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000359class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000360 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 Stump11289f42009-09-09 15:08:12 +0000369
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000374
Douglas Gregorc78d3462009-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 Dunbarf8502d52009-10-17 23:52:28 +0000382 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000383 return R;
384 }
Mike Stump11289f42009-09-09 15:08:12 +0000385
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000389
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000397
Douglas Gregor95c13f52009-04-25 17:48:32 +0000398 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000399 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000400 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000401 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000402 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-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 Gregor038c3382009-05-22 22:45:36 +0000414 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000427 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000443 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-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 Stump11289f42009-09-09 15:08:12 +0000459
460} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000461
462/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000463typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000464 PCHMethodPoolLookupTable;
465
466namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000467class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000468 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 Stump11289f42009-09-09 15:08:12 +0000482 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000483 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000484
Douglas Gregora868bbd2009-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 Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregora868bbd2009-04-21 22:25:48 +0000491 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000492 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000493 }
Mike Stump11289f42009-09-09 15:08:12 +0000494
Douglas Gregora868bbd2009-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 Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregora868bbd2009-04-21 22:25:48 +0000499 static std::pair<unsigned, unsigned>
500 ReadKeyDataLength(const unsigned char*& d) {
501 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000502 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000503 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000504 return std::make_pair(KeyLen, DataLen);
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregora868bbd2009-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 Stump11289f42009-09-09 15:08:12 +0000512
513 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000514 const unsigned char* d,
515 unsigned DataLen) {
516 using namespace clang::io;
Douglas Gregor1d583f22009-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 Gregorb9256522009-04-28 21:32:13 +0000534 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-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 Stump11289f42009-09-09 15:08:12 +0000545
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000546 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000547 DataLen -= 6;
Douglas Gregora868bbd2009-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 Gregor6b7bf5a2009-04-25 20:26:24 +0000553 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
554 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000555 Reader.SetIdentifierInfo(ID, II);
556
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000557 // Set or check the various bits in the IdentifierInfo structure.
558 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000559 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000560 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-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 Gregorc3366a52009-04-21 23:56:24 +0000568 // If this identifier is a macro, deserialize the macro
569 // definition.
570 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000571 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000572 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000573 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000574 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000575
576 // Read all of the declarations visible at global scope with this
577 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000578 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-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 Gregora868bbd2009-04-21 22:25:48 +0000584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
Douglas Gregora868bbd2009-04-21 22:25:48 +0000586 return II;
587 }
588};
Mike Stump11289f42009-09-09 15:08:12 +0000589
590} // end anonymous namespace
Douglas Gregora868bbd2009-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 Stump11289f42009-09-09 15:08:12 +0000594typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000595 PCHIdentifierLookupTable;
596
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000597bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000598 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
599 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000600 return true;
601}
602
Douglas Gregor92863e42009-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 Dunbar20a682d2009-11-11 00:52:11 +0000620bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000621 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000622 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000623 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000624 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000625 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000626 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000627}
628
Douglas Gregorc5046832009-04-27 18:38:38 +0000629//===----------------------------------------------------------------------===//
630// Source Manager Deserialization
631//===----------------------------------------------------------------------===//
632
Douglas Gregor4c7626e2009-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 Gregor0086a5a2009-07-07 00:12:59 +0000635bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000636 unsigned Idx = 0;
637 LineTableInfo &LineTable = SourceMgr.getLineTable();
638
639 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000640 std::map<int, int> FileIDs;
641 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-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 Gregor0086a5a2009-07-07 00:12:59 +0000646 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000647 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000648 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000649 }
650
651 // Parse the line entries
652 std::vector<LineEntry> Entries;
653 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000654 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-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 Stump11289f42009-09-09 15:08:12 +0000664 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-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 Gregorc5046832009-04-27 18:38:38 +0000676namespace {
677
Benjamin Kramer16634c22009-11-28 10:07:24 +0000678class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000679public:
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 Stump11289f42009-09-09 15:08:12 +0000686
Douglas Gregorc5046832009-04-27 18:38:38 +0000687 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000688 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
689
Douglas Gregorc5046832009-04-27 18:38:38 +0000690 PCHStatData()
691 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
692};
693
Benjamin Kramer16634c22009-11-28 10:07:24 +0000694class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000695 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 Dunbarf8502d52009-10-17 23:52:28 +0000702 return llvm::HashString(path);
Douglas Gregorc5046832009-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 Stump11289f42009-09-09 15:08:12 +0000732 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-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.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000742class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000743 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
744 CacheTy *Cache;
745
746 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000747public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000748 PCHStatCache(const unsigned char *Buckets,
749 const unsigned char *Base,
750 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000751 unsigned &NumStatMisses)
Douglas Gregorc5046832009-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 Stump11289f42009-09-09 15:08:12 +0000757
Douglas Gregorc5046832009-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 Gregord2eb58a2009-10-16 18:18:30 +0000765 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Douglas Gregorc5046832009-04-27 18:38:38 +0000768 ++NumStatHits;
769 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000770
Douglas Gregorc5046832009-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 Gregora7f71a92009-04-10 03:52:48 +0000785/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000786PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000787 using namespace SrcMgr;
Douglas Gregor258ae542009-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 Gregor6f00bf82009-04-28 21:53:25 +0000797 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-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 Gregor6f00bf82009-04-28 21:53:25 +0000803 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000804 return Failure;
805 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000806
Douglas Gregora7f71a92009-04-10 03:52:48 +0000807 RecordData Record;
808 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000809 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000810 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000811 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000812 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000813 return Failure;
814 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000815 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000816 }
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregora7f71a92009-04-10 03:52:48 +0000818 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
819 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000820 SLocEntryCursor.ReadSubBlockID();
821 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000822 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000823 return Failure;
824 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000825 continue;
826 }
Mike Stump11289f42009-09-09 15:08:12 +0000827
Douglas Gregora7f71a92009-04-10 03:52:48 +0000828 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000829 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000830 continue;
831 }
Mike Stump11289f42009-09-09 15:08:12 +0000832
Douglas Gregora7f71a92009-04-10 03:52:48 +0000833 // Read a record.
834 const char *BlobStart;
835 unsigned BlobLen;
836 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000837 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000838 default: // Default behavior: ignore.
839 break;
840
Chris Lattner184e65d2009-04-14 23:22:57 +0000841 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000842 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000843 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000844 break;
Douglas Gregoreda6a892009-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 Kyrtzidis366985d2009-06-19 00:03:23 +0000852 if (Listener)
853 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000854 break;
855 }
Douglas Gregor258ae542009-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 Gregora7f71a92009-04-10 03:52:48 +0000862 }
863 }
864}
865
Douglas Gregor258ae542009-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 Gregor258ae542009-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 Gregor0086a5a2009-07-07 00:12:59 +0000895 std::string Filename(BlobStart, BlobStart + BlobLen);
896 MaybeAddSystemRootToFilename(Filename);
897 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000898 if (File == 0) {
899 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000900 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000901 ErrorStr += "' referenced by PCH file";
902 Error(ErrorStr.c_str());
903 return Failure;
904 }
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregor258ae542009-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 Stump11289f42009-09-09 15:08:12 +0000922 unsigned RecCode
Douglas Gregor258ae542009-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 Stump11289f42009-09-09 15:08:12 +0000927 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000928 BlobStart + BlobLen - 1,
929 Name);
930 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregore6648fb2009-04-28 20:33:11 +0000932 if (strcmp(Name, "<built-in>") == 0) {
933 PCHPredefinesBufferID = BufferID;
934 PCHPredefines = BlobStart;
935 PCHPredefinesLen = BlobLen - 1;
936 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000937
938 break;
939 }
940
941 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000942 SourceLocation SpellingLoc
Douglas Gregor258ae542009-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 Stump11289f42009-09-09 15:08:12 +0000951 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000952 }
953
954 return Success;
955}
956
Chris Lattnere78a6be2009-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 Gregor6f00bf82009-04-28 21:53:25 +0000963 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000964 return Failure;
965 }
Mike Stump11289f42009-09-09 15:08:12 +0000966
Chris Lattnere78a6be2009-04-27 01:05:14 +0000967 while (true) {
968 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000969
Chris Lattnere78a6be2009-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 Gregorc3366a52009-04-21 23:56:24 +0000977void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000978 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregorc3366a52009-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 Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregorc3366a52009-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 Gregor6f00bf82009-04-28 21:53:25 +0000999 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001000 return;
1001 }
1002 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001003
Douglas Gregorc3366a52009-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 Gregorc3366a52009-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 Gregor6f00bf82009-04-28 21:53:25 +00001025 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001026 return;
1027 }
1028 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1029 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001030
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001031 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001032 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001033
Douglas Gregorc3366a52009-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 Gregor038c3382009-05-22 22:45:36 +00001047 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001048 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001049 }
1050
1051 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001052 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-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 Stump11289f42009-09-09 15:08:12 +00001060
Douglas Gregorc3366a52009-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 Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregorc3366a52009-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 Naroff3fa455a2009-04-24 20:03:17 +00001077 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001078 }
1079}
1080
Douglas Gregor0086a5a2009-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 Stump11289f42009-09-09 15:08:12 +00001088
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001089 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001090 return;
1091
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001092 if (isysroot == 0) {
1093 // If no system root was given, default to '/'
1094 Filename.insert(Filename.begin(), '/');
1095 return;
1096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001098 unsigned Length = strlen(isysroot);
1099 if (isysroot[Length - 1] != '/')
1100 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001101
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001102 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1103}
1104
Mike Stump11289f42009-09-09 15:08:12 +00001105PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001106PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001107 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001108 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001109 return Failure;
1110 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001111
1112 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001113 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001114 while (!Stream.AtEndOfStream()) {
1115 unsigned Code = Stream.ReadCode();
1116 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001117 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001118 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001119 return Failure;
1120 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001121
Douglas Gregor55abb232009-04-10 20:39:37 +00001122 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001123 }
1124
1125 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1126 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001127 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001128 // We lazily load the decls block, but we want to set up the
1129 // DeclsCursor cursor to point into it. Clone our current bitcode
1130 // cursor to it, enter the block and read the abbrevs in that block.
1131 // With the main cursor, we just skip over it.
1132 DeclsCursor = Stream;
1133 if (Stream.SkipBlock() || // Skip with the main cursor.
1134 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001135 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001136 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001137 return Failure;
1138 }
1139 break;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001141 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001142 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001143 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001144 return Failure;
1145 }
1146 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001147
Douglas Gregora7f71a92009-04-10 03:52:48 +00001148 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001149 switch (ReadSourceManagerBlock()) {
1150 case Success:
1151 break;
1152
1153 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001154 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001155 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001156
1157 case IgnorePCH:
1158 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001159 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001160 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001161 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001162 continue;
1163 }
1164
1165 if (Code == llvm::bitc::DEFINE_ABBREV) {
1166 Stream.ReadAbbrevRecord();
1167 continue;
1168 }
1169
1170 // Read and process a record.
1171 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001172 const char *BlobStart = 0;
1173 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001174 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001175 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001176 default: // Default behavior: ignore.
1177 break;
1178
1179 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001180 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001181 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001182 return Failure;
1183 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001184 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001185 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001186 break;
1187
1188 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001189 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001190 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001191 return Failure;
1192 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001193 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001194 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001195 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001196
1197 case pch::LANGUAGE_OPTIONS:
1198 if (ParseLanguageOptions(Record))
1199 return IgnorePCH;
1200 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001201
Douglas Gregor7b71e632009-04-27 22:23:34 +00001202 case pch::METADATA: {
1203 if (Record[0] != pch::VERSION_MAJOR) {
1204 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1205 : diag::warn_pch_version_too_new);
1206 return IgnorePCH;
1207 }
1208
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001209 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001210 if (Listener) {
1211 std::string TargetTriple(BlobStart, BlobLen);
1212 if (Listener->ReadTargetTriple(TargetTriple))
1213 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001214 }
1215 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001216 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001217
1218 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001219 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001220 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001221 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001222 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001223 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001224 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001225 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001226 if (PP)
1227 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001228 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001229 break;
1230
1231 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001232 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001233 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001234 return Failure;
1235 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001236 IdentifierOffsets = (const uint32_t *)BlobStart;
1237 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001238 if (PP)
1239 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001240 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001241
1242 case pch::EXTERNAL_DEFINITIONS:
1243 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001244 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001245 return Failure;
1246 }
1247 ExternalDefinitions.swap(Record);
1248 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001249
Douglas Gregor652d82a2009-04-18 05:55:16 +00001250 case pch::SPECIAL_TYPES:
1251 SpecialTypes.swap(Record);
1252 break;
1253
Douglas Gregor08f01292009-04-17 22:13:46 +00001254 case pch::STATISTICS:
1255 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001256 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001257 TotalLexicalDeclContexts = Record[2];
1258 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001259 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001260
Douglas Gregord4df8652009-04-22 22:02:47 +00001261 case pch::TENTATIVE_DEFINITIONS:
1262 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001263 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001264 return Failure;
1265 }
1266 TentativeDefinitions.swap(Record);
1267 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001268
1269 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1270 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001271 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001272 return Failure;
1273 }
1274 LocallyScopedExternalDecls.swap(Record);
1275 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001276
Douglas Gregor95c13f52009-04-25 17:48:32 +00001277 case pch::SELECTOR_OFFSETS:
1278 SelectorOffsets = (const uint32_t *)BlobStart;
1279 TotalNumSelectors = Record[0];
1280 SelectorsLoaded.resize(TotalNumSelectors);
1281 break;
1282
Douglas Gregorc78d3462009-04-24 21:10:55 +00001283 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001284 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1285 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001286 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001287 = PCHMethodPoolLookupTable::Create(
1288 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001289 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001290 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001291 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001292 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001293
1294 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001295 if (!Record.empty() && Listener)
1296 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001297 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001298
1299 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001300 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001301 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001302 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001303 break;
1304
1305 case pch::SOURCE_LOCATION_PRELOADS:
1306 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1307 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1308 if (Result != Success)
1309 return Result;
1310 }
1311 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001312
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001313 case pch::STAT_CACHE: {
1314 PCHStatCache *MyStatCache =
1315 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1316 (const unsigned char *)BlobStart,
1317 NumStatHits, NumStatMisses);
1318 FileMgr.addStatCache(MyStatCache);
1319 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001320 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001321 }
1322
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001323 case pch::EXT_VECTOR_DECLS:
1324 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001325 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001326 return Failure;
1327 }
1328 ExtVectorDecls.swap(Record);
1329 break;
1330
Douglas Gregor45fe0362009-05-12 01:31:05 +00001331 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001332 ActualOriginalFileName.assign(BlobStart, BlobLen);
1333 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001334 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001335 break;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001337 case pch::COMMENT_RANGES:
1338 Comments = (SourceRange *)BlobStart;
1339 NumComments = BlobLen / sizeof(SourceRange);
1340 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001341
1342 case pch::SVN_BRANCH_REVISION: {
1343 unsigned CurRevision = getClangSubversionRevision();
1344 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1345 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1346 : diag::warn_pch_version_too_new);
1347 return IgnorePCH;
1348 }
1349
1350 const char *CurBranch = getClangSubversionPath();
1351 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1352 std::string PCHBranch(BlobStart, BlobLen);
1353 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1354 return IgnorePCH;
1355 }
1356 break;
1357 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001358 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001359 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001360 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001361 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001362}
1363
Douglas Gregor92863e42009-04-10 23:10:45 +00001364PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001365 // Set the PCH file name.
1366 this->FileName = FileName;
1367
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001368 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001369 //
1370 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001371 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001372 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001373 if (!Buffer) {
1374 Error(ErrStr.c_str());
1375 return IgnorePCH;
1376 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001377
1378 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001379 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001380 (const unsigned char *)Buffer->getBufferEnd());
1381 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001382
1383 // Sniff for the signature.
1384 if (Stream.Read(8) != 'C' ||
1385 Stream.Read(8) != 'P' ||
1386 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001387 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001388 Diag(diag::err_not_a_pch_file) << FileName;
1389 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001390 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001391
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001392 while (!Stream.AtEndOfStream()) {
1393 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001394
Douglas Gregor92863e42009-04-10 23:10:45 +00001395 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001396 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001397 return Failure;
1398 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001399
1400 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001401
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001402 // We only know the PCH subblock ID.
1403 switch (BlockID) {
1404 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001405 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001406 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001407 return Failure;
1408 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001409 break;
1410 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001411 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001412 case Success:
1413 break;
1414
1415 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001416 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001417
1418 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001419 // FIXME: We could consider reading through to the end of this
1420 // PCH block, skipping subblocks, to see if there are other
1421 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001422
1423 // Clear out any preallocated source location entries, so that
1424 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001425 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001426
1427 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001428 if (StatCache)
1429 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001430
Douglas Gregor92863e42009-04-10 23:10:45 +00001431 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001432 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001433 break;
1434 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001435 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001436 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001437 return Failure;
1438 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001439 break;
1440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441 }
1442
Douglas Gregore6648fb2009-04-28 20:33:11 +00001443 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001444 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001445 PCHPredefinesBufferID))
1446 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001448 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001449 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001450 // PCH file is read, so there may be some identifiers that were
1451 // loaded into the IdentifierTable before we intercepted the
1452 // creation of identifiers. Iterate through the list of known
1453 // identifiers and determine whether we have to establish
1454 // preprocessor definitions or top-level identifier declaration
1455 // chains for those identifiers.
1456 //
1457 // We copy the IdentifierInfo pointers to a small vector first,
1458 // since de-serializing declarations or macro definitions can add
1459 // new entries into the identifier table, invalidating the
1460 // iterators.
1461 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1462 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1463 IdEnd = PP->getIdentifierTable().end();
1464 Id != IdEnd; ++Id)
1465 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001466 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001467 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1468 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1469 IdentifierInfo *II = Identifiers[I];
1470 // Look in the on-disk hash table for an entry for
1471 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001472 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001473 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1474 if (Pos == IdTable->end())
1475 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001476
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001477 // Dereferencing the iterator has the effect of populating the
1478 // IdentifierInfo node with the various declarations it needs.
1479 (void)*Pos;
1480 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001481 }
1482
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001483 if (Context)
1484 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001485
Douglas Gregora868bbd2009-04-21 22:25:48 +00001486 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001487}
1488
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001489void PCHReader::InitializeContext(ASTContext &Ctx) {
1490 Context = &Ctx;
1491 assert(Context && "Passed null context!");
1492
1493 assert(PP && "Forgot to set Preprocessor ?");
1494 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1495 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump11289f42009-09-09 15:08:12 +00001496
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001497 // Load the translation unit declaration
1498 ReadDeclRecord(DeclOffsets[0], 0);
1499
1500 // Load the special types.
1501 Context->setBuiltinVaListType(
1502 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1503 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1504 Context->setObjCIdType(GetType(Id));
1505 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1506 Context->setObjCSelType(GetType(Sel));
1507 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1508 Context->setObjCProtoType(GetType(Proto));
1509 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1510 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001511
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001512 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1513 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001514 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001515 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1516 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001517 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1518 QualType FileType = GetType(File);
1519 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001520 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001521 Context->setFILEDecl(Typedef->getDecl());
1522 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001523 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001524 assert(Tag && "Invalid FILE type in PCH file");
1525 Context->setFILEDecl(Tag->getDecl());
1526 }
1527 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001528 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1529 QualType Jmp_bufType = GetType(Jmp_buf);
1530 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001531 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001532 Context->setjmp_bufDecl(Typedef->getDecl());
1533 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001534 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001535 assert(Tag && "Invalid jmp_bug type in PCH file");
1536 Context->setjmp_bufDecl(Tag->getDecl());
1537 }
1538 }
1539 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1540 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1541 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001542 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001543 Context->setsigjmp_bufDecl(Typedef->getDecl());
1544 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001545 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001546 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1547 Context->setsigjmp_bufDecl(Tag->getDecl());
1548 }
1549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001551 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1552 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001553 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001554 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1555 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001556#if 0
1557 // FIXME. Accommodate for this in several PCH/Index tests
1558 if (unsigned ObjCSelRedef
1559 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001560 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001561#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001562 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1563 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001564 if (unsigned String
1565 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1566 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001567}
1568
Douglas Gregor45fe0362009-05-12 01:31:05 +00001569/// \brief Retrieve the name of the original source file name
1570/// directly from the PCH file, without actually loading the PCH
1571/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001572std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1573 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001574 // Open the PCH file.
1575 std::string ErrStr;
1576 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1577 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1578 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001579 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001580 return std::string();
1581 }
1582
1583 // Initialize the stream
1584 llvm::BitstreamReader StreamFile;
1585 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001586 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001587 (const unsigned char *)Buffer->getBufferEnd());
1588 Stream.init(StreamFile);
1589
1590 // Sniff for the signature.
1591 if (Stream.Read(8) != 'C' ||
1592 Stream.Read(8) != 'P' ||
1593 Stream.Read(8) != 'C' ||
1594 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001595 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001596 return std::string();
1597 }
1598
1599 RecordData Record;
1600 while (!Stream.AtEndOfStream()) {
1601 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001602
Douglas Gregor45fe0362009-05-12 01:31:05 +00001603 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1604 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregor45fe0362009-05-12 01:31:05 +00001606 // We only know the PCH subblock ID.
1607 switch (BlockID) {
1608 case pch::PCH_BLOCK_ID:
1609 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001610 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001611 return std::string();
1612 }
1613 break;
Mike Stump11289f42009-09-09 15:08:12 +00001614
Douglas Gregor45fe0362009-05-12 01:31:05 +00001615 default:
1616 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001617 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001618 return std::string();
1619 }
1620 break;
1621 }
1622 continue;
1623 }
1624
1625 if (Code == llvm::bitc::END_BLOCK) {
1626 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001627 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001628 return std::string();
1629 }
1630 continue;
1631 }
1632
1633 if (Code == llvm::bitc::DEFINE_ABBREV) {
1634 Stream.ReadAbbrevRecord();
1635 continue;
1636 }
1637
1638 Record.clear();
1639 const char *BlobStart = 0;
1640 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001641 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001642 == pch::ORIGINAL_FILE_NAME)
1643 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001644 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001645
1646 return std::string();
1647}
1648
Douglas Gregor55abb232009-04-10 20:39:37 +00001649/// \brief Parse the record that corresponds to a LangOptions data
1650/// structure.
1651///
1652/// This routine compares the language options used to generate the
1653/// PCH file against the language options set for the current
1654/// compilation. For each option, we classify differences between the
1655/// two compiler states as either "benign" or "important". Benign
1656/// differences don't matter, and we accept them without complaint
1657/// (and without modifying the language options). Differences between
1658/// the states for important options cause the PCH file to be
1659/// unusable, so we emit a warning and return true to indicate that
1660/// there was an error.
1661///
1662/// \returns true if the PCH file is unacceptable, false otherwise.
1663bool PCHReader::ParseLanguageOptions(
1664 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001665 if (Listener) {
1666 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001667
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001668 #define PARSE_LANGOPT(Option) \
1669 LangOpts.Option = Record[Idx]; \
1670 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001671
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001672 unsigned Idx = 0;
1673 PARSE_LANGOPT(Trigraphs);
1674 PARSE_LANGOPT(BCPLComment);
1675 PARSE_LANGOPT(DollarIdents);
1676 PARSE_LANGOPT(AsmPreprocessor);
1677 PARSE_LANGOPT(GNUMode);
1678 PARSE_LANGOPT(ImplicitInt);
1679 PARSE_LANGOPT(Digraphs);
1680 PARSE_LANGOPT(HexFloats);
1681 PARSE_LANGOPT(C99);
1682 PARSE_LANGOPT(Microsoft);
1683 PARSE_LANGOPT(CPlusPlus);
1684 PARSE_LANGOPT(CPlusPlus0x);
1685 PARSE_LANGOPT(CXXOperatorNames);
1686 PARSE_LANGOPT(ObjC1);
1687 PARSE_LANGOPT(ObjC2);
1688 PARSE_LANGOPT(ObjCNonFragileABI);
1689 PARSE_LANGOPT(PascalStrings);
1690 PARSE_LANGOPT(WritableStrings);
1691 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001692 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001693 PARSE_LANGOPT(Exceptions);
1694 PARSE_LANGOPT(NeXTRuntime);
1695 PARSE_LANGOPT(Freestanding);
1696 PARSE_LANGOPT(NoBuiltin);
1697 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001698 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001699 PARSE_LANGOPT(Blocks);
1700 PARSE_LANGOPT(EmitAllDecls);
1701 PARSE_LANGOPT(MathErrno);
1702 PARSE_LANGOPT(OverflowChecking);
1703 PARSE_LANGOPT(HeinousExtensions);
1704 PARSE_LANGOPT(Optimize);
1705 PARSE_LANGOPT(OptimizeSize);
1706 PARSE_LANGOPT(Static);
1707 PARSE_LANGOPT(PICLevel);
1708 PARSE_LANGOPT(GNUInline);
1709 PARSE_LANGOPT(NoInline);
1710 PARSE_LANGOPT(AccessControl);
1711 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001712 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001713 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1714 ++Idx;
1715 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1716 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001717 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1718 Record[Idx]);
1719 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001720 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001721 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001722 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001723
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001724 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001725 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001726
1727 return false;
1728}
1729
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001730void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1731 Comments.resize(NumComments);
1732 std::copy(this->Comments, this->Comments + NumComments,
1733 Comments.begin());
1734}
1735
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001736/// \brief Read and return the type at the given offset.
1737///
1738/// This routine actually reads the record corresponding to the type
1739/// at the given offset in the bitstream. It is a helper routine for
1740/// GetType, which deals with reading type IDs.
1741QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001742 // Keep track of where we are in the stream, then jump back there
1743 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001744 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001745
Douglas Gregor1342e842009-07-06 18:54:52 +00001746 // Note that we are loading a type record.
1747 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001748
Douglas Gregor12bfa382009-10-17 00:13:19 +00001749 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001750 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001751 unsigned Code = DeclsCursor.ReadCode();
1752 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001753 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001754 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001755 "Incorrect encoding of extended qualifier type");
1756 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001757 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1758 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001759 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001760
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001761 case pch::TYPE_FIXED_WIDTH_INT: {
1762 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001763 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001764 }
1765
1766 case pch::TYPE_COMPLEX: {
1767 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1768 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001769 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001770 }
1771
1772 case pch::TYPE_POINTER: {
1773 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1774 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001775 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001776 }
1777
1778 case pch::TYPE_BLOCK_POINTER: {
1779 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1780 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001781 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001782 }
1783
1784 case pch::TYPE_LVALUE_REFERENCE: {
1785 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1786 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001787 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001788 }
1789
1790 case pch::TYPE_RVALUE_REFERENCE: {
1791 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1792 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001793 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001794 }
1795
1796 case pch::TYPE_MEMBER_POINTER: {
1797 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1798 QualType PointeeType = GetType(Record[0]);
1799 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001800 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001801 }
1802
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001803 case pch::TYPE_CONSTANT_ARRAY: {
1804 QualType ElementType = GetType(Record[0]);
1805 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1806 unsigned IndexTypeQuals = Record[2];
1807 unsigned Idx = 3;
1808 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001809 return Context->getConstantArrayType(ElementType, Size,
1810 ASM, IndexTypeQuals);
1811 }
1812
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001813 case pch::TYPE_INCOMPLETE_ARRAY: {
1814 QualType ElementType = GetType(Record[0]);
1815 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1816 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001817 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001818 }
1819
1820 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001821 QualType ElementType = GetType(Record[0]);
1822 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1823 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001824 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1825 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001826 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001827 ASM, IndexTypeQuals,
1828 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001829 }
1830
1831 case pch::TYPE_VECTOR: {
1832 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001833 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001834 return QualType();
1835 }
1836
1837 QualType ElementType = GetType(Record[0]);
1838 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001839 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001840 }
1841
1842 case pch::TYPE_EXT_VECTOR: {
1843 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001844 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001845 return QualType();
1846 }
1847
1848 QualType ElementType = GetType(Record[0]);
1849 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001850 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001851 }
1852
1853 case pch::TYPE_FUNCTION_NO_PROTO: {
1854 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001855 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001856 return QualType();
1857 }
1858 QualType ResultType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001859 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001860 }
1861
1862 case pch::TYPE_FUNCTION_PROTO: {
1863 QualType ResultType = GetType(Record[0]);
1864 unsigned Idx = 1;
1865 unsigned NumParams = Record[Idx++];
1866 llvm::SmallVector<QualType, 16> ParamTypes;
1867 for (unsigned I = 0; I != NumParams; ++I)
1868 ParamTypes.push_back(GetType(Record[Idx++]));
1869 bool isVariadic = Record[Idx++];
1870 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001871 bool hasExceptionSpec = Record[Idx++];
1872 bool hasAnyExceptionSpec = Record[Idx++];
1873 unsigned NumExceptions = Record[Idx++];
1874 llvm::SmallVector<QualType, 2> Exceptions;
1875 for (unsigned I = 0; I != NumExceptions; ++I)
1876 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001877 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001878 isVariadic, Quals, hasExceptionSpec,
1879 hasAnyExceptionSpec, NumExceptions,
1880 Exceptions.data());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001881 }
1882
1883 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001884 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001885 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001886
1887 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001888 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001889
1890 case pch::TYPE_TYPEOF: {
1891 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001892 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001893 return QualType();
1894 }
1895 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001896 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Anders Carlsson81df7b82009-06-24 19:06:50 +00001899 case pch::TYPE_DECLTYPE:
1900 return Context->getDecltypeType(ReadTypeExpr());
1901
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001902 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001903 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001904 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001905
Douglas Gregor1daeb692009-04-13 18:14:40 +00001906 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001907 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001908 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001909
John McCallfcc33b02009-09-05 00:15:47 +00001910 case pch::TYPE_ELABORATED: {
1911 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1912 unsigned Tag = Record[1];
1913 return Context->getElaboratedType(GetType(Record[0]),
1914 (ElaboratedType::TagKind) Tag);
1915 }
1916
Steve Naroffc277ad12009-07-18 15:33:26 +00001917 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001918 unsigned Idx = 0;
1919 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1920 unsigned NumProtos = Record[Idx++];
1921 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1922 for (unsigned I = 0; I != NumProtos; ++I)
1923 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001924 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001925 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001926
Steve Narofffb4330f2009-06-17 22:40:22 +00001927 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001928 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001929 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001930 unsigned NumProtos = Record[Idx++];
1931 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1932 for (unsigned I = 0; I != NumProtos; ++I)
1933 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001934 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001935 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00001936
John McCallcebee162009-10-18 09:09:24 +00001937 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1938 unsigned Idx = 0;
1939 QualType Parm = GetType(Record[Idx++]);
1940 QualType Replacement = GetType(Record[Idx++]);
1941 return
1942 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1943 Replacement);
1944 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001945 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001946 // Suppress a GCC warning
1947 return QualType();
1948}
1949
John McCall8f115c62009-10-16 21:56:05 +00001950namespace {
1951
1952class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1953 PCHReader &Reader;
1954 const PCHReader::RecordData &Record;
1955 unsigned &Idx;
1956
1957public:
1958 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1959 unsigned &Idx)
1960 : Reader(Reader), Record(Record), Idx(Idx) { }
1961
John McCall17001972009-10-18 01:05:36 +00001962 // We want compile-time assurance that we've enumerated all of
1963 // these, so unfortunately we have to declare them first, then
1964 // define them out-of-line.
1965#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00001966#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00001967 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00001968#include "clang/AST/TypeLocNodes.def"
1969
John McCall17001972009-10-18 01:05:36 +00001970 void VisitFunctionTypeLoc(FunctionTypeLoc);
1971 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00001972};
1973
1974}
1975
John McCall17001972009-10-18 01:05:36 +00001976void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00001977 // nothing to do
1978}
John McCall17001972009-10-18 01:05:36 +00001979void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1980 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001981}
John McCall17001972009-10-18 01:05:36 +00001982void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1983 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001984}
John McCall17001972009-10-18 01:05:36 +00001985void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1986 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001987}
John McCall17001972009-10-18 01:05:36 +00001988void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1989 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001990}
John McCall17001972009-10-18 01:05:36 +00001991void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1992 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001993}
John McCall17001972009-10-18 01:05:36 +00001994void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1995 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001996}
John McCall17001972009-10-18 01:05:36 +00001997void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1998 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00001999}
John McCall17001972009-10-18 01:05:36 +00002000void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2001 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002002}
John McCall17001972009-10-18 01:05:36 +00002003void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2004 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2005 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002006 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002007 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002008 else
John McCall17001972009-10-18 01:05:36 +00002009 TL.setSizeExpr(0);
2010}
2011void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2012 VisitArrayTypeLoc(TL);
2013}
2014void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2015 VisitArrayTypeLoc(TL);
2016}
2017void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2018 VisitArrayTypeLoc(TL);
2019}
2020void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2021 DependentSizedArrayTypeLoc TL) {
2022 VisitArrayTypeLoc(TL);
2023}
2024void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2025 DependentSizedExtVectorTypeLoc TL) {
2026 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2027}
2028void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2029 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2030}
2031void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2032 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2033}
2034void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2035 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2036 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2037 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002038 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002039 }
2040}
2041void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2042 VisitFunctionTypeLoc(TL);
2043}
2044void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2045 VisitFunctionTypeLoc(TL);
2046}
2047void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2048 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2049}
2050void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2051 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2052}
2053void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2054 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2055}
2056void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2057 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2058}
2059void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2060 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2061}
2062void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2063 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2064}
2065void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2066 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
2068void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2069 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070}
John McCallcebee162009-10-18 09:09:24 +00002071void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2072 SubstTemplateTypeParmTypeLoc TL) {
2073 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2074}
John McCall17001972009-10-18 01:05:36 +00002075void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2076 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002077 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2078 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2079 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2080 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2081 TL.setArgLocInfo(i,
2082 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2083 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002084}
2085void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2086 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2087}
2088void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2089 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2090}
2091void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2092 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002093 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2094 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2096 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002097}
John McCallfc93cf92009-10-22 22:37:11 +00002098void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2099 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2100 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2102 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2103 TL.setHasProtocolsAsWritten(Record[Idx++]);
2104 if (TL.hasProtocolsAsWritten())
2105 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2106 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2107}
John McCall8f115c62009-10-16 21:56:05 +00002108
2109DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2110 unsigned &Idx) {
2111 QualType InfoTy = GetType(Record[Idx++]);
2112 if (InfoTy.isNull())
2113 return 0;
2114
2115 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2116 TypeLocReader TLR(*this, Record, Idx);
2117 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2118 TLR.Visit(TL);
2119 return DInfo;
2120}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002121
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002122QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002123 unsigned FastQuals = ID & Qualifiers::FastMask;
2124 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002125
2126 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2127 QualType T;
2128 switch ((pch::PredefinedTypeIDs)Index) {
2129 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002130 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2131 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002132
2133 case pch::PREDEF_TYPE_CHAR_U_ID:
2134 case pch::PREDEF_TYPE_CHAR_S_ID:
2135 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002136 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002137 break;
2138
Chris Lattner8575daa2009-04-27 21:45:14 +00002139 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2140 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2141 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2142 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2143 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002144 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002145 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2146 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2147 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2148 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2149 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2150 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002151 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002152 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2153 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2154 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2155 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2156 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002157 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002158 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2159 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002160 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2161 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002162 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002163 }
2164
2165 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002166 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002167 }
2168
2169 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002170 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002171 if (TypesLoaded[Index].isNull())
2172 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002173
John McCall8ccfcb52009-09-24 19:53:00 +00002174 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002175}
2176
John McCall0ad16662009-10-29 08:12:44 +00002177TemplateArgumentLocInfo
2178PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2179 const RecordData &Record,
2180 unsigned &Index) {
2181 switch (Kind) {
2182 case TemplateArgument::Expression:
2183 return ReadDeclExpr();
2184 case TemplateArgument::Type:
2185 return GetDeclaratorInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002186 case TemplateArgument::Template: {
2187 SourceLocation
2188 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2189 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2190 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2191 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2192 TemplateNameLoc);
2193 }
John McCall0ad16662009-10-29 08:12:44 +00002194 case TemplateArgument::Null:
2195 case TemplateArgument::Integral:
2196 case TemplateArgument::Declaration:
2197 case TemplateArgument::Pack:
2198 return TemplateArgumentLocInfo();
2199 }
2200 llvm::llvm_unreachable("unexpected template argument loc");
2201 return TemplateArgumentLocInfo();
2202}
2203
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002204Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002205 if (ID == 0)
2206 return 0;
2207
Douglas Gregor745ed142009-04-25 18:35:21 +00002208 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002209 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002210 return 0;
2211 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002212
Douglas Gregor745ed142009-04-25 18:35:21 +00002213 unsigned Index = ID - 1;
2214 if (!DeclsLoaded[Index])
2215 ReadDeclRecord(DeclOffsets[Index], Index);
2216
2217 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002218}
2219
Chris Lattner9c28af02009-04-27 05:46:25 +00002220/// \brief Resolve the offset of a statement into a statement.
2221///
2222/// This operation will read a new statement from the external
2223/// source each time it is called, and is meant to be used via a
2224/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2225Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002226 // Since we know tha this statement is part of a decl, make sure to use the
2227 // decl cursor to read it.
2228 DeclsCursor.JumpToBit(Offset);
2229 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002230}
2231
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002232bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002233 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002234 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002235 "DeclContext has no lexical decls in storage");
2236 uint64_t Offset = DeclContextOffsets[DC].first;
2237 assert(Offset && "DeclContext has no lexical decls in storage");
2238
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002239 // Keep track of where we are in the stream, then jump back there
2240 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002241 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002242
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002243 // Load the record containing all of the declarations lexically in
2244 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002245 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002246 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002247 unsigned Code = DeclsCursor.ReadCode();
2248 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002249 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002250 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2251
2252 // Load all of the declaration IDs
2253 Decls.clear();
2254 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002255 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002256 return false;
2257}
2258
2259bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002260 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002261 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002262 "DeclContext has no visible decls in storage");
2263 uint64_t Offset = DeclContextOffsets[DC].second;
2264 assert(Offset && "DeclContext has no visible decls in storage");
2265
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002266 // Keep track of where we are in the stream, then jump back there
2267 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002268 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002269
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002270 // Load the record containing all of the declarations visible in
2271 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002272 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002273 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002274 unsigned Code = DeclsCursor.ReadCode();
2275 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002276 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002277 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2278 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002279 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002280
2281 Decls.clear();
2282
2283 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002284 while (Idx < Record.size()) {
2285 Decls.push_back(VisibleDeclaration());
2286 Decls.back().Name = ReadDeclarationName(Record, Idx);
2287
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002288 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002289 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002290 LoadedDecls.reserve(Size);
2291 for (unsigned I = 0; I < Size; ++I)
2292 LoadedDecls.push_back(Record[Idx++]);
2293 }
2294
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002295 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002296 return false;
2297}
2298
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002299void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002300 this->Consumer = Consumer;
2301
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002302 if (!Consumer)
2303 return;
2304
2305 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002306 // Force deserialization of this decl, which will cause it to be passed to
2307 // the consumer (or queued).
2308 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002309 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002310
2311 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2312 DeclGroupRef DG(InterestingDecls[I]);
2313 Consumer->HandleTopLevelDecl(DG);
2314 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002315}
2316
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002317void PCHReader::PrintStats() {
2318 std::fprintf(stderr, "*** PCH Statistics:\n");
2319
Mike Stump11289f42009-09-09 15:08:12 +00002320 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002321 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002322 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002323 unsigned NumDeclsLoaded
2324 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2325 (Decl *)0);
2326 unsigned NumIdentifiersLoaded
2327 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2328 IdentifiersLoaded.end(),
2329 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002330 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002331 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2332 SelectorsLoaded.end(),
2333 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002334
Douglas Gregorc5046832009-04-27 18:38:38 +00002335 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2336 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002337 if (TotalNumSLocEntries)
2338 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2339 NumSLocEntriesRead, TotalNumSLocEntries,
2340 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002341 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002342 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002343 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2344 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2345 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002346 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002347 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2348 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002349 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002350 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002351 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2352 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002353 if (TotalNumSelectors)
2354 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2355 NumSelectorsLoaded, TotalNumSelectors,
2356 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2357 if (TotalNumStatements)
2358 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2359 NumStatementsRead, TotalNumStatements,
2360 ((float)NumStatementsRead/TotalNumStatements * 100));
2361 if (TotalNumMacros)
2362 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2363 NumMacrosRead, TotalNumMacros,
2364 ((float)NumMacrosRead/TotalNumMacros * 100));
2365 if (TotalLexicalDeclContexts)
2366 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2367 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2368 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2369 * 100));
2370 if (TotalVisibleDeclContexts)
2371 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2372 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2373 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2374 * 100));
2375 if (TotalSelectorsInMethodPool) {
2376 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2377 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2378 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2379 * 100));
2380 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2381 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002382 std::fprintf(stderr, "\n");
2383}
2384
Douglas Gregora868bbd2009-04-21 22:25:48 +00002385void PCHReader::InitializeSema(Sema &S) {
2386 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002387 S.ExternalSource = this;
2388
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002389 // Makes sure any declarations that were deserialized "too early"
2390 // still get added to the identifier's declaration chains.
2391 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2392 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2393 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002394 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002395 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002396
2397 // If there were any tentative definitions, deserialize them and add
2398 // them to Sema's table of tentative definitions.
2399 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2400 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2401 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner0c797362009-09-08 18:19:27 +00002402 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregord4df8652009-04-22 22:02:47 +00002403 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002404
2405 // If there were any locally-scoped external declarations,
2406 // deserialize them and add them to Sema's table of locally-scoped
2407 // external declarations.
2408 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2409 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2410 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2411 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002412
2413 // If there were any ext_vector type declarations, deserialize them
2414 // and add them to Sema's vector of such declarations.
2415 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2416 SemaObj->ExtVectorDecls.push_back(
2417 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002418}
2419
2420IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2421 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002422 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002423 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2424 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2425 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2426 if (Pos == IdTable->end())
2427 return 0;
2428
2429 // Dereferencing the iterator has the effect of building the
2430 // IdentifierInfo node and populating it with the various
2431 // declarations it needs.
2432 return *Pos;
2433}
2434
Mike Stump11289f42009-09-09 15:08:12 +00002435std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002436PCHReader::ReadMethodPool(Selector Sel) {
2437 if (!MethodPoolLookupTable)
2438 return std::pair<ObjCMethodList, ObjCMethodList>();
2439
2440 // Try to find this selector within our on-disk hash table.
2441 PCHMethodPoolLookupTable *PoolTable
2442 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2443 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002444 if (Pos == PoolTable->end()) {
2445 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002446 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002447 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002448
Douglas Gregor95c13f52009-04-25 17:48:32 +00002449 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002450 return *Pos;
2451}
2452
Douglas Gregor0e149972009-04-25 19:10:14 +00002453void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002454 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002455 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002456 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002457}
2458
Douglas Gregor1342e842009-07-06 18:54:52 +00002459/// \brief Set the globally-visible declarations associated with the given
2460/// identifier.
2461///
2462/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002463/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002464/// them.
2465///
2466/// \param II an IdentifierInfo that refers to one or more globally-visible
2467/// declarations.
2468///
2469/// \param DeclIDs the set of declaration IDs with the name @p II that are
2470/// visible at global scope.
2471///
2472/// \param Nonrecursive should be true to indicate that the caller knows that
2473/// this call is non-recursive, and therefore the globally-visible declarations
2474/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002475void
2476PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002477 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2478 bool Nonrecursive) {
2479 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2480 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2481 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2482 PII.II = II;
2483 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2484 PII.DeclIDs.push_back(DeclIDs[I]);
2485 return;
2486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregor1342e842009-07-06 18:54:52 +00002488 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2489 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2490 if (SemaObj) {
2491 // Introduce this declaration into the translation-unit scope
2492 // and add it to the declaration chain for this identifier, so
2493 // that (unqualified) name lookup will find it.
2494 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2495 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2496 } else {
2497 // Queue this declaration so that it will be added to the
2498 // translation unit scope and identifier's declaration chain
2499 // once a Sema object is known.
2500 PreloadedDecls.push_back(D);
2501 }
2502 }
2503}
2504
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002505IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002506 if (ID == 0)
2507 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Douglas Gregor0e149972009-04-25 19:10:14 +00002509 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002510 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002511 return 0;
2512 }
Mike Stump11289f42009-09-09 15:08:12 +00002513
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002514 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002515 if (!IdentifiersLoaded[ID - 1]) {
2516 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002517 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002518
Douglas Gregorab4df582009-04-28 20:01:51 +00002519 // All of the strings in the PCH file are preceded by a 16-bit
2520 // length. Extract that 16-bit length to avoid having to execute
2521 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002522 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2523 // unsigned integers. This is important to avoid integer overflow when
2524 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002525 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002526 unsigned StrLen = (((unsigned) StrLenPtr[0])
2527 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002528 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002529 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor0e149972009-04-25 19:10:14 +00002532 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002533}
2534
Douglas Gregor258ae542009-04-27 06:38:32 +00002535void PCHReader::ReadSLocEntry(unsigned ID) {
2536 ReadSLocEntryRecord(ID);
2537}
2538
Steve Naroff2ddea052009-04-23 10:39:46 +00002539Selector PCHReader::DecodeSelector(unsigned ID) {
2540 if (ID == 0)
2541 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002543 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002544 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002545
2546 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002547 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002548 return Selector();
2549 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002550
2551 unsigned Index = ID - 1;
2552 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2553 // Load this selector from the selector table.
2554 // FIXME: endianness portability issues with SelectorOffsets table
2555 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002556 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002557 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2558 }
2559
2560 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002561}
2562
Mike Stump11289f42009-09-09 15:08:12 +00002563DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002564PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2565 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2566 switch (Kind) {
2567 case DeclarationName::Identifier:
2568 return DeclarationName(GetIdentifierInfo(Record, Idx));
2569
2570 case DeclarationName::ObjCZeroArgSelector:
2571 case DeclarationName::ObjCOneArgSelector:
2572 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002573 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002574
2575 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002576 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002577 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002578
2579 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002580 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002581 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002582
2583 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002584 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002585 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002586
2587 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002588 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002589 (OverloadedOperatorKind)Record[Idx++]);
2590
Alexis Hunt3d221f22009-11-29 07:34:05 +00002591 case DeclarationName::CXXLiteralOperatorName:
2592 return Context->DeclarationNames.getCXXLiteralOperatorName(
2593 GetIdentifierInfo(Record, Idx));
2594
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002595 case DeclarationName::CXXUsingDirective:
2596 return DeclarationName::getUsingDirectiveName();
2597 }
2598
2599 // Required to silence GCC warning
2600 return DeclarationName();
2601}
Douglas Gregor55abb232009-04-10 20:39:37 +00002602
Douglas Gregor1daeb692009-04-13 18:14:40 +00002603/// \brief Read an integral value
2604llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2605 unsigned BitWidth = Record[Idx++];
2606 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2607 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2608 Idx += NumWords;
2609 return Result;
2610}
2611
2612/// \brief Read a signed integral value
2613llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2614 bool isUnsigned = Record[Idx++];
2615 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2616}
2617
Douglas Gregore0a3a512009-04-14 21:55:33 +00002618/// \brief Read a floating-point value
2619llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002620 return llvm::APFloat(ReadAPInt(Record, Idx));
2621}
2622
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002623// \brief Read a string
2624std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2625 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002626 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002627 Idx += Len;
2628 return Result;
2629}
2630
Douglas Gregor55abb232009-04-10 20:39:37 +00002631DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002632 return Diag(SourceLocation(), DiagID);
2633}
2634
2635DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002636 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002637}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002638
Douglas Gregora868bbd2009-04-21 22:25:48 +00002639/// \brief Retrieve the identifier table associated with the
2640/// preprocessor.
2641IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002642 assert(PP && "Forgot to set Preprocessor ?");
2643 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002644}
2645
Douglas Gregora9af1d12009-04-17 00:04:06 +00002646/// \brief Record that the given ID maps to the given switch-case
2647/// statement.
2648void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2649 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2650 SwitchCaseStmts[ID] = SC;
2651}
2652
2653/// \brief Retrieve the switch-case statement with the given ID.
2654SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2655 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2656 return SwitchCaseStmts[ID];
2657}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002658
2659/// \brief Record that the given label statement has been
2660/// deserialized and has the given ID.
2661void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002662 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002663 "Deserialized label twice");
2664 LabelStmts[ID] = S;
2665
2666 // If we've already seen any goto statements that point to this
2667 // label, resolve them now.
2668 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2669 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2670 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2671 Goto->second->setLabel(S);
2672 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002673
2674 // If we've already seen any address-label statements that point to
2675 // this label, resolve them now.
2676 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002677 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002678 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002679 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002680 AddrLabel != AddrLabels.second; ++AddrLabel)
2681 AddrLabel->second->setLabel(S);
2682 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002683}
2684
2685/// \brief Set the label of the given statement to the label
2686/// identified by ID.
2687///
2688/// Depending on the order in which the label and other statements
2689/// referencing that label occur, this operation may complete
2690/// immediately (updating the statement) or it may queue the
2691/// statement to be back-patched later.
2692void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2693 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2694 if (Label != LabelStmts.end()) {
2695 // We've already seen this label, so set the label of the goto and
2696 // we're done.
2697 S->setLabel(Label->second);
2698 } else {
2699 // We haven't seen this label yet, so add this goto to the set of
2700 // unresolved goto statements.
2701 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2702 }
2703}
Douglas Gregor779d8652009-04-17 18:58:21 +00002704
2705/// \brief Set the label of the given expression to the label
2706/// identified by ID.
2707///
2708/// Depending on the order in which the label and other statements
2709/// referencing that label occur, this operation may complete
2710/// immediately (updating the statement) or it may queue the
2711/// statement to be back-patched later.
2712void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2713 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2714 if (Label != LabelStmts.end()) {
2715 // We've already seen this label, so set the label of the
2716 // label-address expression and we're done.
2717 S->setLabel(Label->second);
2718 } else {
2719 // We haven't seen this label yet, so add this label-address
2720 // expression to the set of unresolved label-address expressions.
2721 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2722 }
2723}
Douglas Gregor1342e842009-07-06 18:54:52 +00002724
2725
Mike Stump11289f42009-09-09 15:08:12 +00002726PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002727 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2728 Reader.CurrentlyLoadingTypeOrDecl = this;
2729}
2730
2731PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2732 if (!Parent) {
2733 // If any identifiers with corresponding top-level declarations have
2734 // been loaded, load those declarations now.
2735 while (!Reader.PendingIdentifierInfos.empty()) {
2736 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2737 Reader.PendingIdentifierInfos.front().DeclIDs,
2738 true);
2739 Reader.PendingIdentifierInfos.pop_front();
2740 }
2741 }
2742
Mike Stump11289f42009-09-09 15:08:12 +00002743 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002744}