blob: 48ef2ac31abab8b295df3cda45db4b43795369e2 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbarc7162932009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000036#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000044// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
75 PARSE_LANGOPT_BENIGN(PascalStrings);
76 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000077 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000078 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000079 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000080 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
81 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
82 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
83 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000084 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000086 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000087 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
88 PARSE_LANGOPT_BENIGN(EmitAllDecls);
89 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
90 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_heinous_extensions);
93 // FIXME: Most of the options below are benign if the macro wasn't
94 // used. Unfortunately, this means that a PCH compiled without
95 // optimization can't be used with optimization turned on, even
96 // though the only thing that changes is whether __OPTIMIZE__ was
97 // defined... but if __OPTIMIZE__ never showed up in the header, it
98 // doesn't matter. We could consider making this some special kind
99 // of check.
100 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
101 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
102 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
103 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
104 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
105 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
106 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
107 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000108 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000109 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000110 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000111 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112 return true;
113 }
114 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000115 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000117 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000118 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000119 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000120 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000121#undef PARSE_LANGOPT_IRRELEVANT
122#undef PARSE_LANGOPT_BENIGN
123
124 return false;
125}
126
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000127bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
128 if (Triple == PP.getTargetInfo().getTriple().str())
129 return false;
130
131 Reader.Diag(diag::warn_pch_target_triple)
132 << Triple << PP.getTargetInfo().getTriple().str();
133 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000134}
135
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000136bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000137 FileID PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000138 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000139 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000140 // We are in the context of an implicit include, so the predefines buffer will
141 // have a #include entry for the PCH file itself (as normalized by the
142 // preprocessor initialization). Find it and skip over it in the checking
143 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000144 llvm::SmallString<256> PCHInclude;
145 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000146 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000147 PCHInclude += "\"\n";
148 std::pair<llvm::StringRef,llvm::StringRef> Split =
149 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
150 llvm::StringRef Left = Split.first, Right = Split.second;
151 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
152
153 // If the predefines is equal to the joined left and right halves, we're done!
154 if (Left.size() + Right.size() == PCHPredef.size() &&
155 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000156 return false;
157
158 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000160 // The predefines buffers are different. Determine what the differences are,
161 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000162 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
163 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
164
165 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
166 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
167 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000168
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000169 // Sort both sets of predefined buffer lines, since we allow some extra
170 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000171 std::sort(CmdLineLines.begin(), CmdLineLines.end());
172 std::sort(PCHLines.begin(), PCHLines.end());
173
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000174 // Determine which predefines that were used to build the PCH file are missing
175 // from the command line.
176 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000177 std::set_difference(PCHLines.begin(), PCHLines.end(),
178 CmdLineLines.begin(), CmdLineLines.end(),
179 std::back_inserter(MissingPredefines));
180
181 bool MissingDefines = false;
182 bool ConflictingDefines = false;
183 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000184 llvm::StringRef Missing = MissingPredefines[I];
185 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000186 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
187 return true;
188 }
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000190 // This is a macro definition. Determine the name of the macro we're
191 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000192 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000193 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000194 = Missing.find_first_of("( \n\r", StartOfMacroName);
195 assert(EndOfMacroName != std::string::npos &&
196 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000197 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000198
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000199 // Determine whether this macro was given a different definition on the
200 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000201 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000202 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000203 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000204 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
205 MacroDefStart);
206 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000207 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000208 // Different macro; we're done.
209 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000210 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000211 }
Mike Stump1eb44332009-09-09 15:08:12 +0000212
213 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000214 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000215 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000216 (*ConflictPos)[MacroDefLen] != '(')
217 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000219 // We found a conflicting macro definition.
220 break;
221 }
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000223 if (ConflictPos != CmdLineLines.end()) {
224 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
225 << MacroName;
226
227 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000228 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
229 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
230 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
231 .getFileLocWithOffset(Offset);
232 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000233
234 ConflictingDefines = true;
235 continue;
236 }
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000238 // If the macro doesn't conflict, then we'll just pick up the macro
239 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000240 if (ConflictingDefines)
241 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000243 if (!MissingDefines) {
244 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
245 MissingDefines = true;
246 }
247
248 // Show the definition of this macro within the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000249 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
250 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
251 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000252 .getFileLocWithOffset(Offset);
253 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
254 }
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000256 if (ConflictingDefines)
257 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000259 // Determine what predefines were introduced based on command-line
260 // parameters that were not present when building the PCH
261 // file. Extra #defines are okay, so long as the identifiers being
262 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000263 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000264 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
265 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000266 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000267 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000268 llvm::StringRef &Extra = ExtraPredefines[I];
269 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000270 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
271 return true;
272 }
273
274 // This is an extra macro definition. Determine the name of the
275 // macro we're defining.
276 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000277 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000278 = Extra.find_first_of("( \n\r", StartOfMacroName);
279 assert(EndOfMacroName != std::string::npos &&
280 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000281 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000282
283 // Check whether this name was used somewhere in the PCH file. If
284 // so, defining it as a macro could change behavior, so we reject
285 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000286 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000287 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000288 return true;
289 }
290
291 // Add this definition to the suggested predefines buffer.
292 SuggestedPredefines += Extra;
293 SuggestedPredefines += '\n';
294 }
295
296 // If we get here, it's because the predefines buffer had compatible
297 // contents. Accept the PCH file.
298 return false;
299}
300
301void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
302 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
303}
304
305void PCHValidator::ReadCounter(unsigned Value) {
306 PP.setCounterValue(Value);
307}
308
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000309//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000310// PCH reader implementation
311//===----------------------------------------------------------------------===//
312
Mike Stump1eb44332009-09-09 15:08:12 +0000313PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
314 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000315 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
316 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000317 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000318 IdentifierTableData(0), IdentifierLookupTable(0),
319 IdentifierOffsets(0),
320 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
321 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000322 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000323 NumStatHits(0), NumStatMisses(0),
324 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000325 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000326 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000327 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000328 RelocatablePCH = false;
329}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000330
331PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000333 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000334 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000335 IdentifierTableData(0), IdentifierLookupTable(0),
336 IdentifierOffsets(0),
337 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
338 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000339 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000340 NumStatHits(0), NumStatMisses(0),
341 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000342 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000343 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000344 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000345 RelocatablePCH = false;
346}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000347
348PCHReader::~PCHReader() {}
349
Chris Lattnerda930612009-04-27 05:58:23 +0000350Expr *PCHReader::ReadDeclExpr() {
351 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
352}
353
354Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000355 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000356}
357
358
Douglas Gregor668c1a42009-04-21 22:25:48 +0000359namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000360class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000361 PCHReader &Reader;
362
363public:
364 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
365
366 typedef Selector external_key_type;
367 typedef external_key_type internal_key_type;
368
369 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000371 static bool EqualKey(const internal_key_type& a,
372 const internal_key_type& b) {
373 return a == b;
374 }
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000376 static unsigned ComputeHash(Selector Sel) {
377 unsigned N = Sel.getNumArgs();
378 if (N == 0)
379 ++N;
380 unsigned R = 5381;
381 for (unsigned I = 0; I != N; ++I)
382 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000383 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000384 return R;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000387 // This hopefully will just get inlined and removed by the optimizer.
388 static const internal_key_type&
389 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000391 static std::pair<unsigned, unsigned>
392 ReadKeyDataLength(const unsigned char*& d) {
393 using namespace clang::io;
394 unsigned KeyLen = ReadUnalignedLE16(d);
395 unsigned DataLen = ReadUnalignedLE16(d);
396 return std::make_pair(KeyLen, DataLen);
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Douglas Gregor83941df2009-04-25 17:48:32 +0000399 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000400 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000401 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000402 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000403 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000404 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
405 if (N == 0)
406 return SelTable.getNullarySelector(FirstII);
407 else if (N == 1)
408 return SelTable.getUnarySelector(FirstII);
409
410 llvm::SmallVector<IdentifierInfo *, 16> Args;
411 Args.push_back(FirstII);
412 for (unsigned I = 1; I != N; ++I)
413 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
414
Douglas Gregor75fdb232009-05-22 22:45:36 +0000415 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000418 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
419 using namespace clang::io;
420 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
421 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
422
423 data_type Result;
424
425 // Load instance methods
426 ObjCMethodList *Prev = 0;
427 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000428 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000429 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
430 if (!Result.first.Method) {
431 // This is the first method, which is the easy case.
432 Result.first.Method = Method;
433 Prev = &Result.first;
434 continue;
435 }
436
437 Prev->Next = new ObjCMethodList(Method, 0);
438 Prev = Prev->Next;
439 }
440
441 // Load factory methods
442 Prev = 0;
443 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000444 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000445 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
446 if (!Result.second.Method) {
447 // This is the first method, which is the easy case.
448 Result.second.Method = Method;
449 Prev = &Result.second;
450 continue;
451 }
452
453 Prev->Next = new ObjCMethodList(Method, 0);
454 Prev = Prev->Next;
455 }
456
457 return Result;
458 }
459};
Mike Stump1eb44332009-09-09 15:08:12 +0000460
461} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000462
463/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000464typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000465 PCHMethodPoolLookupTable;
466
467namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000468class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000469 PCHReader &Reader;
470
471 // If we know the IdentifierInfo in advance, it is here and we will
472 // not build a new one. Used when deserializing information about an
473 // identifier that was constructed before the PCH file was read.
474 IdentifierInfo *KnownII;
475
476public:
477 typedef IdentifierInfo * data_type;
478
479 typedef const std::pair<const char*, unsigned> external_key_type;
480
481 typedef external_key_type internal_key_type;
482
Mike Stump1eb44332009-09-09 15:08:12 +0000483 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000484 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregor668c1a42009-04-21 22:25:48 +0000486 static bool EqualKey(const internal_key_type& a,
487 const internal_key_type& b) {
488 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
489 : false;
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregor668c1a42009-04-21 22:25:48 +0000492 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000493 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregor668c1a42009-04-21 22:25:48 +0000496 // This hopefully will just get inlined and removed by the optimizer.
497 static const internal_key_type&
498 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Douglas Gregor668c1a42009-04-21 22:25:48 +0000500 static std::pair<unsigned, unsigned>
501 ReadKeyDataLength(const unsigned char*& d) {
502 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000503 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000504 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000505 return std::make_pair(KeyLen, DataLen);
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregor668c1a42009-04-21 22:25:48 +0000508 static std::pair<const char*, unsigned>
509 ReadKey(const unsigned char* d, unsigned n) {
510 assert(n >= 2 && d[n-1] == '\0');
511 return std::make_pair((const char*) d, n-1);
512 }
Mike Stump1eb44332009-09-09 15:08:12 +0000513
514 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 const unsigned char* d,
516 unsigned DataLen) {
517 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000518 pch::IdentID ID = ReadUnalignedLE32(d);
519 bool IsInteresting = ID & 0x01;
520
521 // Wipe out the "is interesting" bit.
522 ID = ID >> 1;
523
524 if (!IsInteresting) {
525 // For unintersting identifiers, just build the IdentifierInfo
526 // and associate it with the persistent ID.
527 IdentifierInfo *II = KnownII;
528 if (!II)
529 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
530 k.first, k.first + k.second);
531 Reader.SetIdentifierInfo(ID, II);
532 return II;
533 }
534
Douglas Gregor5998da52009-04-28 21:32:13 +0000535 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000536 bool CPlusPlusOperatorKeyword = Bits & 0x01;
537 Bits >>= 1;
538 bool Poisoned = Bits & 0x01;
539 Bits >>= 1;
540 bool ExtensionToken = Bits & 0x01;
541 Bits >>= 1;
542 bool hasMacroDefinition = Bits & 0x01;
543 Bits >>= 1;
544 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
545 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Douglas Gregor2deaea32009-04-22 18:49:13 +0000547 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000548 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000549
550 // Build the IdentifierInfo itself and link the identifier ID with
551 // the new IdentifierInfo.
552 IdentifierInfo *II = KnownII;
553 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000554 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
555 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000556 Reader.SetIdentifierInfo(ID, II);
557
Douglas Gregor2deaea32009-04-22 18:49:13 +0000558 // Set or check the various bits in the IdentifierInfo structure.
559 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000560 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000561 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000562 "Incorrect extension token flag");
563 (void)ExtensionToken;
564 II->setIsPoisoned(Poisoned);
565 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
566 "Incorrect C++ operator keyword flag");
567 (void)CPlusPlusOperatorKeyword;
568
Douglas Gregor37e26842009-04-21 23:56:24 +0000569 // If this identifier is a macro, deserialize the macro
570 // definition.
571 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000572 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000573 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000574 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000575 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000576
577 // Read all of the declarations visible at global scope with this
578 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000579 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000580 if (DataLen > 0) {
581 llvm::SmallVector<uint32_t, 4> DeclIDs;
582 for (; DataLen > 0; DataLen -= 4)
583 DeclIDs.push_back(ReadUnalignedLE32(d));
584 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587 return II;
588 }
589};
Mike Stump1eb44332009-09-09 15:08:12 +0000590
591} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000592
593/// \brief The on-disk hash table used to contain information about
594/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000595typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000596 PCHIdentifierLookupTable;
597
Douglas Gregora02b1472009-04-28 21:53:25 +0000598bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000599 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
600 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000601 return true;
602}
603
Douglas Gregore1d918e2009-04-10 23:10:45 +0000604/// \brief Check the contents of the predefines buffer against the
605/// contents of the predefines buffer used to build the PCH file.
606///
607/// The contents of the two predefines buffers should be the same. If
608/// not, then some command-line option changed the preprocessor state
609/// and we must reject the PCH file.
610///
611/// \param PCHPredef The start of the predefines buffer in the PCH
612/// file.
613///
614/// \param PCHPredefLen The length of the predefines buffer in the PCH
615/// file.
616///
617/// \param PCHBufferID The FileID for the PCH predefines buffer.
618///
619/// \returns true if there was a mismatch (in which case the PCH file
620/// should be ignored), or false otherwise.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000621bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000622 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000623 if (Listener)
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000624 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000625 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000626 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000627 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000628}
629
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000630//===----------------------------------------------------------------------===//
631// Source Manager Deserialization
632//===----------------------------------------------------------------------===//
633
Douglas Gregorbd945002009-04-13 16:31:14 +0000634/// \brief Read the line table in the source manager block.
635/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000636bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000637 unsigned Idx = 0;
638 LineTableInfo &LineTable = SourceMgr.getLineTable();
639
640 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000641 std::map<int, int> FileIDs;
642 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000643 // Extract the file name
644 unsigned FilenameLen = Record[Idx++];
645 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
646 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000647 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000648 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000649 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000650 }
651
652 // Parse the line entries
653 std::vector<LineEntry> Entries;
654 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000655 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000656
657 // Extract the line entries
658 unsigned NumEntries = Record[Idx++];
659 Entries.clear();
660 Entries.reserve(NumEntries);
661 for (unsigned I = 0; I != NumEntries; ++I) {
662 unsigned FileOffset = Record[Idx++];
663 unsigned LineNo = Record[Idx++];
664 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000665 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000666 = (SrcMgr::CharacteristicKind)Record[Idx++];
667 unsigned IncludeOffset = Record[Idx++];
668 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
669 FileKind, IncludeOffset));
670 }
671 LineTable.AddEntry(FID, Entries);
672 }
673
674 return false;
675}
676
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000677namespace {
678
Benjamin Kramerbd218282009-11-28 10:07:24 +0000679class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000680public:
681 const bool hasStat;
682 const ino_t ino;
683 const dev_t dev;
684 const mode_t mode;
685 const time_t mtime;
686 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000688 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000689 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
690
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000691 PCHStatData()
692 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
693};
694
Benjamin Kramerbd218282009-11-28 10:07:24 +0000695class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000696 public:
697 typedef const char *external_key_type;
698 typedef const char *internal_key_type;
699
700 typedef PCHStatData data_type;
701
702 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000703 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000704 }
705
706 static internal_key_type GetInternalKey(const char *path) { return path; }
707
708 static bool EqualKey(internal_key_type a, internal_key_type b) {
709 return strcmp(a, b) == 0;
710 }
711
712 static std::pair<unsigned, unsigned>
713 ReadKeyDataLength(const unsigned char*& d) {
714 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
715 unsigned DataLen = (unsigned) *d++;
716 return std::make_pair(KeyLen + 1, DataLen);
717 }
718
719 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
720 return (const char *)d;
721 }
722
723 static data_type ReadData(const internal_key_type, const unsigned char *d,
724 unsigned /*DataLen*/) {
725 using namespace clang::io;
726
727 if (*d++ == 1)
728 return data_type();
729
730 ino_t ino = (ino_t) ReadUnalignedLE32(d);
731 dev_t dev = (dev_t) ReadUnalignedLE32(d);
732 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000733 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000734 off_t size = (off_t) ReadUnalignedLE64(d);
735 return data_type(ino, dev, mode, mtime, size);
736 }
737};
738
739/// \brief stat() cache for precompiled headers.
740///
741/// This cache is very similar to the stat cache used by pretokenized
742/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000743class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000744 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
745 CacheTy *Cache;
746
747 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000748public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000749 PCHStatCache(const unsigned char *Buckets,
750 const unsigned char *Base,
751 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000752 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000753 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
754 Cache = CacheTy::Create(Buckets, Base);
755 }
756
757 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000759 int stat(const char *path, struct stat *buf) {
760 // Do the lookup for the file's data in the PCH file.
761 CacheTy::iterator I = Cache->find(path);
762
763 // If we don't get a hit in the PCH file just forward to 'stat'.
764 if (I == Cache->end()) {
765 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000766 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000769 ++NumStatHits;
770 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000772 if (!Data.hasStat)
773 return 1;
774
775 buf->st_ino = Data.ino;
776 buf->st_dev = Data.dev;
777 buf->st_mtime = Data.mtime;
778 buf->st_mode = Data.mode;
779 buf->st_size = Data.size;
780 return 0;
781 }
782};
783} // end anonymous namespace
784
785
Douglas Gregor14f79002009-04-10 03:52:48 +0000786/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000787PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000788 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000789
790 // Set the source-location entry cursor to the current position in
791 // the stream. This cursor will be used to read the contents of the
792 // source manager block initially, and then lazily read
793 // source-location entries as needed.
794 SLocEntryCursor = Stream;
795
796 // The stream itself is going to skip over the source manager block.
797 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000798 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000799 return Failure;
800 }
801
802 // Enter the source manager block.
803 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000804 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000805 return Failure;
806 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000807
Douglas Gregor14f79002009-04-10 03:52:48 +0000808 RecordData Record;
809 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000810 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000811 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000812 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000813 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000814 return Failure;
815 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000816 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000817 }
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Douglas Gregor14f79002009-04-10 03:52:48 +0000819 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
820 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000821 SLocEntryCursor.ReadSubBlockID();
822 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000823 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000824 return Failure;
825 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000826 continue;
827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Douglas Gregor14f79002009-04-10 03:52:48 +0000829 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000830 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000831 continue;
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor14f79002009-04-10 03:52:48 +0000834 // Read a record.
835 const char *BlobStart;
836 unsigned BlobLen;
837 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000838 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 default: // Default behavior: ignore.
840 break;
841
Chris Lattner2c78b872009-04-14 23:22:57 +0000842 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000843 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000844 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000845 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000846
847 case pch::SM_HEADER_FILE_INFO: {
848 HeaderFileInfo HFI;
849 HFI.isImport = Record[0];
850 HFI.DirInfo = Record[1];
851 HFI.NumIncludes = Record[2];
852 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000853 if (Listener)
854 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000855 break;
856 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000857
858 case pch::SM_SLOC_FILE_ENTRY:
859 case pch::SM_SLOC_BUFFER_ENTRY:
860 case pch::SM_SLOC_INSTANTIATION_ENTRY:
861 // Once we hit one of the source location entries, we're done.
862 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000863 }
864 }
865}
866
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000867/// \brief Read in the source location entry with the given ID.
868PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
869 if (ID == 0)
870 return Success;
871
872 if (ID > TotalNumSLocEntries) {
873 Error("source location entry ID out-of-range for PCH file");
874 return Failure;
875 }
876
877 ++NumSLocEntriesRead;
878 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
879 unsigned Code = SLocEntryCursor.ReadCode();
880 if (Code == llvm::bitc::END_BLOCK ||
881 Code == llvm::bitc::ENTER_SUBBLOCK ||
882 Code == llvm::bitc::DEFINE_ABBREV) {
883 Error("incorrectly-formatted source location entry in PCH file");
884 return Failure;
885 }
886
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000887 RecordData Record;
888 const char *BlobStart;
889 unsigned BlobLen;
890 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
891 default:
892 Error("incorrectly-formatted source location entry in PCH file");
893 return Failure;
894
895 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000896 std::string Filename(BlobStart, BlobStart + BlobLen);
897 MaybeAddSystemRootToFilename(Filename);
898 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000899 if (File == 0) {
900 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000901 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000902 ErrorStr += "' referenced by PCH file";
903 Error(ErrorStr.c_str());
904 return Failure;
905 }
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000907 FileID FID = SourceMgr.createFileID(File,
908 SourceLocation::getFromRawEncoding(Record[1]),
909 (SrcMgr::CharacteristicKind)Record[2],
910 ID, Record[0]);
911 if (Record[3])
912 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
913 .setHasLineDirectives();
914
915 break;
916 }
917
918 case pch::SM_SLOC_BUFFER_ENTRY: {
919 const char *Name = BlobStart;
920 unsigned Offset = Record[0];
921 unsigned Code = SLocEntryCursor.ReadCode();
922 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000923 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000924 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
925 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
926 (void)RecCode;
927 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000928 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000929 BlobStart + BlobLen - 1,
930 Name);
931 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregor92b059e2009-04-28 20:33:11 +0000933 if (strcmp(Name, "<built-in>") == 0) {
934 PCHPredefinesBufferID = BufferID;
935 PCHPredefines = BlobStart;
936 PCHPredefinesLen = BlobLen - 1;
937 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000938
939 break;
940 }
941
942 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000943 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000944 = SourceLocation::getFromRawEncoding(Record[1]);
945 SourceMgr.createInstantiationLoc(SpellingLoc,
946 SourceLocation::getFromRawEncoding(Record[2]),
947 SourceLocation::getFromRawEncoding(Record[3]),
948 Record[4],
949 ID,
950 Record[0]);
951 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000952 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000953 }
954
955 return Success;
956}
957
Chris Lattner6367f6d2009-04-27 01:05:14 +0000958/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
959/// specified cursor. Read the abbreviations that are at the top of the block
960/// and then leave the cursor pointing into the block.
961bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
962 unsigned BlockID) {
963 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000964 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000965 return Failure;
966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner6367f6d2009-04-27 01:05:14 +0000968 while (true) {
969 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattner6367f6d2009-04-27 01:05:14 +0000971 // We expect all abbrevs to be at the start of the block.
972 if (Code != llvm::bitc::DEFINE_ABBREV)
973 return false;
974 Cursor.ReadAbbrevRecord();
975 }
976}
977
Douglas Gregor37e26842009-04-21 23:56:24 +0000978void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000979 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor37e26842009-04-21 23:56:24 +0000981 // Keep track of where we are in the stream, then jump back there
982 // after reading this macro.
983 SavedStreamPosition SavedPosition(Stream);
984
985 Stream.JumpToBit(Offset);
986 RecordData Record;
987 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
988 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Douglas Gregor37e26842009-04-21 23:56:24 +0000990 while (true) {
991 unsigned Code = Stream.ReadCode();
992 switch (Code) {
993 case llvm::bitc::END_BLOCK:
994 return;
995
996 case llvm::bitc::ENTER_SUBBLOCK:
997 // No known subblocks, always skip them.
998 Stream.ReadSubBlockID();
999 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001000 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001001 return;
1002 }
1003 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Douglas Gregor37e26842009-04-21 23:56:24 +00001005 case llvm::bitc::DEFINE_ABBREV:
1006 Stream.ReadAbbrevRecord();
1007 continue;
1008 default: break;
1009 }
1010
1011 // Read a record.
1012 Record.clear();
1013 pch::PreprocessorRecordTypes RecType =
1014 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1015 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001016 case pch::PP_MACRO_OBJECT_LIKE:
1017 case pch::PP_MACRO_FUNCTION_LIKE: {
1018 // If we already have a macro, that means that we've hit the end
1019 // of the definition of the macro we were looking for. We're
1020 // done.
1021 if (Macro)
1022 return;
1023
1024 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1025 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001026 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001027 return;
1028 }
1029 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1030 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001032 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001033 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Douglas Gregor37e26842009-04-21 23:56:24 +00001035 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1036 // Decode function-like macro info.
1037 bool isC99VarArgs = Record[3];
1038 bool isGNUVarArgs = Record[4];
1039 MacroArgs.clear();
1040 unsigned NumArgs = Record[5];
1041 for (unsigned i = 0; i != NumArgs; ++i)
1042 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1043
1044 // Install function-like macro info.
1045 MI->setIsFunctionLike();
1046 if (isC99VarArgs) MI->setIsC99Varargs();
1047 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001048 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001049 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001050 }
1051
1052 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001053 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001054
1055 // Remember that we saw this macro last so that we add the tokens that
1056 // form its body to it.
1057 Macro = MI;
1058 ++NumMacrosRead;
1059 break;
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregor37e26842009-04-21 23:56:24 +00001062 case pch::PP_TOKEN: {
1063 // If we see a TOKEN before a PP_MACRO_*, then the file is
1064 // erroneous, just pretend we didn't see this.
1065 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregor37e26842009-04-21 23:56:24 +00001067 Token Tok;
1068 Tok.startToken();
1069 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1070 Tok.setLength(Record[1]);
1071 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1072 Tok.setIdentifierInfo(II);
1073 Tok.setKind((tok::TokenKind)Record[3]);
1074 Tok.setFlag((Token::TokenFlags)Record[4]);
1075 Macro->AddTokenToBody(Tok);
1076 break;
1077 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001078 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001079 }
1080}
1081
Douglas Gregore650c8c2009-07-07 00:12:59 +00001082/// \brief If we are loading a relocatable PCH file, and the filename is
1083/// not an absolute path, add the system root to the beginning of the file
1084/// name.
1085void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1086 // If this is not a relocatable PCH file, there's nothing to do.
1087 if (!RelocatablePCH)
1088 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Daniel Dunbard5b21972009-11-18 19:50:41 +00001090 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001091 return;
1092
Douglas Gregore650c8c2009-07-07 00:12:59 +00001093 if (isysroot == 0) {
1094 // If no system root was given, default to '/'
1095 Filename.insert(Filename.begin(), '/');
1096 return;
1097 }
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregore650c8c2009-07-07 00:12:59 +00001099 unsigned Length = strlen(isysroot);
1100 if (isysroot[Length - 1] != '/')
1101 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregore650c8c2009-07-07 00:12:59 +00001103 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1104}
1105
Mike Stump1eb44332009-09-09 15:08:12 +00001106PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001107PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001108 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001109 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001110 return Failure;
1111 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001112
1113 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001114 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001115 while (!Stream.AtEndOfStream()) {
1116 unsigned Code = Stream.ReadCode();
1117 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001118 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001119 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001120 return Failure;
1121 }
Chris Lattner7356a312009-04-11 21:15:38 +00001122
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001123 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001124 }
1125
1126 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1127 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001128 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001129 // We lazily load the decls block, but we want to set up the
1130 // DeclsCursor cursor to point into it. Clone our current bitcode
1131 // cursor to it, enter the block and read the abbrevs in that block.
1132 // With the main cursor, we just skip over it.
1133 DeclsCursor = Stream;
1134 if (Stream.SkipBlock() || // Skip with the main cursor.
1135 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001136 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001137 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001138 return Failure;
1139 }
1140 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Chris Lattner7356a312009-04-11 21:15:38 +00001142 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001143 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001144 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001145 return Failure;
1146 }
1147 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001148
Douglas Gregor14f79002009-04-10 03:52:48 +00001149 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001150 switch (ReadSourceManagerBlock()) {
1151 case Success:
1152 break;
1153
1154 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001155 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001156 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001157
1158 case IgnorePCH:
1159 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001160 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001161 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001162 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001163 continue;
1164 }
1165
1166 if (Code == llvm::bitc::DEFINE_ABBREV) {
1167 Stream.ReadAbbrevRecord();
1168 continue;
1169 }
1170
1171 // Read and process a record.
1172 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001173 const char *BlobStart = 0;
1174 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001175 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001176 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001177 default: // Default behavior: ignore.
1178 break;
1179
1180 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001181 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001182 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001183 return Failure;
1184 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001185 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001186 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001187 break;
1188
1189 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001190 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001191 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001192 return Failure;
1193 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001194 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001195 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001196 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001197
1198 case pch::LANGUAGE_OPTIONS:
1199 if (ParseLanguageOptions(Record))
1200 return IgnorePCH;
1201 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001202
Douglas Gregorab41e632009-04-27 22:23:34 +00001203 case pch::METADATA: {
1204 if (Record[0] != pch::VERSION_MAJOR) {
1205 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1206 : diag::warn_pch_version_too_new);
1207 return IgnorePCH;
1208 }
1209
Douglas Gregore650c8c2009-07-07 00:12:59 +00001210 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001211 if (Listener) {
1212 std::string TargetTriple(BlobStart, BlobLen);
1213 if (Listener->ReadTargetTriple(TargetTriple))
1214 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001215 }
1216 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001217 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001218
1219 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001220 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001221 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001223 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001224 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001225 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001226 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001227 if (PP)
1228 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001229 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001230 break;
1231
1232 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001233 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001234 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001235 return Failure;
1236 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001237 IdentifierOffsets = (const uint32_t *)BlobStart;
1238 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001239 if (PP)
1240 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001241 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001242
1243 case pch::EXTERNAL_DEFINITIONS:
1244 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001245 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001246 return Failure;
1247 }
1248 ExternalDefinitions.swap(Record);
1249 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001250
Douglas Gregorad1de002009-04-18 05:55:16 +00001251 case pch::SPECIAL_TYPES:
1252 SpecialTypes.swap(Record);
1253 break;
1254
Douglas Gregor3e1af842009-04-17 22:13:46 +00001255 case pch::STATISTICS:
1256 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001257 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001258 TotalLexicalDeclContexts = Record[2];
1259 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001260 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001261
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001262 case pch::TENTATIVE_DEFINITIONS:
1263 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001264 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001265 return Failure;
1266 }
1267 TentativeDefinitions.swap(Record);
1268 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001269
1270 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1271 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001272 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001273 return Failure;
1274 }
1275 LocallyScopedExternalDecls.swap(Record);
1276 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001277
Douglas Gregor83941df2009-04-25 17:48:32 +00001278 case pch::SELECTOR_OFFSETS:
1279 SelectorOffsets = (const uint32_t *)BlobStart;
1280 TotalNumSelectors = Record[0];
1281 SelectorsLoaded.resize(TotalNumSelectors);
1282 break;
1283
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001284 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001285 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1286 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001287 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001288 = PCHMethodPoolLookupTable::Create(
1289 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001290 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001291 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001292 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001293 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001294
1295 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001296 if (!Record.empty() && Listener)
1297 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001298 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001299
1300 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001301 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001302 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001303 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001304 break;
1305
1306 case pch::SOURCE_LOCATION_PRELOADS:
1307 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1308 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1309 if (Result != Success)
1310 return Result;
1311 }
1312 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001313
Douglas Gregor52e71082009-10-16 18:18:30 +00001314 case pch::STAT_CACHE: {
1315 PCHStatCache *MyStatCache =
1316 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1317 (const unsigned char *)BlobStart,
1318 NumStatHits, NumStatMisses);
1319 FileMgr.addStatCache(MyStatCache);
1320 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001321 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001322 }
1323
Douglas Gregorb81c1702009-04-27 20:06:05 +00001324 case pch::EXT_VECTOR_DECLS:
1325 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001326 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001327 return Failure;
1328 }
1329 ExtVectorDecls.swap(Record);
1330 break;
1331
Douglas Gregorb64c1932009-05-12 01:31:05 +00001332 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001333 ActualOriginalFileName.assign(BlobStart, BlobLen);
1334 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001335 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001336 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregor2e222532009-07-02 17:08:52 +00001338 case pch::COMMENT_RANGES:
1339 Comments = (SourceRange *)BlobStart;
1340 NumComments = BlobLen / sizeof(SourceRange);
1341 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001342
1343 case pch::SVN_BRANCH_REVISION: {
1344 unsigned CurRevision = getClangSubversionRevision();
1345 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1346 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1347 : diag::warn_pch_version_too_new);
1348 return IgnorePCH;
1349 }
1350
1351 const char *CurBranch = getClangSubversionPath();
1352 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1353 std::string PCHBranch(BlobStart, BlobLen);
1354 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1355 return IgnorePCH;
1356 }
1357 break;
1358 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001359 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001360 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001361 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001362 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001363}
1364
Douglas Gregore1d918e2009-04-10 23:10:45 +00001365PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001366 // Set the PCH file name.
1367 this->FileName = FileName;
1368
Douglas Gregor2cf26342009-04-09 22:27:44 +00001369 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001370 //
1371 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001372 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001373 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001374 if (!Buffer) {
1375 Error(ErrStr.c_str());
1376 return IgnorePCH;
1377 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001378
1379 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001380 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001381 (const unsigned char *)Buffer->getBufferEnd());
1382 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001383
1384 // Sniff for the signature.
1385 if (Stream.Read(8) != 'C' ||
1386 Stream.Read(8) != 'P' ||
1387 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001388 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001389 Diag(diag::err_not_a_pch_file) << FileName;
1390 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001391 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001392
Douglas Gregor2cf26342009-04-09 22:27:44 +00001393 while (!Stream.AtEndOfStream()) {
1394 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregore1d918e2009-04-10 23:10:45 +00001396 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001397 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001398 return Failure;
1399 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001400
1401 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001402
Douglas Gregor2cf26342009-04-09 22:27:44 +00001403 // We only know the PCH subblock ID.
1404 switch (BlockID) {
1405 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001406 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001407 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001408 return Failure;
1409 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001410 break;
1411 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001412 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001413 case Success:
1414 break;
1415
1416 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001417 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001418
1419 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001420 // FIXME: We could consider reading through to the end of this
1421 // PCH block, skipping subblocks, to see if there are other
1422 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001423
1424 // Clear out any preallocated source location entries, so that
1425 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001426 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001427
1428 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001429 if (StatCache)
1430 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001431
Douglas Gregore1d918e2009-04-10 23:10:45 +00001432 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001433 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001434 break;
1435 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001436 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001437 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001438 return Failure;
1439 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001440 break;
1441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442 }
1443
Douglas Gregor92b059e2009-04-28 20:33:11 +00001444 // Check the predefines buffer.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +00001445 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregor92b059e2009-04-28 20:33:11 +00001446 PCHPredefinesBufferID))
1447 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001449 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001450 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001451 // PCH file is read, so there may be some identifiers that were
1452 // loaded into the IdentifierTable before we intercepted the
1453 // creation of identifiers. Iterate through the list of known
1454 // identifiers and determine whether we have to establish
1455 // preprocessor definitions or top-level identifier declaration
1456 // chains for those identifiers.
1457 //
1458 // We copy the IdentifierInfo pointers to a small vector first,
1459 // since de-serializing declarations or macro definitions can add
1460 // new entries into the identifier table, invalidating the
1461 // iterators.
1462 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1463 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1464 IdEnd = PP->getIdentifierTable().end();
1465 Id != IdEnd; ++Id)
1466 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001467 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001468 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1469 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1470 IdentifierInfo *II = Identifiers[I];
1471 // Look in the on-disk hash table for an entry for
1472 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001473 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001474 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1475 if (Pos == IdTable->end())
1476 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001478 // Dereferencing the iterator has the effect of populating the
1479 // IdentifierInfo node with the various declarations it needs.
1480 (void)*Pos;
1481 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001482 }
1483
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001484 if (Context)
1485 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001486
Douglas Gregor668c1a42009-04-21 22:25:48 +00001487 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001488}
1489
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001490void PCHReader::InitializeContext(ASTContext &Ctx) {
1491 Context = &Ctx;
1492 assert(Context && "Passed null context!");
1493
1494 assert(PP && "Forgot to set Preprocessor ?");
1495 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1496 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001498 // Load the translation unit declaration
1499 ReadDeclRecord(DeclOffsets[0], 0);
1500
1501 // Load the special types.
1502 Context->setBuiltinVaListType(
1503 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1504 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1505 Context->setObjCIdType(GetType(Id));
1506 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1507 Context->setObjCSelType(GetType(Sel));
1508 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1509 Context->setObjCProtoType(GetType(Proto));
1510 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1511 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001512
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001513 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1514 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001515 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001516 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1517 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001518 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1519 QualType FileType = GetType(File);
1520 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001521 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001522 Context->setFILEDecl(Typedef->getDecl());
1523 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001524 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001525 assert(Tag && "Invalid FILE type in PCH file");
1526 Context->setFILEDecl(Tag->getDecl());
1527 }
1528 }
Mike Stump782fa302009-07-28 02:25:19 +00001529 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1530 QualType Jmp_bufType = GetType(Jmp_buf);
1531 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001532 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001533 Context->setjmp_bufDecl(Typedef->getDecl());
1534 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001535 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001536 assert(Tag && "Invalid jmp_bug type in PCH file");
1537 Context->setjmp_bufDecl(Tag->getDecl());
1538 }
1539 }
1540 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1541 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1542 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001543 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001544 Context->setsigjmp_bufDecl(Typedef->getDecl());
1545 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001546 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001547 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1548 Context->setsigjmp_bufDecl(Tag->getDecl());
1549 }
1550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001552 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1553 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001554 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001555 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1556 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001557#if 0
1558 // FIXME. Accommodate for this in several PCH/Index tests
1559 if (unsigned ObjCSelRedef
1560 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00001561 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00001562#endif
Mike Stumpadaaad32009-10-20 02:12:22 +00001563 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1564 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001565 if (unsigned String
1566 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1567 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001568}
1569
Douglas Gregorb64c1932009-05-12 01:31:05 +00001570/// \brief Retrieve the name of the original source file name
1571/// directly from the PCH file, without actually loading the PCH
1572/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001573std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1574 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00001575 // Open the PCH file.
1576 std::string ErrStr;
1577 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1578 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1579 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001580 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001581 return std::string();
1582 }
1583
1584 // Initialize the stream
1585 llvm::BitstreamReader StreamFile;
1586 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001587 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001588 (const unsigned char *)Buffer->getBufferEnd());
1589 Stream.init(StreamFile);
1590
1591 // Sniff for the signature.
1592 if (Stream.Read(8) != 'C' ||
1593 Stream.Read(8) != 'P' ||
1594 Stream.Read(8) != 'C' ||
1595 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001596 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001597 return std::string();
1598 }
1599
1600 RecordData Record;
1601 while (!Stream.AtEndOfStream()) {
1602 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregorb64c1932009-05-12 01:31:05 +00001604 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1605 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregorb64c1932009-05-12 01:31:05 +00001607 // We only know the PCH subblock ID.
1608 switch (BlockID) {
1609 case pch::PCH_BLOCK_ID:
1610 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001611 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001612 return std::string();
1613 }
1614 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregorb64c1932009-05-12 01:31:05 +00001616 default:
1617 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001618 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001619 return std::string();
1620 }
1621 break;
1622 }
1623 continue;
1624 }
1625
1626 if (Code == llvm::bitc::END_BLOCK) {
1627 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001628 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001629 return std::string();
1630 }
1631 continue;
1632 }
1633
1634 if (Code == llvm::bitc::DEFINE_ABBREV) {
1635 Stream.ReadAbbrevRecord();
1636 continue;
1637 }
1638
1639 Record.clear();
1640 const char *BlobStart = 0;
1641 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001642 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001643 == pch::ORIGINAL_FILE_NAME)
1644 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001645 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001646
1647 return std::string();
1648}
1649
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001650/// \brief Parse the record that corresponds to a LangOptions data
1651/// structure.
1652///
1653/// This routine compares the language options used to generate the
1654/// PCH file against the language options set for the current
1655/// compilation. For each option, we classify differences between the
1656/// two compiler states as either "benign" or "important". Benign
1657/// differences don't matter, and we accept them without complaint
1658/// (and without modifying the language options). Differences between
1659/// the states for important options cause the PCH file to be
1660/// unusable, so we emit a warning and return true to indicate that
1661/// there was an error.
1662///
1663/// \returns true if the PCH file is unacceptable, false otherwise.
1664bool PCHReader::ParseLanguageOptions(
1665 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001666 if (Listener) {
1667 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001669 #define PARSE_LANGOPT(Option) \
1670 LangOpts.Option = Record[Idx]; \
1671 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001673 unsigned Idx = 0;
1674 PARSE_LANGOPT(Trigraphs);
1675 PARSE_LANGOPT(BCPLComment);
1676 PARSE_LANGOPT(DollarIdents);
1677 PARSE_LANGOPT(AsmPreprocessor);
1678 PARSE_LANGOPT(GNUMode);
1679 PARSE_LANGOPT(ImplicitInt);
1680 PARSE_LANGOPT(Digraphs);
1681 PARSE_LANGOPT(HexFloats);
1682 PARSE_LANGOPT(C99);
1683 PARSE_LANGOPT(Microsoft);
1684 PARSE_LANGOPT(CPlusPlus);
1685 PARSE_LANGOPT(CPlusPlus0x);
1686 PARSE_LANGOPT(CXXOperatorNames);
1687 PARSE_LANGOPT(ObjC1);
1688 PARSE_LANGOPT(ObjC2);
1689 PARSE_LANGOPT(ObjCNonFragileABI);
1690 PARSE_LANGOPT(PascalStrings);
1691 PARSE_LANGOPT(WritableStrings);
1692 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001693 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001694 PARSE_LANGOPT(Exceptions);
1695 PARSE_LANGOPT(NeXTRuntime);
1696 PARSE_LANGOPT(Freestanding);
1697 PARSE_LANGOPT(NoBuiltin);
1698 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001699 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001700 PARSE_LANGOPT(Blocks);
1701 PARSE_LANGOPT(EmitAllDecls);
1702 PARSE_LANGOPT(MathErrno);
1703 PARSE_LANGOPT(OverflowChecking);
1704 PARSE_LANGOPT(HeinousExtensions);
1705 PARSE_LANGOPT(Optimize);
1706 PARSE_LANGOPT(OptimizeSize);
1707 PARSE_LANGOPT(Static);
1708 PARSE_LANGOPT(PICLevel);
1709 PARSE_LANGOPT(GNUInline);
1710 PARSE_LANGOPT(NoInline);
1711 PARSE_LANGOPT(AccessControl);
1712 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001713 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001714 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1715 ++Idx;
1716 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1717 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001718 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1719 Record[Idx]);
1720 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001721 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001722 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00001723 PARSE_LANGOPT(CatchUndefined);
1724 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001725 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001726
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001727 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001728 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001729
1730 return false;
1731}
1732
Douglas Gregor2e222532009-07-02 17:08:52 +00001733void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1734 Comments.resize(NumComments);
1735 std::copy(this->Comments, this->Comments + NumComments,
1736 Comments.begin());
1737}
1738
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739/// \brief Read and return the type at the given offset.
1740///
1741/// This routine actually reads the record corresponding to the type
1742/// at the given offset in the bitstream. It is a helper routine for
1743/// GetType, which deals with reading type IDs.
1744QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001745 // Keep track of where we are in the stream, then jump back there
1746 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001747 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001748
Douglas Gregord89275b2009-07-06 18:54:52 +00001749 // Note that we are loading a type record.
1750 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001752 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001753 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001754 unsigned Code = DeclsCursor.ReadCode();
1755 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001756 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001757 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001758 "Incorrect encoding of extended qualifier type");
1759 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001760 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1761 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001762 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001763
Douglas Gregor2cf26342009-04-09 22:27:44 +00001764 case pch::TYPE_FIXED_WIDTH_INT: {
1765 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001766 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767 }
1768
1769 case pch::TYPE_COMPLEX: {
1770 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1771 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001772 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773 }
1774
1775 case pch::TYPE_POINTER: {
1776 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1777 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001778 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001779 }
1780
1781 case pch::TYPE_BLOCK_POINTER: {
1782 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1783 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001784 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001785 }
1786
1787 case pch::TYPE_LVALUE_REFERENCE: {
1788 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1789 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001790 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791 }
1792
1793 case pch::TYPE_RVALUE_REFERENCE: {
1794 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1795 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001796 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001797 }
1798
1799 case pch::TYPE_MEMBER_POINTER: {
1800 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1801 QualType PointeeType = GetType(Record[0]);
1802 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001803 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001804 }
1805
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001806 case pch::TYPE_CONSTANT_ARRAY: {
1807 QualType ElementType = GetType(Record[0]);
1808 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1809 unsigned IndexTypeQuals = Record[2];
1810 unsigned Idx = 3;
1811 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001812 return Context->getConstantArrayType(ElementType, Size,
1813 ASM, IndexTypeQuals);
1814 }
1815
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001816 case pch::TYPE_INCOMPLETE_ARRAY: {
1817 QualType ElementType = GetType(Record[0]);
1818 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1819 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001820 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001821 }
1822
1823 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001824 QualType ElementType = GetType(Record[0]);
1825 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1826 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001827 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1828 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001829 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001830 ASM, IndexTypeQuals,
1831 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001832 }
1833
1834 case pch::TYPE_VECTOR: {
1835 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001836 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001837 return QualType();
1838 }
1839
1840 QualType ElementType = GetType(Record[0]);
1841 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001842 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001843 }
1844
1845 case pch::TYPE_EXT_VECTOR: {
1846 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001847 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001848 return QualType();
1849 }
1850
1851 QualType ElementType = GetType(Record[0]);
1852 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001853 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001854 }
1855
1856 case pch::TYPE_FUNCTION_NO_PROTO: {
1857 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001858 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001859 return QualType();
1860 }
1861 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001862 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001863 }
1864
1865 case pch::TYPE_FUNCTION_PROTO: {
1866 QualType ResultType = GetType(Record[0]);
1867 unsigned Idx = 1;
1868 unsigned NumParams = Record[Idx++];
1869 llvm::SmallVector<QualType, 16> ParamTypes;
1870 for (unsigned I = 0; I != NumParams; ++I)
1871 ParamTypes.push_back(GetType(Record[Idx++]));
1872 bool isVariadic = Record[Idx++];
1873 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001874 bool hasExceptionSpec = Record[Idx++];
1875 bool hasAnyExceptionSpec = Record[Idx++];
1876 unsigned NumExceptions = Record[Idx++];
1877 llvm::SmallVector<QualType, 2> Exceptions;
1878 for (unsigned I = 0; I != NumExceptions; ++I)
1879 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001880 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001881 isVariadic, Quals, hasExceptionSpec,
1882 hasAnyExceptionSpec, NumExceptions,
1883 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001884 }
1885
John McCalled976492009-12-04 22:46:56 +00001886 case pch::TYPE_UNRESOLVED_USING:
1887 return Context->getTypeDeclType(
1888 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1889
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001890 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001891 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001892 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001893
1894 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001895 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001896
1897 case pch::TYPE_TYPEOF: {
1898 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001899 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001900 return QualType();
1901 }
1902 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001903 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Anders Carlsson395b4752009-06-24 19:06:50 +00001906 case pch::TYPE_DECLTYPE:
1907 return Context->getDecltypeType(ReadTypeExpr());
1908
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001909 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001910 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001911 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001912
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001913 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001914 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001915 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001916
John McCall7da24312009-09-05 00:15:47 +00001917 case pch::TYPE_ELABORATED: {
1918 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1919 unsigned Tag = Record[1];
1920 return Context->getElaboratedType(GetType(Record[0]),
1921 (ElaboratedType::TagKind) Tag);
1922 }
1923
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001924 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001925 unsigned Idx = 0;
1926 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1927 unsigned NumProtos = Record[Idx++];
1928 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1929 for (unsigned I = 0; I != NumProtos; ++I)
1930 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001931 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001932 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001933
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001934 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001935 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001936 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001937 unsigned NumProtos = Record[Idx++];
1938 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1939 for (unsigned I = 0; I != NumProtos; ++I)
1940 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001941 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001942 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001943
John McCall49a832b2009-10-18 09:09:24 +00001944 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1945 unsigned Idx = 0;
1946 QualType Parm = GetType(Record[Idx++]);
1947 QualType Replacement = GetType(Record[Idx++]);
1948 return
1949 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1950 Replacement);
1951 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001952 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001953 // Suppress a GCC warning
1954 return QualType();
1955}
1956
John McCalla1ee0c52009-10-16 21:56:05 +00001957namespace {
1958
1959class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1960 PCHReader &Reader;
1961 const PCHReader::RecordData &Record;
1962 unsigned &Idx;
1963
1964public:
1965 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1966 unsigned &Idx)
1967 : Reader(Reader), Record(Record), Idx(Idx) { }
1968
John McCall51bd8032009-10-18 01:05:36 +00001969 // We want compile-time assurance that we've enumerated all of
1970 // these, so unfortunately we have to declare them first, then
1971 // define them out-of-line.
1972#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00001973#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00001974 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001975#include "clang/AST/TypeLocNodes.def"
1976
John McCall51bd8032009-10-18 01:05:36 +00001977 void VisitFunctionTypeLoc(FunctionTypeLoc);
1978 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001979};
1980
1981}
1982
John McCall51bd8032009-10-18 01:05:36 +00001983void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00001984 // nothing to do
1985}
John McCall51bd8032009-10-18 01:05:36 +00001986void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1987 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001988}
John McCall51bd8032009-10-18 01:05:36 +00001989void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1990 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001991}
John McCall51bd8032009-10-18 01:05:36 +00001992void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1993 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001994}
John McCall51bd8032009-10-18 01:05:36 +00001995void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1996 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001997}
John McCall51bd8032009-10-18 01:05:36 +00001998void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1999 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002000}
John McCall51bd8032009-10-18 01:05:36 +00002001void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2002 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002003}
John McCall51bd8032009-10-18 01:05:36 +00002004void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2005 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002006}
John McCall51bd8032009-10-18 01:05:36 +00002007void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2008 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002009}
John McCall51bd8032009-10-18 01:05:36 +00002010void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2011 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2012 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002013 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002014 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002015 else
John McCall51bd8032009-10-18 01:05:36 +00002016 TL.setSizeExpr(0);
2017}
2018void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2019 VisitArrayTypeLoc(TL);
2020}
2021void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2022 VisitArrayTypeLoc(TL);
2023}
2024void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2025 VisitArrayTypeLoc(TL);
2026}
2027void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2028 DependentSizedArrayTypeLoc TL) {
2029 VisitArrayTypeLoc(TL);
2030}
2031void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2032 DependentSizedExtVectorTypeLoc TL) {
2033 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2034}
2035void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2036 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2037}
2038void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2039 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2040}
2041void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2042 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2043 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2044 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002045 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002046 }
2047}
2048void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2049 VisitFunctionTypeLoc(TL);
2050}
2051void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2052 VisitFunctionTypeLoc(TL);
2053}
John McCalled976492009-12-04 22:46:56 +00002054void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2055 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2056}
John McCall51bd8032009-10-18 01:05:36 +00002057void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2058 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2059}
2060void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2061 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2062}
2063void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2064 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2065}
2066void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2067 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2068}
2069void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2070 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2071}
2072void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2073 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2074}
2075void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2076 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2077}
2078void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2079 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2080}
John McCall49a832b2009-10-18 09:09:24 +00002081void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2082 SubstTemplateTypeParmTypeLoc TL) {
2083 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2084}
John McCall51bd8032009-10-18 01:05:36 +00002085void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2086 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002087 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2088 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2089 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2090 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2091 TL.setArgLocInfo(i,
2092 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2093 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002094}
2095void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2096 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097}
2098void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2099 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2100}
2101void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2102 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002103 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2104 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2105 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2106 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002107}
John McCall54e14c42009-10-22 22:37:11 +00002108void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2109 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2110 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2111 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2112 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2113 TL.setHasProtocolsAsWritten(Record[Idx++]);
2114 if (TL.hasProtocolsAsWritten())
2115 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2116 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2117}
John McCalla1ee0c52009-10-16 21:56:05 +00002118
John McCalla93c9342009-12-07 02:54:59 +00002119TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002120 unsigned &Idx) {
2121 QualType InfoTy = GetType(Record[Idx++]);
2122 if (InfoTy.isNull())
2123 return 0;
2124
John McCalla93c9342009-12-07 02:54:59 +00002125 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCalla1ee0c52009-10-16 21:56:05 +00002126 TypeLocReader TLR(*this, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002127 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002128 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002129 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002130}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002131
Douglas Gregor8038d512009-04-10 17:25:41 +00002132QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002133 unsigned FastQuals = ID & Qualifiers::FastMask;
2134 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002135
2136 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2137 QualType T;
2138 switch ((pch::PredefinedTypeIDs)Index) {
2139 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002140 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2141 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002142
2143 case pch::PREDEF_TYPE_CHAR_U_ID:
2144 case pch::PREDEF_TYPE_CHAR_S_ID:
2145 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002146 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002147 break;
2148
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002149 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2150 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2151 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2152 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2153 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002154 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002155 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2156 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2157 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2158 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2159 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2160 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002161 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002162 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2163 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2164 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2165 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2166 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002167 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002168 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2169 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002170 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2171 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002172 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002173 }
2174
2175 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002176 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002177 }
2178
2179 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002180 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002181 if (TypesLoaded[Index].isNull())
2182 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002183
John McCall0953e762009-09-24 19:53:00 +00002184 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002185}
2186
John McCall833ca992009-10-29 08:12:44 +00002187TemplateArgumentLocInfo
2188PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2189 const RecordData &Record,
2190 unsigned &Index) {
2191 switch (Kind) {
2192 case TemplateArgument::Expression:
2193 return ReadDeclExpr();
2194 case TemplateArgument::Type:
John McCalla93c9342009-12-07 02:54:59 +00002195 return GetTypeSourceInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002196 case TemplateArgument::Template: {
2197 SourceLocation
2198 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2199 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2200 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2201 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2202 TemplateNameLoc);
2203 }
John McCall833ca992009-10-29 08:12:44 +00002204 case TemplateArgument::Null:
2205 case TemplateArgument::Integral:
2206 case TemplateArgument::Declaration:
2207 case TemplateArgument::Pack:
2208 return TemplateArgumentLocInfo();
2209 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002210 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002211 return TemplateArgumentLocInfo();
2212}
2213
Douglas Gregor8038d512009-04-10 17:25:41 +00002214Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002215 if (ID == 0)
2216 return 0;
2217
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002218 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002219 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002220 return 0;
2221 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002222
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002223 unsigned Index = ID - 1;
2224 if (!DeclsLoaded[Index])
2225 ReadDeclRecord(DeclOffsets[Index], Index);
2226
2227 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002228}
2229
Chris Lattner887e2b32009-04-27 05:46:25 +00002230/// \brief Resolve the offset of a statement into a statement.
2231///
2232/// This operation will read a new statement from the external
2233/// source each time it is called, and is meant to be used via a
2234/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2235Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002236 // Since we know tha this statement is part of a decl, make sure to use the
2237 // decl cursor to read it.
2238 DeclsCursor.JumpToBit(Offset);
2239 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002240}
2241
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002243 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002244 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002245 "DeclContext has no lexical decls in storage");
2246 uint64_t Offset = DeclContextOffsets[DC].first;
2247 assert(Offset && "DeclContext has no lexical decls in storage");
2248
Douglas Gregor0b748912009-04-14 21:18:50 +00002249 // Keep track of where we are in the stream, then jump back there
2250 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002251 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002252
Douglas Gregor2cf26342009-04-09 22:27:44 +00002253 // Load the record containing all of the declarations lexically in
2254 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002255 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002256 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002257 unsigned Code = DeclsCursor.ReadCode();
2258 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002259 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002260 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2261
2262 // Load all of the declaration IDs
2263 Decls.clear();
2264 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002265 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002266 return false;
2267}
2268
2269bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002270 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002271 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002272 "DeclContext has no visible decls in storage");
2273 uint64_t Offset = DeclContextOffsets[DC].second;
2274 assert(Offset && "DeclContext has no visible decls in storage");
2275
Douglas Gregor0b748912009-04-14 21:18:50 +00002276 // Keep track of where we are in the stream, then jump back there
2277 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002278 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002279
Douglas Gregor2cf26342009-04-09 22:27:44 +00002280 // Load the record containing all of the declarations visible in
2281 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002282 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002283 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002284 unsigned Code = DeclsCursor.ReadCode();
2285 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002286 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002287 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2288 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002289 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002290
2291 Decls.clear();
2292
2293 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002294 while (Idx < Record.size()) {
2295 Decls.push_back(VisibleDeclaration());
2296 Decls.back().Name = ReadDeclarationName(Record, Idx);
2297
Douglas Gregor2cf26342009-04-09 22:27:44 +00002298 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002299 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002300 LoadedDecls.reserve(Size);
2301 for (unsigned I = 0; I < Size; ++I)
2302 LoadedDecls.push_back(Record[Idx++]);
2303 }
2304
Douglas Gregor25123082009-04-22 22:34:57 +00002305 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002306 return false;
2307}
2308
Douglas Gregorfdd01722009-04-14 00:24:19 +00002309void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002310 this->Consumer = Consumer;
2311
Douglas Gregorfdd01722009-04-14 00:24:19 +00002312 if (!Consumer)
2313 return;
2314
2315 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002316 // Force deserialization of this decl, which will cause it to be passed to
2317 // the consumer (or queued).
2318 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002319 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002320
2321 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2322 DeclGroupRef DG(InterestingDecls[I]);
2323 Consumer->HandleTopLevelDecl(DG);
2324 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002325}
2326
Douglas Gregor2cf26342009-04-09 22:27:44 +00002327void PCHReader::PrintStats() {
2328 std::fprintf(stderr, "*** PCH Statistics:\n");
2329
Mike Stump1eb44332009-09-09 15:08:12 +00002330 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002331 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002332 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002333 unsigned NumDeclsLoaded
2334 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2335 (Decl *)0);
2336 unsigned NumIdentifiersLoaded
2337 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2338 IdentifiersLoaded.end(),
2339 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002340 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002341 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2342 SelectorsLoaded.end(),
2343 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002344
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002345 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2346 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002347 if (TotalNumSLocEntries)
2348 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2349 NumSLocEntriesRead, TotalNumSLocEntries,
2350 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002351 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002352 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002353 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2354 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2355 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002356 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002357 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2358 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002359 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002360 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002361 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2362 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002363 if (TotalNumSelectors)
2364 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2365 NumSelectorsLoaded, TotalNumSelectors,
2366 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2367 if (TotalNumStatements)
2368 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2369 NumStatementsRead, TotalNumStatements,
2370 ((float)NumStatementsRead/TotalNumStatements * 100));
2371 if (TotalNumMacros)
2372 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2373 NumMacrosRead, TotalNumMacros,
2374 ((float)NumMacrosRead/TotalNumMacros * 100));
2375 if (TotalLexicalDeclContexts)
2376 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2377 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2378 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2379 * 100));
2380 if (TotalVisibleDeclContexts)
2381 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2382 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2383 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2384 * 100));
2385 if (TotalSelectorsInMethodPool) {
2386 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2387 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2388 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2389 * 100));
2390 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2391 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002392 std::fprintf(stderr, "\n");
2393}
2394
Douglas Gregor668c1a42009-04-21 22:25:48 +00002395void PCHReader::InitializeSema(Sema &S) {
2396 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002397 S.ExternalSource = this;
2398
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002399 // Makes sure any declarations that were deserialized "too early"
2400 // still get added to the identifier's declaration chains.
2401 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2402 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2403 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002404 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002405 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002406
2407 // If there were any tentative definitions, deserialize them and add
2408 // them to Sema's table of tentative definitions.
2409 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2410 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2411 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002412 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002413 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002414
2415 // If there were any locally-scoped external declarations,
2416 // deserialize them and add them to Sema's table of locally-scoped
2417 // external declarations.
2418 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2419 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2420 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2421 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002422
2423 // If there were any ext_vector type declarations, deserialize them
2424 // and add them to Sema's vector of such declarations.
2425 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2426 SemaObj->ExtVectorDecls.push_back(
2427 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002428}
2429
2430IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2431 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002432 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002433 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2434 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2435 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2436 if (Pos == IdTable->end())
2437 return 0;
2438
2439 // Dereferencing the iterator has the effect of building the
2440 // IdentifierInfo node and populating it with the various
2441 // declarations it needs.
2442 return *Pos;
2443}
2444
Mike Stump1eb44332009-09-09 15:08:12 +00002445std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002446PCHReader::ReadMethodPool(Selector Sel) {
2447 if (!MethodPoolLookupTable)
2448 return std::pair<ObjCMethodList, ObjCMethodList>();
2449
2450 // Try to find this selector within our on-disk hash table.
2451 PCHMethodPoolLookupTable *PoolTable
2452 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2453 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002454 if (Pos == PoolTable->end()) {
2455 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002456 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002457 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002458
Douglas Gregor83941df2009-04-25 17:48:32 +00002459 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002460 return *Pos;
2461}
2462
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002463void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002464 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002465 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002466 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002467}
2468
Douglas Gregord89275b2009-07-06 18:54:52 +00002469/// \brief Set the globally-visible declarations associated with the given
2470/// identifier.
2471///
2472/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002473/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002474/// them.
2475///
2476/// \param II an IdentifierInfo that refers to one or more globally-visible
2477/// declarations.
2478///
2479/// \param DeclIDs the set of declaration IDs with the name @p II that are
2480/// visible at global scope.
2481///
2482/// \param Nonrecursive should be true to indicate that the caller knows that
2483/// this call is non-recursive, and therefore the globally-visible declarations
2484/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002485void
2486PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002487 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2488 bool Nonrecursive) {
2489 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2490 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2491 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2492 PII.II = II;
2493 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2494 PII.DeclIDs.push_back(DeclIDs[I]);
2495 return;
2496 }
Mike Stump1eb44332009-09-09 15:08:12 +00002497
Douglas Gregord89275b2009-07-06 18:54:52 +00002498 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2499 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2500 if (SemaObj) {
2501 // Introduce this declaration into the translation-unit scope
2502 // and add it to the declaration chain for this identifier, so
2503 // that (unqualified) name lookup will find it.
2504 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2505 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2506 } else {
2507 // Queue this declaration so that it will be added to the
2508 // translation unit scope and identifier's declaration chain
2509 // once a Sema object is known.
2510 PreloadedDecls.push_back(D);
2511 }
2512 }
2513}
2514
Chris Lattner7356a312009-04-11 21:15:38 +00002515IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002516 if (ID == 0)
2517 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002518
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002519 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002520 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002521 return 0;
2522 }
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002524 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002525 if (!IdentifiersLoaded[ID - 1]) {
2526 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002527 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002528
Douglas Gregor02fc7512009-04-28 20:01:51 +00002529 // All of the strings in the PCH file are preceded by a 16-bit
2530 // length. Extract that 16-bit length to avoid having to execute
2531 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002532 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2533 // unsigned integers. This is important to avoid integer overflow when
2534 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002535 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002536 unsigned StrLen = (((unsigned) StrLenPtr[0])
2537 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002538 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002539 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002540 }
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002542 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002543}
2544
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002545void PCHReader::ReadSLocEntry(unsigned ID) {
2546 ReadSLocEntryRecord(ID);
2547}
2548
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002549Selector PCHReader::DecodeSelector(unsigned ID) {
2550 if (ID == 0)
2551 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregora02b1472009-04-28 21:53:25 +00002553 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002554 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002555
2556 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002557 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002558 return Selector();
2559 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002560
2561 unsigned Index = ID - 1;
2562 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2563 // Load this selector from the selector table.
2564 // FIXME: endianness portability issues with SelectorOffsets table
2565 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002566 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002567 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2568 }
2569
2570 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002571}
2572
Mike Stump1eb44332009-09-09 15:08:12 +00002573DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002574PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2575 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2576 switch (Kind) {
2577 case DeclarationName::Identifier:
2578 return DeclarationName(GetIdentifierInfo(Record, Idx));
2579
2580 case DeclarationName::ObjCZeroArgSelector:
2581 case DeclarationName::ObjCOneArgSelector:
2582 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002583 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002584
2585 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002586 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002587 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002588
2589 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002590 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002591 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002592
2593 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002594 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002595 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002596
2597 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002598 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002599 (OverloadedOperatorKind)Record[Idx++]);
2600
Sean Hunt3e518bd2009-11-29 07:34:05 +00002601 case DeclarationName::CXXLiteralOperatorName:
2602 return Context->DeclarationNames.getCXXLiteralOperatorName(
2603 GetIdentifierInfo(Record, Idx));
2604
Douglas Gregor2cf26342009-04-09 22:27:44 +00002605 case DeclarationName::CXXUsingDirective:
2606 return DeclarationName::getUsingDirectiveName();
2607 }
2608
2609 // Required to silence GCC warning
2610 return DeclarationName();
2611}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002612
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002613/// \brief Read an integral value
2614llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2615 unsigned BitWidth = Record[Idx++];
2616 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2617 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2618 Idx += NumWords;
2619 return Result;
2620}
2621
2622/// \brief Read a signed integral value
2623llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2624 bool isUnsigned = Record[Idx++];
2625 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2626}
2627
Douglas Gregor17fc2232009-04-14 21:55:33 +00002628/// \brief Read a floating-point value
2629llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002630 return llvm::APFloat(ReadAPInt(Record, Idx));
2631}
2632
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002633// \brief Read a string
2634std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2635 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002636 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002637 Idx += Len;
2638 return Result;
2639}
2640
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002641DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002642 return Diag(SourceLocation(), DiagID);
2643}
2644
2645DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002646 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002647}
Douglas Gregor025452f2009-04-17 00:04:06 +00002648
Douglas Gregor668c1a42009-04-21 22:25:48 +00002649/// \brief Retrieve the identifier table associated with the
2650/// preprocessor.
2651IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002652 assert(PP && "Forgot to set Preprocessor ?");
2653 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002654}
2655
Douglas Gregor025452f2009-04-17 00:04:06 +00002656/// \brief Record that the given ID maps to the given switch-case
2657/// statement.
2658void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2659 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2660 SwitchCaseStmts[ID] = SC;
2661}
2662
2663/// \brief Retrieve the switch-case statement with the given ID.
2664SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2665 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2666 return SwitchCaseStmts[ID];
2667}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002668
2669/// \brief Record that the given label statement has been
2670/// deserialized and has the given ID.
2671void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002672 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002673 "Deserialized label twice");
2674 LabelStmts[ID] = S;
2675
2676 // If we've already seen any goto statements that point to this
2677 // label, resolve them now.
2678 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2679 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2680 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2681 Goto->second->setLabel(S);
2682 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002683
2684 // If we've already seen any address-label statements that point to
2685 // this label, resolve them now.
2686 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002687 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002688 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002689 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002690 AddrLabel != AddrLabels.second; ++AddrLabel)
2691 AddrLabel->second->setLabel(S);
2692 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002693}
2694
2695/// \brief Set the label of the given statement to the label
2696/// identified by ID.
2697///
2698/// Depending on the order in which the label and other statements
2699/// referencing that label occur, this operation may complete
2700/// immediately (updating the statement) or it may queue the
2701/// statement to be back-patched later.
2702void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2703 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2704 if (Label != LabelStmts.end()) {
2705 // We've already seen this label, so set the label of the goto and
2706 // we're done.
2707 S->setLabel(Label->second);
2708 } else {
2709 // We haven't seen this label yet, so add this goto to the set of
2710 // unresolved goto statements.
2711 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2712 }
2713}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002714
2715/// \brief Set the label of the given expression to the label
2716/// identified by ID.
2717///
2718/// Depending on the order in which the label and other statements
2719/// referencing that label occur, this operation may complete
2720/// immediately (updating the statement) or it may queue the
2721/// statement to be back-patched later.
2722void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2723 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2724 if (Label != LabelStmts.end()) {
2725 // We've already seen this label, so set the label of the
2726 // label-address expression and we're done.
2727 S->setLabel(Label->second);
2728 } else {
2729 // We haven't seen this label yet, so add this label-address
2730 // expression to the set of unresolved label-address expressions.
2731 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2732 }
2733}
Douglas Gregord89275b2009-07-06 18:54:52 +00002734
2735
Mike Stump1eb44332009-09-09 15:08:12 +00002736PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002737 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2738 Reader.CurrentlyLoadingTypeOrDecl = this;
2739}
2740
2741PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2742 if (!Parent) {
2743 // If any identifiers with corresponding top-level declarations have
2744 // been loaded, load those declarations now.
2745 while (!Reader.PendingIdentifierInfos.empty()) {
2746 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2747 Reader.PendingIdentifierInfos.front().DeclIDs,
2748 true);
2749 Reader.PendingIdentifierInfos.pop_front();
2750 }
2751 }
2752
Mike Stump1eb44332009-09-09 15:08:12 +00002753 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002754}