blob: 641ab9f6231a37028797973c290606710bd9ad4c [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"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000021#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000025#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000027#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000030#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000037#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000039#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000043// PCH reader validator implementation
44//===----------------------------------------------------------------------===//
45
46PCHReaderListener::~PCHReaderListener() {}
47
48bool
49PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
50 const LangOptions &PPLangOpts = PP.getLangOptions();
51#define PARSE_LANGOPT_BENIGN(Option)
52#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
53 if (PPLangOpts.Option != LangOpts.Option) { \
54 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
55 return true; \
56 }
57
58 PARSE_LANGOPT_BENIGN(Trigraphs);
59 PARSE_LANGOPT_BENIGN(BCPLComment);
60 PARSE_LANGOPT_BENIGN(DollarIdents);
61 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
62 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
63 PARSE_LANGOPT_BENIGN(ImplicitInt);
64 PARSE_LANGOPT_BENIGN(Digraphs);
65 PARSE_LANGOPT_BENIGN(HexFloats);
66 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
67 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
68 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
70 PARSE_LANGOPT_BENIGN(CXXOperatorName);
71 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
72 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
73 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
74 PARSE_LANGOPT_BENIGN(PascalStrings);
75 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000076 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000077 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000078 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000079 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
80 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
81 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
82 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000084 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000085 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
87 PARSE_LANGOPT_BENIGN(EmitAllDecls);
88 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
89 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000090 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000091 diag::warn_pch_heinous_extensions);
92 // FIXME: Most of the options below are benign if the macro wasn't
93 // used. Unfortunately, this means that a PCH compiled without
94 // optimization can't be used with optimization turned on, even
95 // though the only thing that changes is whether __OPTIMIZE__ was
96 // defined... but if __OPTIMIZE__ never showed up in the header, it
97 // doesn't matter. We could consider making this some special kind
98 // of check.
99 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
100 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
101 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
102 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
103 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
104 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
105 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
106 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000107 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000108 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000110 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
111 return true;
112 }
113 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000114 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
115 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000116 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000117 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000118 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000119#undef PARSE_LANGOPT_IRRELEVANT
120#undef PARSE_LANGOPT_BENIGN
121
122 return false;
123}
124
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000125bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
126 if (Triple == PP.getTargetInfo().getTriple().str())
127 return false;
128
129 Reader.Diag(diag::warn_pch_target_triple)
130 << Triple << PP.getTargetInfo().getTriple().str();
131 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000132}
133
134/// \brief Split the given string into a vector of lines, eliminating
135/// any empty lines in the process.
136///
137/// \param Str the string to split.
138/// \param Len the length of Str.
139/// \param KeepEmptyLines true if empty lines should be included
140/// \returns a vector of lines, with the line endings removed
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000141static std::vector<llvm::StringRef> splitLines(llvm::StringRef Str,
142 bool KeepEmptyLines = false) {
143 std::vector<llvm::StringRef> Lines;
144
145 while (!Str.empty()) {
146 std::pair<llvm::StringRef, llvm::StringRef> split = Str.split('\n');
147
148 if (KeepEmptyLines || !split.first.empty())
149 Lines.push_back(split.first);
150
151 Str = split.second;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000152 }
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000153
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000154 return Lines;
155}
156
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000157bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000158 FileID PCHBufferID,
159 std::string &SuggestedPredefines) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000160 // If the two predefines buffers compare equal, we're done!
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000161 if (PP.getPredefines() == PCHPredef)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000162 return false;
163
164 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000166 // The predefines buffers are different. Determine what the differences are,
167 // and whether they require us to reject the PCH file.
168 std::vector<llvm::StringRef> CmdLineLines = splitLines(PP.getPredefines());
169 std::vector<llvm::StringRef> PCHLines = splitLines(PCHPredef);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000170
Mike Stump1eb44332009-09-09 15:08:12 +0000171 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000172 std::sort(CmdLineLines.begin(), CmdLineLines.end());
173 std::sort(PCHLines.begin(), PCHLines.end());
174
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000175 // Determine which predefines that where used to build the PCH file are
176 // missing from the command line.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000177 std::vector<std::string> MissingPredefines;
178 std::set_difference(PCHLines.begin(), PCHLines.end(),
179 CmdLineLines.begin(), CmdLineLines.end(),
180 std::back_inserter(MissingPredefines));
181
182 bool MissingDefines = false;
183 bool ConflictingDefines = false;
184 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
185 const std::string &Missing = MissingPredefines[I];
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000186 if (!llvm::StringRef(Missing).startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000187 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
188 return true;
189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000191 // This is a macro definition. Determine the name of the macro we're
192 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000193 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000194 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000195 = Missing.find_first_of("( \n\r", StartOfMacroName);
196 assert(EndOfMacroName != std::string::npos &&
197 "Couldn't find the end of the macro name");
198 std::string MacroName = Missing.substr(StartOfMacroName,
199 EndOfMacroName - StartOfMacroName);
200
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000201 // Determine whether this macro was given a different definition on the
202 // command line.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000203 std::string MacroDefStart = "#define " + MacroName;
204 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000205 std::vector<llvm::StringRef>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000206 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
207 MacroDefStart);
208 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000209 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000210 // Different macro; we're done.
211 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000212 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
215 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000216 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000217 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000218 (*ConflictPos)[MacroDefLen] != '(')
219 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000221 // We found a conflicting macro definition.
222 break;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000225 if (ConflictPos != CmdLineLines.end()) {
226 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
227 << MacroName;
228
229 // Show the definition of this macro within the PCH file.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000230 const char *MissingDef = strstr(PCHPredef.data(), Missing.c_str());
231 unsigned Offset = MissingDef - PCHPredef.data();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000232 SourceLocation PCHMissingLoc
233 = SourceMgr.getLocForStartOfFile(PCHBufferID)
234 .getFileLocWithOffset(Offset);
235 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
236 << MacroName;
237
238 ConflictingDefines = true;
239 continue;
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000242 // If the macro doesn't conflict, then we'll just pick up the macro
243 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000244 if (ConflictingDefines)
245 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000247 if (!MissingDefines) {
248 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
249 MissingDefines = true;
250 }
251
252 // Show the definition of this macro within the PCH file.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000253 const char *MissingDef = strstr(PCHPredef.data(), Missing.c_str());
254 unsigned Offset = MissingDef - PCHPredef.data();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000255 SourceLocation PCHMissingLoc
256 = SourceMgr.getLocForStartOfFile(PCHBufferID)
257 .getFileLocWithOffset(Offset);
258 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
259 }
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000261 if (ConflictingDefines)
262 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000264 // Determine what predefines were introduced based on command-line
265 // parameters that were not present when building the PCH
266 // file. Extra #defines are okay, so long as the identifiers being
267 // defined were not used within the precompiled header.
268 std::vector<std::string> ExtraPredefines;
269 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
270 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000271 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000272 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
273 const std::string &Extra = ExtraPredefines[I];
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000274 if (!llvm::StringRef(Extra).startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000275 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
276 return true;
277 }
278
279 // This is an extra macro definition. Determine the name of the
280 // macro we're defining.
281 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000282 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000283 = Extra.find_first_of("( \n\r", StartOfMacroName);
284 assert(EndOfMacroName != std::string::npos &&
285 "Couldn't find the end of the macro name");
286 std::string MacroName = Extra.substr(StartOfMacroName,
287 EndOfMacroName - StartOfMacroName);
288
289 // Check whether this name was used somewhere in the PCH file. If
290 // so, defining it as a macro could change behavior, so we reject
291 // the PCH file.
292 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
293 MacroName.c_str() + MacroName.size())) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000294 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295 return true;
296 }
297
298 // Add this definition to the suggested predefines buffer.
299 SuggestedPredefines += Extra;
300 SuggestedPredefines += '\n';
301 }
302
303 // If we get here, it's because the predefines buffer had compatible
304 // contents. Accept the PCH file.
305 return false;
306}
307
308void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
309 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
310}
311
312void PCHValidator::ReadCounter(unsigned Value) {
313 PP.setCounterValue(Value);
314}
315
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000316//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000317// PCH reader implementation
318//===----------------------------------------------------------------------===//
319
Mike Stump1eb44332009-09-09 15:08:12 +0000320PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
321 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000322 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
323 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000324 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000325 IdentifierTableData(0), IdentifierLookupTable(0),
326 IdentifierOffsets(0),
327 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
328 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000329 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000330 NumStatHits(0), NumStatMisses(0),
331 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000333 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000334 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000335 RelocatablePCH = false;
336}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000337
338PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000339 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000341 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000342 IdentifierTableData(0), IdentifierLookupTable(0),
343 IdentifierOffsets(0),
344 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
345 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000346 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000347 NumStatHits(0), NumStatMisses(0),
348 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000349 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000350 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000351 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000352 RelocatablePCH = false;
353}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000354
355PCHReader::~PCHReader() {}
356
Chris Lattnerda930612009-04-27 05:58:23 +0000357Expr *PCHReader::ReadDeclExpr() {
358 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
359}
360
361Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000362 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000363}
364
365
Douglas Gregor668c1a42009-04-21 22:25:48 +0000366namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000367class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
368 PCHReader &Reader;
369
370public:
371 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
372
373 typedef Selector external_key_type;
374 typedef external_key_type internal_key_type;
375
376 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000378 static bool EqualKey(const internal_key_type& a,
379 const internal_key_type& b) {
380 return a == b;
381 }
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000383 static unsigned ComputeHash(Selector Sel) {
384 unsigned N = Sel.getNumArgs();
385 if (N == 0)
386 ++N;
387 unsigned R = 5381;
388 for (unsigned I = 0; I != N; ++I)
389 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000390 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000391 return R;
392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000394 // This hopefully will just get inlined and removed by the optimizer.
395 static const internal_key_type&
396 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000398 static std::pair<unsigned, unsigned>
399 ReadKeyDataLength(const unsigned char*& d) {
400 using namespace clang::io;
401 unsigned KeyLen = ReadUnalignedLE16(d);
402 unsigned DataLen = ReadUnalignedLE16(d);
403 return std::make_pair(KeyLen, DataLen);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Douglas Gregor83941df2009-04-25 17:48:32 +0000406 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000407 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000408 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000409 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000410 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000411 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
412 if (N == 0)
413 return SelTable.getNullarySelector(FirstII);
414 else if (N == 1)
415 return SelTable.getUnarySelector(FirstII);
416
417 llvm::SmallVector<IdentifierInfo *, 16> Args;
418 Args.push_back(FirstII);
419 for (unsigned I = 1; I != N; ++I)
420 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
421
Douglas Gregor75fdb232009-05-22 22:45:36 +0000422 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000425 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
426 using namespace clang::io;
427 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
428 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
429
430 data_type Result;
431
432 // Load instance methods
433 ObjCMethodList *Prev = 0;
434 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000435 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000436 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
437 if (!Result.first.Method) {
438 // This is the first method, which is the easy case.
439 Result.first.Method = Method;
440 Prev = &Result.first;
441 continue;
442 }
443
444 Prev->Next = new ObjCMethodList(Method, 0);
445 Prev = Prev->Next;
446 }
447
448 // Load factory methods
449 Prev = 0;
450 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000451 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000452 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
453 if (!Result.second.Method) {
454 // This is the first method, which is the easy case.
455 Result.second.Method = Method;
456 Prev = &Result.second;
457 continue;
458 }
459
460 Prev->Next = new ObjCMethodList(Method, 0);
461 Prev = Prev->Next;
462 }
463
464 return Result;
465 }
466};
Mike Stump1eb44332009-09-09 15:08:12 +0000467
468} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000469
470/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000471typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000472 PCHMethodPoolLookupTable;
473
474namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000475class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
476 PCHReader &Reader;
477
478 // If we know the IdentifierInfo in advance, it is here and we will
479 // not build a new one. Used when deserializing information about an
480 // identifier that was constructed before the PCH file was read.
481 IdentifierInfo *KnownII;
482
483public:
484 typedef IdentifierInfo * data_type;
485
486 typedef const std::pair<const char*, unsigned> external_key_type;
487
488 typedef external_key_type internal_key_type;
489
Mike Stump1eb44332009-09-09 15:08:12 +0000490 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000491 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregor668c1a42009-04-21 22:25:48 +0000493 static bool EqualKey(const internal_key_type& a,
494 const internal_key_type& b) {
495 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
496 : false;
497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregor668c1a42009-04-21 22:25:48 +0000499 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000500 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregor668c1a42009-04-21 22:25:48 +0000503 // This hopefully will just get inlined and removed by the optimizer.
504 static const internal_key_type&
505 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor668c1a42009-04-21 22:25:48 +0000507 static std::pair<unsigned, unsigned>
508 ReadKeyDataLength(const unsigned char*& d) {
509 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000510 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000511 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000512 return std::make_pair(KeyLen, DataLen);
513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 static std::pair<const char*, unsigned>
516 ReadKey(const unsigned char* d, unsigned n) {
517 assert(n >= 2 && d[n-1] == '\0');
518 return std::make_pair((const char*) d, n-1);
519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
521 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000522 const unsigned char* d,
523 unsigned DataLen) {
524 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000525 pch::IdentID ID = ReadUnalignedLE32(d);
526 bool IsInteresting = ID & 0x01;
527
528 // Wipe out the "is interesting" bit.
529 ID = ID >> 1;
530
531 if (!IsInteresting) {
532 // For unintersting identifiers, just build the IdentifierInfo
533 // and associate it with the persistent ID.
534 IdentifierInfo *II = KnownII;
535 if (!II)
536 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
537 k.first, k.first + k.second);
538 Reader.SetIdentifierInfo(ID, II);
539 return II;
540 }
541
Douglas Gregor5998da52009-04-28 21:32:13 +0000542 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000543 bool CPlusPlusOperatorKeyword = Bits & 0x01;
544 Bits >>= 1;
545 bool Poisoned = Bits & 0x01;
546 Bits >>= 1;
547 bool ExtensionToken = Bits & 0x01;
548 Bits >>= 1;
549 bool hasMacroDefinition = Bits & 0x01;
550 Bits >>= 1;
551 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
552 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Douglas Gregor2deaea32009-04-22 18:49:13 +0000554 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000555 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000556
557 // Build the IdentifierInfo itself and link the identifier ID with
558 // the new IdentifierInfo.
559 IdentifierInfo *II = KnownII;
560 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000561 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
562 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000563 Reader.SetIdentifierInfo(ID, II);
564
Douglas Gregor2deaea32009-04-22 18:49:13 +0000565 // Set or check the various bits in the IdentifierInfo structure.
566 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000567 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000568 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000569 "Incorrect extension token flag");
570 (void)ExtensionToken;
571 II->setIsPoisoned(Poisoned);
572 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
573 "Incorrect C++ operator keyword flag");
574 (void)CPlusPlusOperatorKeyword;
575
Douglas Gregor37e26842009-04-21 23:56:24 +0000576 // If this identifier is a macro, deserialize the macro
577 // definition.
578 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000579 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000580 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000581 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000582 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000583
584 // Read all of the declarations visible at global scope with this
585 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000586 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000587 if (DataLen > 0) {
588 llvm::SmallVector<uint32_t, 4> DeclIDs;
589 for (; DataLen > 0; DataLen -= 4)
590 DeclIDs.push_back(ReadUnalignedLE32(d));
591 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000592 }
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Douglas Gregor668c1a42009-04-21 22:25:48 +0000594 return II;
595 }
596};
Mike Stump1eb44332009-09-09 15:08:12 +0000597
598} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000599
600/// \brief The on-disk hash table used to contain information about
601/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000602typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000603 PCHIdentifierLookupTable;
604
Douglas Gregora02b1472009-04-28 21:53:25 +0000605bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000606 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
607 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000608 return true;
609}
610
Douglas Gregore1d918e2009-04-10 23:10:45 +0000611/// \brief Check the contents of the predefines buffer against the
612/// contents of the predefines buffer used to build the PCH file.
613///
614/// The contents of the two predefines buffers should be the same. If
615/// not, then some command-line option changed the preprocessor state
616/// and we must reject the PCH file.
617///
618/// \param PCHPredef The start of the predefines buffer in the PCH
619/// file.
620///
621/// \param PCHPredefLen The length of the predefines buffer in the PCH
622/// file.
623///
624/// \param PCHBufferID The FileID for the PCH predefines buffer.
625///
626/// \returns true if there was a mismatch (in which case the PCH file
627/// should be ignored), or false otherwise.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000628bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000629 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000630 if (Listener)
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000631 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000632 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000633 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000634}
635
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000636//===----------------------------------------------------------------------===//
637// Source Manager Deserialization
638//===----------------------------------------------------------------------===//
639
Douglas Gregorbd945002009-04-13 16:31:14 +0000640/// \brief Read the line table in the source manager block.
641/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000642bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000643 unsigned Idx = 0;
644 LineTableInfo &LineTable = SourceMgr.getLineTable();
645
646 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000647 std::map<int, int> FileIDs;
648 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000649 // Extract the file name
650 unsigned FilenameLen = Record[Idx++];
651 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
652 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000653 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000654 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000655 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000656 }
657
658 // Parse the line entries
659 std::vector<LineEntry> Entries;
660 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000661 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000662
663 // Extract the line entries
664 unsigned NumEntries = Record[Idx++];
665 Entries.clear();
666 Entries.reserve(NumEntries);
667 for (unsigned I = 0; I != NumEntries; ++I) {
668 unsigned FileOffset = Record[Idx++];
669 unsigned LineNo = Record[Idx++];
670 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000671 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000672 = (SrcMgr::CharacteristicKind)Record[Idx++];
673 unsigned IncludeOffset = Record[Idx++];
674 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
675 FileKind, IncludeOffset));
676 }
677 LineTable.AddEntry(FID, Entries);
678 }
679
680 return false;
681}
682
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000683namespace {
684
685class VISIBILITY_HIDDEN PCHStatData {
686public:
687 const bool hasStat;
688 const ino_t ino;
689 const dev_t dev;
690 const mode_t mode;
691 const time_t mtime;
692 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000694 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000695 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
696
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000697 PCHStatData()
698 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
699};
700
701class VISIBILITY_HIDDEN PCHStatLookupTrait {
702 public:
703 typedef const char *external_key_type;
704 typedef const char *internal_key_type;
705
706 typedef PCHStatData data_type;
707
708 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000709 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000710 }
711
712 static internal_key_type GetInternalKey(const char *path) { return path; }
713
714 static bool EqualKey(internal_key_type a, internal_key_type b) {
715 return strcmp(a, b) == 0;
716 }
717
718 static std::pair<unsigned, unsigned>
719 ReadKeyDataLength(const unsigned char*& d) {
720 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
721 unsigned DataLen = (unsigned) *d++;
722 return std::make_pair(KeyLen + 1, DataLen);
723 }
724
725 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
726 return (const char *)d;
727 }
728
729 static data_type ReadData(const internal_key_type, const unsigned char *d,
730 unsigned /*DataLen*/) {
731 using namespace clang::io;
732
733 if (*d++ == 1)
734 return data_type();
735
736 ino_t ino = (ino_t) ReadUnalignedLE32(d);
737 dev_t dev = (dev_t) ReadUnalignedLE32(d);
738 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000739 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000740 off_t size = (off_t) ReadUnalignedLE64(d);
741 return data_type(ino, dev, mode, mtime, size);
742 }
743};
744
745/// \brief stat() cache for precompiled headers.
746///
747/// This cache is very similar to the stat cache used by pretokenized
748/// headers.
749class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
750 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
751 CacheTy *Cache;
752
753 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000754public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000755 PCHStatCache(const unsigned char *Buckets,
756 const unsigned char *Base,
757 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000758 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000759 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
760 Cache = CacheTy::Create(Buckets, Base);
761 }
762
763 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000765 int stat(const char *path, struct stat *buf) {
766 // Do the lookup for the file's data in the PCH file.
767 CacheTy::iterator I = Cache->find(path);
768
769 // If we don't get a hit in the PCH file just forward to 'stat'.
770 if (I == Cache->end()) {
771 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000772 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000775 ++NumStatHits;
776 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000778 if (!Data.hasStat)
779 return 1;
780
781 buf->st_ino = Data.ino;
782 buf->st_dev = Data.dev;
783 buf->st_mtime = Data.mtime;
784 buf->st_mode = Data.mode;
785 buf->st_size = Data.size;
786 return 0;
787 }
788};
789} // end anonymous namespace
790
791
Douglas Gregor14f79002009-04-10 03:52:48 +0000792/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000793PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000794 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000795
796 // Set the source-location entry cursor to the current position in
797 // the stream. This cursor will be used to read the contents of the
798 // source manager block initially, and then lazily read
799 // source-location entries as needed.
800 SLocEntryCursor = Stream;
801
802 // The stream itself is going to skip over the source manager block.
803 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000804 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000805 return Failure;
806 }
807
808 // Enter the source manager block.
809 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000810 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000811 return Failure;
812 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000813
Douglas Gregor14f79002009-04-10 03:52:48 +0000814 RecordData Record;
815 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000816 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000817 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000818 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000819 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000820 return Failure;
821 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000822 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Douglas Gregor14f79002009-04-10 03:52:48 +0000825 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
826 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000827 SLocEntryCursor.ReadSubBlockID();
828 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000830 return Failure;
831 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000832 continue;
833 }
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregor14f79002009-04-10 03:52:48 +0000835 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000836 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000837 continue;
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor14f79002009-04-10 03:52:48 +0000840 // Read a record.
841 const char *BlobStart;
842 unsigned BlobLen;
843 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000844 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000845 default: // Default behavior: ignore.
846 break;
847
Chris Lattner2c78b872009-04-14 23:22:57 +0000848 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000849 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000850 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000851 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000852
853 case pch::SM_HEADER_FILE_INFO: {
854 HeaderFileInfo HFI;
855 HFI.isImport = Record[0];
856 HFI.DirInfo = Record[1];
857 HFI.NumIncludes = Record[2];
858 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000859 if (Listener)
860 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000861 break;
862 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000863
864 case pch::SM_SLOC_FILE_ENTRY:
865 case pch::SM_SLOC_BUFFER_ENTRY:
866 case pch::SM_SLOC_INSTANTIATION_ENTRY:
867 // Once we hit one of the source location entries, we're done.
868 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000869 }
870 }
871}
872
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000873/// \brief Read in the source location entry with the given ID.
874PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
875 if (ID == 0)
876 return Success;
877
878 if (ID > TotalNumSLocEntries) {
879 Error("source location entry ID out-of-range for PCH file");
880 return Failure;
881 }
882
883 ++NumSLocEntriesRead;
884 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
885 unsigned Code = SLocEntryCursor.ReadCode();
886 if (Code == llvm::bitc::END_BLOCK ||
887 Code == llvm::bitc::ENTER_SUBBLOCK ||
888 Code == llvm::bitc::DEFINE_ABBREV) {
889 Error("incorrectly-formatted source location entry in PCH file");
890 return Failure;
891 }
892
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000893 RecordData Record;
894 const char *BlobStart;
895 unsigned BlobLen;
896 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
897 default:
898 Error("incorrectly-formatted source location entry in PCH file");
899 return Failure;
900
901 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000902 std::string Filename(BlobStart, BlobStart + BlobLen);
903 MaybeAddSystemRootToFilename(Filename);
904 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000905 if (File == 0) {
906 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000907 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000908 ErrorStr += "' referenced by PCH file";
909 Error(ErrorStr.c_str());
910 return Failure;
911 }
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913 FileID FID = SourceMgr.createFileID(File,
914 SourceLocation::getFromRawEncoding(Record[1]),
915 (SrcMgr::CharacteristicKind)Record[2],
916 ID, Record[0]);
917 if (Record[3])
918 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
919 .setHasLineDirectives();
920
921 break;
922 }
923
924 case pch::SM_SLOC_BUFFER_ENTRY: {
925 const char *Name = BlobStart;
926 unsigned Offset = Record[0];
927 unsigned Code = SLocEntryCursor.ReadCode();
928 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000929 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000930 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
931 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
932 (void)RecCode;
933 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000934 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000935 BlobStart + BlobLen - 1,
936 Name);
937 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Douglas Gregor92b059e2009-04-28 20:33:11 +0000939 if (strcmp(Name, "<built-in>") == 0) {
940 PCHPredefinesBufferID = BufferID;
941 PCHPredefines = BlobStart;
942 PCHPredefinesLen = BlobLen - 1;
943 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000944
945 break;
946 }
947
948 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000949 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000950 = SourceLocation::getFromRawEncoding(Record[1]);
951 SourceMgr.createInstantiationLoc(SpellingLoc,
952 SourceLocation::getFromRawEncoding(Record[2]),
953 SourceLocation::getFromRawEncoding(Record[3]),
954 Record[4],
955 ID,
956 Record[0]);
957 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000958 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000959 }
960
961 return Success;
962}
963
Chris Lattner6367f6d2009-04-27 01:05:14 +0000964/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
965/// specified cursor. Read the abbreviations that are at the top of the block
966/// and then leave the cursor pointing into the block.
967bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
968 unsigned BlockID) {
969 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000970 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000971 return Failure;
972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattner6367f6d2009-04-27 01:05:14 +0000974 while (true) {
975 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chris Lattner6367f6d2009-04-27 01:05:14 +0000977 // We expect all abbrevs to be at the start of the block.
978 if (Code != llvm::bitc::DEFINE_ABBREV)
979 return false;
980 Cursor.ReadAbbrevRecord();
981 }
982}
983
Douglas Gregor37e26842009-04-21 23:56:24 +0000984void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000985 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregor37e26842009-04-21 23:56:24 +0000987 // Keep track of where we are in the stream, then jump back there
988 // after reading this macro.
989 SavedStreamPosition SavedPosition(Stream);
990
991 Stream.JumpToBit(Offset);
992 RecordData Record;
993 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
994 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Douglas Gregor37e26842009-04-21 23:56:24 +0000996 while (true) {
997 unsigned Code = Stream.ReadCode();
998 switch (Code) {
999 case llvm::bitc::END_BLOCK:
1000 return;
1001
1002 case llvm::bitc::ENTER_SUBBLOCK:
1003 // No known subblocks, always skip them.
1004 Stream.ReadSubBlockID();
1005 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001006 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001007 return;
1008 }
1009 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Douglas Gregor37e26842009-04-21 23:56:24 +00001011 case llvm::bitc::DEFINE_ABBREV:
1012 Stream.ReadAbbrevRecord();
1013 continue;
1014 default: break;
1015 }
1016
1017 // Read a record.
1018 Record.clear();
1019 pch::PreprocessorRecordTypes RecType =
1020 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1021 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001022 case pch::PP_MACRO_OBJECT_LIKE:
1023 case pch::PP_MACRO_FUNCTION_LIKE: {
1024 // If we already have a macro, that means that we've hit the end
1025 // of the definition of the macro we were looking for. We're
1026 // done.
1027 if (Macro)
1028 return;
1029
1030 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1031 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001032 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001033 return;
1034 }
1035 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1036 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001038 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001039 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Douglas Gregor37e26842009-04-21 23:56:24 +00001041 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1042 // Decode function-like macro info.
1043 bool isC99VarArgs = Record[3];
1044 bool isGNUVarArgs = Record[4];
1045 MacroArgs.clear();
1046 unsigned NumArgs = Record[5];
1047 for (unsigned i = 0; i != NumArgs; ++i)
1048 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1049
1050 // Install function-like macro info.
1051 MI->setIsFunctionLike();
1052 if (isC99VarArgs) MI->setIsC99Varargs();
1053 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001054 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001055 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001056 }
1057
1058 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001059 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001060
1061 // Remember that we saw this macro last so that we add the tokens that
1062 // form its body to it.
1063 Macro = MI;
1064 ++NumMacrosRead;
1065 break;
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor37e26842009-04-21 23:56:24 +00001068 case pch::PP_TOKEN: {
1069 // If we see a TOKEN before a PP_MACRO_*, then the file is
1070 // erroneous, just pretend we didn't see this.
1071 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregor37e26842009-04-21 23:56:24 +00001073 Token Tok;
1074 Tok.startToken();
1075 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1076 Tok.setLength(Record[1]);
1077 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1078 Tok.setIdentifierInfo(II);
1079 Tok.setKind((tok::TokenKind)Record[3]);
1080 Tok.setFlag((Token::TokenFlags)Record[4]);
1081 Macro->AddTokenToBody(Tok);
1082 break;
1083 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001084 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001085 }
1086}
1087
Douglas Gregore650c8c2009-07-07 00:12:59 +00001088/// \brief If we are loading a relocatable PCH file, and the filename is
1089/// not an absolute path, add the system root to the beginning of the file
1090/// name.
1091void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1092 // If this is not a relocatable PCH file, there's nothing to do.
1093 if (!RelocatablePCH)
1094 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregore650c8c2009-07-07 00:12:59 +00001096 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1097 return;
1098
1099 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregore650c8c2009-07-07 00:12:59 +00001101 if (isysroot == 0) {
1102 // If no system root was given, default to '/'
1103 Filename.insert(Filename.begin(), '/');
1104 return;
1105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregore650c8c2009-07-07 00:12:59 +00001107 unsigned Length = strlen(isysroot);
1108 if (isysroot[Length - 1] != '/')
1109 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregore650c8c2009-07-07 00:12:59 +00001111 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1112}
1113
Mike Stump1eb44332009-09-09 15:08:12 +00001114PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001115PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001116 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001117 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001118 return Failure;
1119 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001120
1121 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001122 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001123 while (!Stream.AtEndOfStream()) {
1124 unsigned Code = Stream.ReadCode();
1125 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001126 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001127 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001128 return Failure;
1129 }
Chris Lattner7356a312009-04-11 21:15:38 +00001130
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001131 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001132 }
1133
1134 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1135 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001136 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001137 // We lazily load the decls block, but we want to set up the
1138 // DeclsCursor cursor to point into it. Clone our current bitcode
1139 // cursor to it, enter the block and read the abbrevs in that block.
1140 // With the main cursor, we just skip over it.
1141 DeclsCursor = Stream;
1142 if (Stream.SkipBlock() || // Skip with the main cursor.
1143 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001144 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001145 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001146 return Failure;
1147 }
1148 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Chris Lattner7356a312009-04-11 21:15:38 +00001150 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001151 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001152 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001153 return Failure;
1154 }
1155 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001156
Douglas Gregor14f79002009-04-10 03:52:48 +00001157 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001158 switch (ReadSourceManagerBlock()) {
1159 case Success:
1160 break;
1161
1162 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001163 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001164 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001165
1166 case IgnorePCH:
1167 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001168 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001169 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001170 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001171 continue;
1172 }
1173
1174 if (Code == llvm::bitc::DEFINE_ABBREV) {
1175 Stream.ReadAbbrevRecord();
1176 continue;
1177 }
1178
1179 // Read and process a record.
1180 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001181 const char *BlobStart = 0;
1182 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001183 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001184 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001185 default: // Default behavior: ignore.
1186 break;
1187
1188 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001189 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001190 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001191 return Failure;
1192 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001193 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001194 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001195 break;
1196
1197 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001198 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001199 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001200 return Failure;
1201 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001202 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001203 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001204 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001205
1206 case pch::LANGUAGE_OPTIONS:
1207 if (ParseLanguageOptions(Record))
1208 return IgnorePCH;
1209 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001210
Douglas Gregorab41e632009-04-27 22:23:34 +00001211 case pch::METADATA: {
1212 if (Record[0] != pch::VERSION_MAJOR) {
1213 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1214 : diag::warn_pch_version_too_new);
1215 return IgnorePCH;
1216 }
1217
Douglas Gregore650c8c2009-07-07 00:12:59 +00001218 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001219 if (Listener) {
1220 std::string TargetTriple(BlobStart, BlobLen);
1221 if (Listener->ReadTargetTriple(TargetTriple))
1222 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001223 }
1224 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001225 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001226
1227 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001228 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001229 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001230 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001231 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001232 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001233 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001234 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001235 if (PP)
1236 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001237 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001238 break;
1239
1240 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001241 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001242 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001243 return Failure;
1244 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001245 IdentifierOffsets = (const uint32_t *)BlobStart;
1246 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001247 if (PP)
1248 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001249 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001250
1251 case pch::EXTERNAL_DEFINITIONS:
1252 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001253 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001254 return Failure;
1255 }
1256 ExternalDefinitions.swap(Record);
1257 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001258
Douglas Gregorad1de002009-04-18 05:55:16 +00001259 case pch::SPECIAL_TYPES:
1260 SpecialTypes.swap(Record);
1261 break;
1262
Douglas Gregor3e1af842009-04-17 22:13:46 +00001263 case pch::STATISTICS:
1264 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001265 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001266 TotalLexicalDeclContexts = Record[2];
1267 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001268 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001269
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001270 case pch::TENTATIVE_DEFINITIONS:
1271 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001272 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001273 return Failure;
1274 }
1275 TentativeDefinitions.swap(Record);
1276 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001277
1278 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1279 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001280 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001281 return Failure;
1282 }
1283 LocallyScopedExternalDecls.swap(Record);
1284 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001285
Douglas Gregor83941df2009-04-25 17:48:32 +00001286 case pch::SELECTOR_OFFSETS:
1287 SelectorOffsets = (const uint32_t *)BlobStart;
1288 TotalNumSelectors = Record[0];
1289 SelectorsLoaded.resize(TotalNumSelectors);
1290 break;
1291
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001292 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001293 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1294 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001295 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001296 = PCHMethodPoolLookupTable::Create(
1297 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001298 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001299 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001300 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001301 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001302
1303 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001304 if (!Record.empty() && Listener)
1305 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001306 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001307
1308 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001309 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001310 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001311 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001312 break;
1313
1314 case pch::SOURCE_LOCATION_PRELOADS:
1315 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1316 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1317 if (Result != Success)
1318 return Result;
1319 }
1320 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001321
Douglas Gregor52e71082009-10-16 18:18:30 +00001322 case pch::STAT_CACHE: {
1323 PCHStatCache *MyStatCache =
1324 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1325 (const unsigned char *)BlobStart,
1326 NumStatHits, NumStatMisses);
1327 FileMgr.addStatCache(MyStatCache);
1328 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001329 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001330 }
1331
Douglas Gregorb81c1702009-04-27 20:06:05 +00001332 case pch::EXT_VECTOR_DECLS:
1333 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001334 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001335 return Failure;
1336 }
1337 ExtVectorDecls.swap(Record);
1338 break;
1339
Douglas Gregorb64c1932009-05-12 01:31:05 +00001340 case pch::ORIGINAL_FILE_NAME:
1341 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001342 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001343 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Douglas Gregor2e222532009-07-02 17:08:52 +00001345 case pch::COMMENT_RANGES:
1346 Comments = (SourceRange *)BlobStart;
1347 NumComments = BlobLen / sizeof(SourceRange);
1348 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001349
1350 case pch::SVN_BRANCH_REVISION: {
1351 unsigned CurRevision = getClangSubversionRevision();
1352 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1353 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1354 : diag::warn_pch_version_too_new);
1355 return IgnorePCH;
1356 }
1357
1358 const char *CurBranch = getClangSubversionPath();
1359 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1360 std::string PCHBranch(BlobStart, BlobLen);
1361 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1362 return IgnorePCH;
1363 }
1364 break;
1365 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001366 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001367 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001368 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001369 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001370}
1371
Douglas Gregore1d918e2009-04-10 23:10:45 +00001372PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001373 // Set the PCH file name.
1374 this->FileName = FileName;
1375
Douglas Gregor2cf26342009-04-09 22:27:44 +00001376 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001377 //
1378 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001379 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001380 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001381 if (!Buffer) {
1382 Error(ErrStr.c_str());
1383 return IgnorePCH;
1384 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001385
1386 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001387 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001388 (const unsigned char *)Buffer->getBufferEnd());
1389 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001390
1391 // Sniff for the signature.
1392 if (Stream.Read(8) != 'C' ||
1393 Stream.Read(8) != 'P' ||
1394 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001395 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001396 Diag(diag::err_not_a_pch_file) << FileName;
1397 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001398 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001399
Douglas Gregor2cf26342009-04-09 22:27:44 +00001400 while (!Stream.AtEndOfStream()) {
1401 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Douglas Gregore1d918e2009-04-10 23:10:45 +00001403 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001404 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001405 return Failure;
1406 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001407
1408 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001409
Douglas Gregor2cf26342009-04-09 22:27:44 +00001410 // We only know the PCH subblock ID.
1411 switch (BlockID) {
1412 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001413 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001414 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001415 return Failure;
1416 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001417 break;
1418 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001419 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001420 case Success:
1421 break;
1422
1423 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001424 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001425
1426 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001427 // FIXME: We could consider reading through to the end of this
1428 // PCH block, skipping subblocks, to see if there are other
1429 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001430
1431 // Clear out any preallocated source location entries, so that
1432 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001433 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001434
1435 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001436 if (StatCache)
1437 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001438
Douglas Gregore1d918e2009-04-10 23:10:45 +00001439 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001440 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001441 break;
1442 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001443 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001444 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001445 return Failure;
1446 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001447 break;
1448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449 }
1450
Douglas Gregor92b059e2009-04-28 20:33:11 +00001451 // Check the predefines buffer.
Daniel Dunbardc3c0d22009-11-11 00:52:11 +00001452 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregor92b059e2009-04-28 20:33:11 +00001453 PCHPredefinesBufferID))
1454 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001456 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001457 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001458 // PCH file is read, so there may be some identifiers that were
1459 // loaded into the IdentifierTable before we intercepted the
1460 // creation of identifiers. Iterate through the list of known
1461 // identifiers and determine whether we have to establish
1462 // preprocessor definitions or top-level identifier declaration
1463 // chains for those identifiers.
1464 //
1465 // We copy the IdentifierInfo pointers to a small vector first,
1466 // since de-serializing declarations or macro definitions can add
1467 // new entries into the identifier table, invalidating the
1468 // iterators.
1469 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1470 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1471 IdEnd = PP->getIdentifierTable().end();
1472 Id != IdEnd; ++Id)
1473 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001474 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001475 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1476 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1477 IdentifierInfo *II = Identifiers[I];
1478 // Look in the on-disk hash table for an entry for
1479 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001480 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001481 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1482 if (Pos == IdTable->end())
1483 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001485 // Dereferencing the iterator has the effect of populating the
1486 // IdentifierInfo node with the various declarations it needs.
1487 (void)*Pos;
1488 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001489 }
1490
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001491 if (Context)
1492 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001493
Douglas Gregor668c1a42009-04-21 22:25:48 +00001494 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001495}
1496
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001497void PCHReader::InitializeContext(ASTContext &Ctx) {
1498 Context = &Ctx;
1499 assert(Context && "Passed null context!");
1500
1501 assert(PP && "Forgot to set Preprocessor ?");
1502 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1503 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001505 // Load the translation unit declaration
1506 ReadDeclRecord(DeclOffsets[0], 0);
1507
1508 // Load the special types.
1509 Context->setBuiltinVaListType(
1510 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1511 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1512 Context->setObjCIdType(GetType(Id));
1513 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1514 Context->setObjCSelType(GetType(Sel));
1515 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1516 Context->setObjCProtoType(GetType(Proto));
1517 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1518 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001519
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001520 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1521 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001522 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001523 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1524 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001525 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1526 QualType FileType = GetType(File);
1527 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001528 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001529 Context->setFILEDecl(Typedef->getDecl());
1530 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001531 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001532 assert(Tag && "Invalid FILE type in PCH file");
1533 Context->setFILEDecl(Tag->getDecl());
1534 }
1535 }
Mike Stump782fa302009-07-28 02:25:19 +00001536 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1537 QualType Jmp_bufType = GetType(Jmp_buf);
1538 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001539 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001540 Context->setjmp_bufDecl(Typedef->getDecl());
1541 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001542 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001543 assert(Tag && "Invalid jmp_bug type in PCH file");
1544 Context->setjmp_bufDecl(Tag->getDecl());
1545 }
1546 }
1547 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1548 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1549 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001550 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001551 Context->setsigjmp_bufDecl(Typedef->getDecl());
1552 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001553 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001554 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1555 Context->setsigjmp_bufDecl(Tag->getDecl());
1556 }
1557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001559 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1560 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001561 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001562 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1563 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001564 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1565 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001566 if (unsigned String
1567 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1568 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001569}
1570
Douglas Gregorb64c1932009-05-12 01:31:05 +00001571/// \brief Retrieve the name of the original source file name
1572/// directly from the PCH file, without actually loading the PCH
1573/// file.
1574std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1575 // 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) {
1580 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1581 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') {
Mike Stump1eb44332009-09-09 15:08:12 +00001596 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001597 "error: '%s' does not appear to be a precompiled header file\n",
1598 PCHFileName.c_str());
1599 return std::string();
1600 }
1601
1602 RecordData Record;
1603 while (!Stream.AtEndOfStream()) {
1604 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Douglas Gregorb64c1932009-05-12 01:31:05 +00001606 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1607 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Douglas Gregorb64c1932009-05-12 01:31:05 +00001609 // We only know the PCH subblock ID.
1610 switch (BlockID) {
1611 case pch::PCH_BLOCK_ID:
1612 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1613 fprintf(stderr, "error: malformed block record in PCH file\n");
1614 return std::string();
1615 }
1616 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Douglas Gregorb64c1932009-05-12 01:31:05 +00001618 default:
1619 if (Stream.SkipBlock()) {
1620 fprintf(stderr, "error: malformed block record in PCH file\n");
1621 return std::string();
1622 }
1623 break;
1624 }
1625 continue;
1626 }
1627
1628 if (Code == llvm::bitc::END_BLOCK) {
1629 if (Stream.ReadBlockEnd()) {
1630 fprintf(stderr, "error: error at end of module block in PCH file\n");
1631 return std::string();
1632 }
1633 continue;
1634 }
1635
1636 if (Code == llvm::bitc::DEFINE_ABBREV) {
1637 Stream.ReadAbbrevRecord();
1638 continue;
1639 }
1640
1641 Record.clear();
1642 const char *BlobStart = 0;
1643 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001644 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001645 == pch::ORIGINAL_FILE_NAME)
1646 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001647 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001648
1649 return std::string();
1650}
1651
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001652/// \brief Parse the record that corresponds to a LangOptions data
1653/// structure.
1654///
1655/// This routine compares the language options used to generate the
1656/// PCH file against the language options set for the current
1657/// compilation. For each option, we classify differences between the
1658/// two compiler states as either "benign" or "important". Benign
1659/// differences don't matter, and we accept them without complaint
1660/// (and without modifying the language options). Differences between
1661/// the states for important options cause the PCH file to be
1662/// unusable, so we emit a warning and return true to indicate that
1663/// there was an error.
1664///
1665/// \returns true if the PCH file is unacceptable, false otherwise.
1666bool PCHReader::ParseLanguageOptions(
1667 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001668 if (Listener) {
1669 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001671 #define PARSE_LANGOPT(Option) \
1672 LangOpts.Option = Record[Idx]; \
1673 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001675 unsigned Idx = 0;
1676 PARSE_LANGOPT(Trigraphs);
1677 PARSE_LANGOPT(BCPLComment);
1678 PARSE_LANGOPT(DollarIdents);
1679 PARSE_LANGOPT(AsmPreprocessor);
1680 PARSE_LANGOPT(GNUMode);
1681 PARSE_LANGOPT(ImplicitInt);
1682 PARSE_LANGOPT(Digraphs);
1683 PARSE_LANGOPT(HexFloats);
1684 PARSE_LANGOPT(C99);
1685 PARSE_LANGOPT(Microsoft);
1686 PARSE_LANGOPT(CPlusPlus);
1687 PARSE_LANGOPT(CPlusPlus0x);
1688 PARSE_LANGOPT(CXXOperatorNames);
1689 PARSE_LANGOPT(ObjC1);
1690 PARSE_LANGOPT(ObjC2);
1691 PARSE_LANGOPT(ObjCNonFragileABI);
1692 PARSE_LANGOPT(PascalStrings);
1693 PARSE_LANGOPT(WritableStrings);
1694 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001695 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001696 PARSE_LANGOPT(Exceptions);
1697 PARSE_LANGOPT(NeXTRuntime);
1698 PARSE_LANGOPT(Freestanding);
1699 PARSE_LANGOPT(NoBuiltin);
1700 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001701 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001702 PARSE_LANGOPT(Blocks);
1703 PARSE_LANGOPT(EmitAllDecls);
1704 PARSE_LANGOPT(MathErrno);
1705 PARSE_LANGOPT(OverflowChecking);
1706 PARSE_LANGOPT(HeinousExtensions);
1707 PARSE_LANGOPT(Optimize);
1708 PARSE_LANGOPT(OptimizeSize);
1709 PARSE_LANGOPT(Static);
1710 PARSE_LANGOPT(PICLevel);
1711 PARSE_LANGOPT(GNUInline);
1712 PARSE_LANGOPT(NoInline);
1713 PARSE_LANGOPT(AccessControl);
1714 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001715 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001716 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1717 ++Idx;
1718 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1719 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001720 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1721 Record[Idx]);
1722 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001723 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001724 PARSE_LANGOPT(OpenCL);
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
1886 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001887 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001888 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001889
1890 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001891 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001892
1893 case pch::TYPE_TYPEOF: {
1894 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001895 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001896 return QualType();
1897 }
1898 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001899 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Anders Carlsson395b4752009-06-24 19:06:50 +00001902 case pch::TYPE_DECLTYPE:
1903 return Context->getDecltypeType(ReadTypeExpr());
1904
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001905 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001906 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001907 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001908
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001909 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001910 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001911 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001912
John McCall7da24312009-09-05 00:15:47 +00001913 case pch::TYPE_ELABORATED: {
1914 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1915 unsigned Tag = Record[1];
1916 return Context->getElaboratedType(GetType(Record[0]),
1917 (ElaboratedType::TagKind) Tag);
1918 }
1919
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001920 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001921 unsigned Idx = 0;
1922 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1923 unsigned NumProtos = Record[Idx++];
1924 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1925 for (unsigned I = 0; I != NumProtos; ++I)
1926 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001927 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001928 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001929
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001930 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001931 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001932 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001933 unsigned NumProtos = Record[Idx++];
1934 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1935 for (unsigned I = 0; I != NumProtos; ++I)
1936 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001937 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001938 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001939
John McCall49a832b2009-10-18 09:09:24 +00001940 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1941 unsigned Idx = 0;
1942 QualType Parm = GetType(Record[Idx++]);
1943 QualType Replacement = GetType(Record[Idx++]);
1944 return
1945 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1946 Replacement);
1947 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001948 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001949 // Suppress a GCC warning
1950 return QualType();
1951}
1952
John McCalla1ee0c52009-10-16 21:56:05 +00001953namespace {
1954
1955class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1956 PCHReader &Reader;
1957 const PCHReader::RecordData &Record;
1958 unsigned &Idx;
1959
1960public:
1961 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1962 unsigned &Idx)
1963 : Reader(Reader), Record(Record), Idx(Idx) { }
1964
John McCall51bd8032009-10-18 01:05:36 +00001965 // We want compile-time assurance that we've enumerated all of
1966 // these, so unfortunately we have to declare them first, then
1967 // define them out-of-line.
1968#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00001969#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00001970 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001971#include "clang/AST/TypeLocNodes.def"
1972
John McCall51bd8032009-10-18 01:05:36 +00001973 void VisitFunctionTypeLoc(FunctionTypeLoc);
1974 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00001975};
1976
1977}
1978
John McCall51bd8032009-10-18 01:05:36 +00001979void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00001980 // nothing to do
1981}
John McCall51bd8032009-10-18 01:05:36 +00001982void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1983 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001984}
John McCall51bd8032009-10-18 01:05:36 +00001985void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
1986 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001987}
John McCall51bd8032009-10-18 01:05:36 +00001988void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
1989 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001990}
John McCall51bd8032009-10-18 01:05:36 +00001991void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
1992 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001993}
John McCall51bd8032009-10-18 01:05:36 +00001994void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1995 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001996}
John McCall51bd8032009-10-18 01:05:36 +00001997void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1998 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00001999}
John McCall51bd8032009-10-18 01:05:36 +00002000void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2001 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002002}
John McCall51bd8032009-10-18 01:05:36 +00002003void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2004 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002005}
John McCall51bd8032009-10-18 01:05:36 +00002006void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2007 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2008 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002009 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002010 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002011 else
John McCall51bd8032009-10-18 01:05:36 +00002012 TL.setSizeExpr(0);
2013}
2014void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2015 VisitArrayTypeLoc(TL);
2016}
2017void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2018 VisitArrayTypeLoc(TL);
2019}
2020void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2021 VisitArrayTypeLoc(TL);
2022}
2023void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2024 DependentSizedArrayTypeLoc TL) {
2025 VisitArrayTypeLoc(TL);
2026}
2027void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2028 DependentSizedExtVectorTypeLoc TL) {
2029 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2030}
2031void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2032 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2033}
2034void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2035 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2036}
2037void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2038 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2039 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2040 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002041 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002042 }
2043}
2044void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2045 VisitFunctionTypeLoc(TL);
2046}
2047void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2048 VisitFunctionTypeLoc(TL);
2049}
2050void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2051 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2052}
2053void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2054 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2055}
2056void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2057 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2058}
2059void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2060 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2061}
2062void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2063 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2064}
2065void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2066 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
2068void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2069 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070}
2071void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2072 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2073}
John McCall49a832b2009-10-18 09:09:24 +00002074void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2075 SubstTemplateTypeParmTypeLoc TL) {
2076 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2077}
John McCall51bd8032009-10-18 01:05:36 +00002078void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2079 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002080 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2081 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2082 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2083 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2084 TL.setArgLocInfo(i,
2085 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2086 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002087}
2088void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2089 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2090}
2091void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2092 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2093}
2094void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2095 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002096 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2099 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002100}
John McCall54e14c42009-10-22 22:37:11 +00002101void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2102 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2103 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2104 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2105 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2106 TL.setHasProtocolsAsWritten(Record[Idx++]);
2107 if (TL.hasProtocolsAsWritten())
2108 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2109 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2110}
John McCalla1ee0c52009-10-16 21:56:05 +00002111
2112DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2113 unsigned &Idx) {
2114 QualType InfoTy = GetType(Record[Idx++]);
2115 if (InfoTy.isNull())
2116 return 0;
2117
2118 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2119 TypeLocReader TLR(*this, Record, Idx);
2120 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2121 TLR.Visit(TL);
2122 return DInfo;
2123}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002124
Douglas Gregor8038d512009-04-10 17:25:41 +00002125QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002126 unsigned FastQuals = ID & Qualifiers::FastMask;
2127 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002128
2129 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2130 QualType T;
2131 switch ((pch::PredefinedTypeIDs)Index) {
2132 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002133 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2134 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002135
2136 case pch::PREDEF_TYPE_CHAR_U_ID:
2137 case pch::PREDEF_TYPE_CHAR_S_ID:
2138 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002139 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002140 break;
2141
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002142 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2143 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2144 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2145 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2146 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002147 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002148 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2149 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2150 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2151 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2152 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2153 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002154 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002155 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2156 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2157 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2158 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2159 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002160 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002161 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2162 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002163 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2164 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002165 }
2166
2167 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002168 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002169 }
2170
2171 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002172 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002173 if (TypesLoaded[Index].isNull())
2174 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
John McCall0953e762009-09-24 19:53:00 +00002176 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002177}
2178
John McCall833ca992009-10-29 08:12:44 +00002179TemplateArgumentLocInfo
2180PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2181 const RecordData &Record,
2182 unsigned &Index) {
2183 switch (Kind) {
2184 case TemplateArgument::Expression:
2185 return ReadDeclExpr();
2186 case TemplateArgument::Type:
2187 return GetDeclaratorInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002188 case TemplateArgument::Template: {
2189 SourceLocation
2190 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2191 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2192 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2193 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2194 TemplateNameLoc);
2195 }
John McCall833ca992009-10-29 08:12:44 +00002196 case TemplateArgument::Null:
2197 case TemplateArgument::Integral:
2198 case TemplateArgument::Declaration:
2199 case TemplateArgument::Pack:
2200 return TemplateArgumentLocInfo();
2201 }
2202 llvm::llvm_unreachable("unexpected template argument loc");
2203 return TemplateArgumentLocInfo();
2204}
2205
Douglas Gregor8038d512009-04-10 17:25:41 +00002206Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002207 if (ID == 0)
2208 return 0;
2209
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002210 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002211 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002212 return 0;
2213 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002214
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002215 unsigned Index = ID - 1;
2216 if (!DeclsLoaded[Index])
2217 ReadDeclRecord(DeclOffsets[Index], Index);
2218
2219 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002220}
2221
Chris Lattner887e2b32009-04-27 05:46:25 +00002222/// \brief Resolve the offset of a statement into a statement.
2223///
2224/// This operation will read a new statement from the external
2225/// source each time it is called, and is meant to be used via a
2226/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2227Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002228 // Since we know tha this statement is part of a decl, make sure to use the
2229 // decl cursor to read it.
2230 DeclsCursor.JumpToBit(Offset);
2231 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002232}
2233
Douglas Gregor2cf26342009-04-09 22:27:44 +00002234bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002235 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002236 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002237 "DeclContext has no lexical decls in storage");
2238 uint64_t Offset = DeclContextOffsets[DC].first;
2239 assert(Offset && "DeclContext has no lexical decls in storage");
2240
Douglas Gregor0b748912009-04-14 21:18:50 +00002241 // Keep track of where we are in the stream, then jump back there
2242 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002243 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002244
Douglas Gregor2cf26342009-04-09 22:27:44 +00002245 // Load the record containing all of the declarations lexically in
2246 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002247 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002248 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002249 unsigned Code = DeclsCursor.ReadCode();
2250 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002251 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002252 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2253
2254 // Load all of the declaration IDs
2255 Decls.clear();
2256 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002257 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002258 return false;
2259}
2260
2261bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002262 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002263 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002264 "DeclContext has no visible decls in storage");
2265 uint64_t Offset = DeclContextOffsets[DC].second;
2266 assert(Offset && "DeclContext has no visible decls in storage");
2267
Douglas Gregor0b748912009-04-14 21:18:50 +00002268 // Keep track of where we are in the stream, then jump back there
2269 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002270 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002271
Douglas Gregor2cf26342009-04-09 22:27:44 +00002272 // Load the record containing all of the declarations visible in
2273 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002274 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002275 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002276 unsigned Code = DeclsCursor.ReadCode();
2277 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002278 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002279 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2280 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002281 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002282
2283 Decls.clear();
2284
2285 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002286 while (Idx < Record.size()) {
2287 Decls.push_back(VisibleDeclaration());
2288 Decls.back().Name = ReadDeclarationName(Record, Idx);
2289
Douglas Gregor2cf26342009-04-09 22:27:44 +00002290 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002291 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002292 LoadedDecls.reserve(Size);
2293 for (unsigned I = 0; I < Size; ++I)
2294 LoadedDecls.push_back(Record[Idx++]);
2295 }
2296
Douglas Gregor25123082009-04-22 22:34:57 +00002297 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002298 return false;
2299}
2300
Douglas Gregorfdd01722009-04-14 00:24:19 +00002301void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002302 this->Consumer = Consumer;
2303
Douglas Gregorfdd01722009-04-14 00:24:19 +00002304 if (!Consumer)
2305 return;
2306
2307 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002308 // Force deserialization of this decl, which will cause it to be passed to
2309 // the consumer (or queued).
2310 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002311 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002312
2313 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2314 DeclGroupRef DG(InterestingDecls[I]);
2315 Consumer->HandleTopLevelDecl(DG);
2316 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002317}
2318
Douglas Gregor2cf26342009-04-09 22:27:44 +00002319void PCHReader::PrintStats() {
2320 std::fprintf(stderr, "*** PCH Statistics:\n");
2321
Mike Stump1eb44332009-09-09 15:08:12 +00002322 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002323 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002324 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002325 unsigned NumDeclsLoaded
2326 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2327 (Decl *)0);
2328 unsigned NumIdentifiersLoaded
2329 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2330 IdentifiersLoaded.end(),
2331 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002332 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002333 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2334 SelectorsLoaded.end(),
2335 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002336
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002337 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2338 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002339 if (TotalNumSLocEntries)
2340 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2341 NumSLocEntriesRead, TotalNumSLocEntries,
2342 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002343 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002344 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002345 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2346 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2347 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002348 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002349 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2350 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002351 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002352 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002353 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2354 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002355 if (TotalNumSelectors)
2356 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2357 NumSelectorsLoaded, TotalNumSelectors,
2358 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2359 if (TotalNumStatements)
2360 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2361 NumStatementsRead, TotalNumStatements,
2362 ((float)NumStatementsRead/TotalNumStatements * 100));
2363 if (TotalNumMacros)
2364 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2365 NumMacrosRead, TotalNumMacros,
2366 ((float)NumMacrosRead/TotalNumMacros * 100));
2367 if (TotalLexicalDeclContexts)
2368 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2369 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2370 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2371 * 100));
2372 if (TotalVisibleDeclContexts)
2373 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2374 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2375 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2376 * 100));
2377 if (TotalSelectorsInMethodPool) {
2378 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2379 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2380 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2381 * 100));
2382 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2383 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002384 std::fprintf(stderr, "\n");
2385}
2386
Douglas Gregor668c1a42009-04-21 22:25:48 +00002387void PCHReader::InitializeSema(Sema &S) {
2388 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002389 S.ExternalSource = this;
2390
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002391 // Makes sure any declarations that were deserialized "too early"
2392 // still get added to the identifier's declaration chains.
2393 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2394 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2395 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002396 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002397 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002398
2399 // If there were any tentative definitions, deserialize them and add
2400 // them to Sema's table of tentative definitions.
2401 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2402 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2403 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002404 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002405 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002406
2407 // If there were any locally-scoped external declarations,
2408 // deserialize them and add them to Sema's table of locally-scoped
2409 // external declarations.
2410 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2411 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2412 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2413 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002414
2415 // If there were any ext_vector type declarations, deserialize them
2416 // and add them to Sema's vector of such declarations.
2417 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2418 SemaObj->ExtVectorDecls.push_back(
2419 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002420}
2421
2422IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2423 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002424 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002425 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2426 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2427 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2428 if (Pos == IdTable->end())
2429 return 0;
2430
2431 // Dereferencing the iterator has the effect of building the
2432 // IdentifierInfo node and populating it with the various
2433 // declarations it needs.
2434 return *Pos;
2435}
2436
Mike Stump1eb44332009-09-09 15:08:12 +00002437std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002438PCHReader::ReadMethodPool(Selector Sel) {
2439 if (!MethodPoolLookupTable)
2440 return std::pair<ObjCMethodList, ObjCMethodList>();
2441
2442 // Try to find this selector within our on-disk hash table.
2443 PCHMethodPoolLookupTable *PoolTable
2444 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2445 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002446 if (Pos == PoolTable->end()) {
2447 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002448 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002449 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002450
Douglas Gregor83941df2009-04-25 17:48:32 +00002451 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002452 return *Pos;
2453}
2454
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002455void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002456 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002457 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002458 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002459}
2460
Douglas Gregord89275b2009-07-06 18:54:52 +00002461/// \brief Set the globally-visible declarations associated with the given
2462/// identifier.
2463///
2464/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002465/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002466/// them.
2467///
2468/// \param II an IdentifierInfo that refers to one or more globally-visible
2469/// declarations.
2470///
2471/// \param DeclIDs the set of declaration IDs with the name @p II that are
2472/// visible at global scope.
2473///
2474/// \param Nonrecursive should be true to indicate that the caller knows that
2475/// this call is non-recursive, and therefore the globally-visible declarations
2476/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002477void
2478PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002479 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2480 bool Nonrecursive) {
2481 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2482 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2483 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2484 PII.II = II;
2485 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2486 PII.DeclIDs.push_back(DeclIDs[I]);
2487 return;
2488 }
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Douglas Gregord89275b2009-07-06 18:54:52 +00002490 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2491 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2492 if (SemaObj) {
2493 // Introduce this declaration into the translation-unit scope
2494 // and add it to the declaration chain for this identifier, so
2495 // that (unqualified) name lookup will find it.
2496 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2497 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2498 } else {
2499 // Queue this declaration so that it will be added to the
2500 // translation unit scope and identifier's declaration chain
2501 // once a Sema object is known.
2502 PreloadedDecls.push_back(D);
2503 }
2504 }
2505}
2506
Chris Lattner7356a312009-04-11 21:15:38 +00002507IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002508 if (ID == 0)
2509 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002511 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002512 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002513 return 0;
2514 }
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002516 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002517 if (!IdentifiersLoaded[ID - 1]) {
2518 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002519 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002520
Douglas Gregor02fc7512009-04-28 20:01:51 +00002521 // All of the strings in the PCH file are preceded by a 16-bit
2522 // length. Extract that 16-bit length to avoid having to execute
2523 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002524 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2525 // unsigned integers. This is important to avoid integer overflow when
2526 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002527 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002528 unsigned StrLen = (((unsigned) StrLenPtr[0])
2529 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002530 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002531 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002532 }
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002534 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002535}
2536
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002537void PCHReader::ReadSLocEntry(unsigned ID) {
2538 ReadSLocEntryRecord(ID);
2539}
2540
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002541Selector PCHReader::DecodeSelector(unsigned ID) {
2542 if (ID == 0)
2543 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002544
Douglas Gregora02b1472009-04-28 21:53:25 +00002545 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002546 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002547
2548 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002549 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002550 return Selector();
2551 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002552
2553 unsigned Index = ID - 1;
2554 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2555 // Load this selector from the selector table.
2556 // FIXME: endianness portability issues with SelectorOffsets table
2557 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002558 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002559 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2560 }
2561
2562 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002563}
2564
Mike Stump1eb44332009-09-09 15:08:12 +00002565DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002566PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2567 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2568 switch (Kind) {
2569 case DeclarationName::Identifier:
2570 return DeclarationName(GetIdentifierInfo(Record, Idx));
2571
2572 case DeclarationName::ObjCZeroArgSelector:
2573 case DeclarationName::ObjCOneArgSelector:
2574 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002575 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002576
2577 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002578 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002579 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002580
2581 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002582 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002583 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002584
2585 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002586 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002587 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002588
2589 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002590 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002591 (OverloadedOperatorKind)Record[Idx++]);
2592
2593 case DeclarationName::CXXUsingDirective:
2594 return DeclarationName::getUsingDirectiveName();
2595 }
2596
2597 // Required to silence GCC warning
2598 return DeclarationName();
2599}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002600
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002601/// \brief Read an integral value
2602llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2603 unsigned BitWidth = Record[Idx++];
2604 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2605 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2606 Idx += NumWords;
2607 return Result;
2608}
2609
2610/// \brief Read a signed integral value
2611llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2612 bool isUnsigned = Record[Idx++];
2613 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2614}
2615
Douglas Gregor17fc2232009-04-14 21:55:33 +00002616/// \brief Read a floating-point value
2617llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002618 return llvm::APFloat(ReadAPInt(Record, Idx));
2619}
2620
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002621// \brief Read a string
2622std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2623 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002624 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002625 Idx += Len;
2626 return Result;
2627}
2628
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002629DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002630 return Diag(SourceLocation(), DiagID);
2631}
2632
2633DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002634 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002635}
Douglas Gregor025452f2009-04-17 00:04:06 +00002636
Douglas Gregor668c1a42009-04-21 22:25:48 +00002637/// \brief Retrieve the identifier table associated with the
2638/// preprocessor.
2639IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002640 assert(PP && "Forgot to set Preprocessor ?");
2641 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002642}
2643
Douglas Gregor025452f2009-04-17 00:04:06 +00002644/// \brief Record that the given ID maps to the given switch-case
2645/// statement.
2646void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2647 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2648 SwitchCaseStmts[ID] = SC;
2649}
2650
2651/// \brief Retrieve the switch-case statement with the given ID.
2652SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2653 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2654 return SwitchCaseStmts[ID];
2655}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002656
2657/// \brief Record that the given label statement has been
2658/// deserialized and has the given ID.
2659void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002660 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002661 "Deserialized label twice");
2662 LabelStmts[ID] = S;
2663
2664 // If we've already seen any goto statements that point to this
2665 // label, resolve them now.
2666 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2667 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2668 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2669 Goto->second->setLabel(S);
2670 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002671
2672 // If we've already seen any address-label statements that point to
2673 // this label, resolve them now.
2674 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002675 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002676 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002677 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002678 AddrLabel != AddrLabels.second; ++AddrLabel)
2679 AddrLabel->second->setLabel(S);
2680 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002681}
2682
2683/// \brief Set the label of the given statement to the label
2684/// identified by ID.
2685///
2686/// Depending on the order in which the label and other statements
2687/// referencing that label occur, this operation may complete
2688/// immediately (updating the statement) or it may queue the
2689/// statement to be back-patched later.
2690void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2691 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2692 if (Label != LabelStmts.end()) {
2693 // We've already seen this label, so set the label of the goto and
2694 // we're done.
2695 S->setLabel(Label->second);
2696 } else {
2697 // We haven't seen this label yet, so add this goto to the set of
2698 // unresolved goto statements.
2699 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2700 }
2701}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002702
2703/// \brief Set the label of the given expression to the label
2704/// identified by ID.
2705///
2706/// Depending on the order in which the label and other statements
2707/// referencing that label occur, this operation may complete
2708/// immediately (updating the statement) or it may queue the
2709/// statement to be back-patched later.
2710void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2711 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2712 if (Label != LabelStmts.end()) {
2713 // We've already seen this label, so set the label of the
2714 // label-address expression and we're done.
2715 S->setLabel(Label->second);
2716 } else {
2717 // We haven't seen this label yet, so add this label-address
2718 // expression to the set of unresolved label-address expressions.
2719 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2720 }
2721}
Douglas Gregord89275b2009-07-06 18:54:52 +00002722
2723
Mike Stump1eb44332009-09-09 15:08:12 +00002724PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002725 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2726 Reader.CurrentlyLoadingTypeOrDecl = this;
2727}
2728
2729PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2730 if (!Parent) {
2731 // If any identifiers with corresponding top-level declarations have
2732 // been loaded, load those declarations now.
2733 while (!Reader.PendingIdentifierInfos.empty()) {
2734 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2735 Reader.PendingIdentifierInfos.front().DeclIDs,
2736 true);
2737 Reader.PendingIdentifierInfos.pop_front();
2738 }
2739 }
2740
Mike Stump1eb44332009-09-09 15:08:12 +00002741 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002742}