blob: 9ab3b7a0a2610463805032f1c6cd5bdfbaa1f206 [file] [log] [blame]
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000025#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000026#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000027#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000028#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000030#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000031#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000032#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000036#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000037#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000038#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000040#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041using namespace clang;
42
43//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000044// PCH reader validator implementation
45//===----------------------------------------------------------------------===//
46
47PCHReaderListener::~PCHReaderListener() {}
48
49bool
50PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51 const LangOptions &PPLangOpts = PP.getLangOptions();
52#define PARSE_LANGOPT_BENIGN(Option)
53#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
54 if (PPLangOpts.Option != LangOpts.Option) { \
55 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
56 return true; \
57 }
58
59 PARSE_LANGOPT_BENIGN(Trigraphs);
60 PARSE_LANGOPT_BENIGN(BCPLComment);
61 PARSE_LANGOPT_BENIGN(DollarIdents);
62 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64 PARSE_LANGOPT_BENIGN(ImplicitInt);
65 PARSE_LANGOPT_BENIGN(Digraphs);
66 PARSE_LANGOPT_BENIGN(HexFloats);
67 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71 PARSE_LANGOPT_BENIGN(CXXOperatorName);
72 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000075 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000076 PARSE_LANGOPT_BENIGN(PascalStrings);
77 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000078 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000079 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000080 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000081 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
82 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
83 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
84 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000085 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000086 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000087 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000088 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
89 PARSE_LANGOPT_BENIGN(EmitAllDecls);
90 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
91 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000092 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000093 diag::warn_pch_heinous_extensions);
94 // FIXME: Most of the options below are benign if the macro wasn't
95 // used. Unfortunately, this means that a PCH compiled without
96 // optimization can't be used with optimization turned on, even
97 // though the only thing that changes is whether __OPTIMIZE__ was
98 // defined... but if __OPTIMIZE__ never showed up in the header, it
99 // doesn't matter. We could consider making this some special kind
100 // of check.
101 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
102 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
103 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
104 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
105 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
106 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
107 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
108 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000109 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000110 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000111 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000112 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
113 return true;
114 }
115 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000116 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
117 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000118 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000119 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000120 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000121 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000122#undef PARSE_LANGOPT_IRRELEVANT
123#undef PARSE_LANGOPT_BENIGN
124
125 return false;
126}
127
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000128bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
129 if (Triple == PP.getTargetInfo().getTriple().str())
130 return false;
131
132 Reader.Diag(diag::warn_pch_target_triple)
133 << Triple << PP.getTargetInfo().getTriple().str();
134 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000135}
136
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000137bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000138 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000139 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000140 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000141 // We are in the context of an implicit include, so the predefines buffer will
142 // have a #include entry for the PCH file itself (as normalized by the
143 // preprocessor initialization). Find it and skip over it in the checking
144 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000145 llvm::SmallString<256> PCHInclude;
146 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000147 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000148 PCHInclude += "\"\n";
149 std::pair<llvm::StringRef,llvm::StringRef> Split =
150 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
151 llvm::StringRef Left = Split.first, Right = Split.second;
152 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
153
154 // If the predefines is equal to the joined left and right halves, we're done!
155 if (Left.size() + Right.size() == PCHPredef.size() &&
156 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000157 return false;
158
159 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000161 // The predefines buffers are different. Determine what the differences are,
162 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000163 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
164 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
165
166 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
167 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
168 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000169
Daniel Dunbar499baed2009-11-11 05:26:28 +0000170 // Sort both sets of predefined buffer lines, since we allow some extra
171 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000172 std::sort(CmdLineLines.begin(), CmdLineLines.end());
173 std::sort(PCHLines.begin(), PCHLines.end());
174
Daniel Dunbar499baed2009-11-11 05:26:28 +0000175 // Determine which predefines that were used to build the PCH file are missing
176 // from the command line.
177 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000178 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) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000185 llvm::StringRef Missing = MissingPredefines[I];
186 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000187 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
188 return true;
189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000191 // This is a macro definition. Determine the name of the macro we're
192 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000193 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000194 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-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");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000198 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000199
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000200 // Determine whether this macro was given a different definition on the
201 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000202 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000203 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000204 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000205 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
206 MacroDefStart);
207 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000208 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000209 // Different macro; we're done.
210 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000211 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000212 }
Mike Stump11289f42009-09-09 15:08:12 +0000213
214 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000215 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000216 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000217 (*ConflictPos)[MacroDefLen] != '(')
218 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000219
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000220 // We found a conflicting macro definition.
221 break;
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000224 if (ConflictPos != CmdLineLines.end()) {
225 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
226 << MacroName;
227
228 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000229 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
230 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
231 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
232 .getFileLocWithOffset(Offset);
233 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000234
235 ConflictingDefines = true;
236 continue;
237 }
Mike Stump11289f42009-09-09 15:08:12 +0000238
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000239 // If the macro doesn't conflict, then we'll just pick up the macro
240 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000241 if (ConflictingDefines)
242 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000243
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000244 if (!MissingDefines) {
245 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
246 MissingDefines = true;
247 }
248
249 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000250 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
251 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
252 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000253 .getFileLocWithOffset(Offset);
254 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
255 }
Mike Stump11289f42009-09-09 15:08:12 +0000256
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000257 if (ConflictingDefines)
258 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000259
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000260 // Determine what predefines were introduced based on command-line
261 // parameters that were not present when building the PCH
262 // file. Extra #defines are okay, so long as the identifiers being
263 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000264 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000265 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
266 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000267 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000268 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000269 llvm::StringRef &Extra = ExtraPredefines[I];
270 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000271 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
272 return true;
273 }
274
275 // This is an extra macro definition. Determine the name of the
276 // macro we're defining.
277 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000278 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000279 = Extra.find_first_of("( \n\r", StartOfMacroName);
280 assert(EndOfMacroName != std::string::npos &&
281 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000282 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000283
284 // Check whether this name was used somewhere in the PCH file. If
285 // so, defining it as a macro could change behavior, so we reject
286 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000287 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000288 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000289 return true;
290 }
291
292 // Add this definition to the suggested predefines buffer.
293 SuggestedPredefines += Extra;
294 SuggestedPredefines += '\n';
295 }
296
297 // If we get here, it's because the predefines buffer had compatible
298 // contents. Accept the PCH file.
299 return false;
300}
301
302void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
303 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
304}
305
306void PCHValidator::ReadCounter(unsigned Value) {
307 PP.setCounterValue(Value);
308}
309
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000310//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000311// PCH reader implementation
312//===----------------------------------------------------------------------===//
313
Mike Stump11289f42009-09-09 15:08:12 +0000314PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
315 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000316 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
317 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000318 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000319 IdentifierTableData(0), IdentifierLookupTable(0),
320 IdentifierOffsets(0),
321 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
322 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000323 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000324 NumStatHits(0), NumStatMisses(0),
325 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000326 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000327 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000328 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000329 RelocatablePCH = false;
330}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000331
332PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000333 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000334 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000335 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000336 IdentifierTableData(0), IdentifierLookupTable(0),
337 IdentifierOffsets(0),
338 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
339 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000340 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000341 NumStatHits(0), NumStatMisses(0),
342 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000343 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000344 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000345 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000346 RelocatablePCH = false;
347}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000348
349PCHReader::~PCHReader() {}
350
Chris Lattner1de76db2009-04-27 05:58:23 +0000351Expr *PCHReader::ReadDeclExpr() {
352 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
353}
354
355Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000356 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000357}
358
359
Douglas Gregora868bbd2009-04-21 22:25:48 +0000360namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000361class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000362 PCHReader &Reader;
363
364public:
365 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
366
367 typedef Selector external_key_type;
368 typedef external_key_type internal_key_type;
369
370 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000371
Douglas Gregorc78d3462009-04-24 21:10:55 +0000372 static bool EqualKey(const internal_key_type& a,
373 const internal_key_type& b) {
374 return a == b;
375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376
Douglas Gregorc78d3462009-04-24 21:10:55 +0000377 static unsigned ComputeHash(Selector Sel) {
378 unsigned N = Sel.getNumArgs();
379 if (N == 0)
380 ++N;
381 unsigned R = 5381;
382 for (unsigned I = 0; I != N; ++I)
383 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000384 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000385 return R;
386 }
Mike Stump11289f42009-09-09 15:08:12 +0000387
Douglas Gregorc78d3462009-04-24 21:10:55 +0000388 // This hopefully will just get inlined and removed by the optimizer.
389 static const internal_key_type&
390 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000391
Douglas Gregorc78d3462009-04-24 21:10:55 +0000392 static std::pair<unsigned, unsigned>
393 ReadKeyDataLength(const unsigned char*& d) {
394 using namespace clang::io;
395 unsigned KeyLen = ReadUnalignedLE16(d);
396 unsigned DataLen = ReadUnalignedLE16(d);
397 return std::make_pair(KeyLen, DataLen);
398 }
Mike Stump11289f42009-09-09 15:08:12 +0000399
Douglas Gregor95c13f52009-04-25 17:48:32 +0000400 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000401 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000402 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000403 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000404 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000405 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
406 if (N == 0)
407 return SelTable.getNullarySelector(FirstII);
408 else if (N == 1)
409 return SelTable.getUnarySelector(FirstII);
410
411 llvm::SmallVector<IdentifierInfo *, 16> Args;
412 Args.push_back(FirstII);
413 for (unsigned I = 1; I != N; ++I)
414 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
415
Douglas Gregor038c3382009-05-22 22:45:36 +0000416 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Douglas Gregorc78d3462009-04-24 21:10:55 +0000419 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
420 using namespace clang::io;
421 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
422 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
423
424 data_type Result;
425
426 // Load instance methods
427 ObjCMethodList *Prev = 0;
428 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000429 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000430 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
431 if (!Result.first.Method) {
432 // This is the first method, which is the easy case.
433 Result.first.Method = Method;
434 Prev = &Result.first;
435 continue;
436 }
437
438 Prev->Next = new ObjCMethodList(Method, 0);
439 Prev = Prev->Next;
440 }
441
442 // Load factory methods
443 Prev = 0;
444 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000445 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000446 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
447 if (!Result.second.Method) {
448 // This is the first method, which is the easy case.
449 Result.second.Method = Method;
450 Prev = &Result.second;
451 continue;
452 }
453
454 Prev->Next = new ObjCMethodList(Method, 0);
455 Prev = Prev->Next;
456 }
457
458 return Result;
459 }
460};
Mike Stump11289f42009-09-09 15:08:12 +0000461
462} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000463
464/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000465typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000466 PCHMethodPoolLookupTable;
467
468namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000469class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000470 PCHReader &Reader;
471
472 // If we know the IdentifierInfo in advance, it is here and we will
473 // not build a new one. Used when deserializing information about an
474 // identifier that was constructed before the PCH file was read.
475 IdentifierInfo *KnownII;
476
477public:
478 typedef IdentifierInfo * data_type;
479
480 typedef const std::pair<const char*, unsigned> external_key_type;
481
482 typedef external_key_type internal_key_type;
483
Mike Stump11289f42009-09-09 15:08:12 +0000484 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000485 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Douglas Gregora868bbd2009-04-21 22:25:48 +0000487 static bool EqualKey(const internal_key_type& a,
488 const internal_key_type& b) {
489 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
490 : false;
491 }
Mike Stump11289f42009-09-09 15:08:12 +0000492
Douglas Gregora868bbd2009-04-21 22:25:48 +0000493 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000494 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000495 }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Douglas Gregora868bbd2009-04-21 22:25:48 +0000497 // This hopefully will just get inlined and removed by the optimizer.
498 static const internal_key_type&
499 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregora868bbd2009-04-21 22:25:48 +0000501 static std::pair<unsigned, unsigned>
502 ReadKeyDataLength(const unsigned char*& d) {
503 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000504 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000505 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000506 return std::make_pair(KeyLen, DataLen);
507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregora868bbd2009-04-21 22:25:48 +0000509 static std::pair<const char*, unsigned>
510 ReadKey(const unsigned char* d, unsigned n) {
511 assert(n >= 2 && d[n-1] == '\0');
512 return std::make_pair((const char*) d, n-1);
513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
515 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000516 const unsigned char* d,
517 unsigned DataLen) {
518 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000519 pch::IdentID ID = ReadUnalignedLE32(d);
520 bool IsInteresting = ID & 0x01;
521
522 // Wipe out the "is interesting" bit.
523 ID = ID >> 1;
524
525 if (!IsInteresting) {
526 // For unintersting identifiers, just build the IdentifierInfo
527 // and associate it with the persistent ID.
528 IdentifierInfo *II = KnownII;
529 if (!II)
530 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
531 k.first, k.first + k.second);
532 Reader.SetIdentifierInfo(ID, II);
533 return II;
534 }
535
Douglas Gregorb9256522009-04-28 21:32:13 +0000536 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000537 bool CPlusPlusOperatorKeyword = Bits & 0x01;
538 Bits >>= 1;
539 bool Poisoned = Bits & 0x01;
540 Bits >>= 1;
541 bool ExtensionToken = Bits & 0x01;
542 Bits >>= 1;
543 bool hasMacroDefinition = Bits & 0x01;
544 Bits >>= 1;
545 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
546 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000548 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000549 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000550
551 // Build the IdentifierInfo itself and link the identifier ID with
552 // the new IdentifierInfo.
553 IdentifierInfo *II = KnownII;
554 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000555 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
556 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000557 Reader.SetIdentifierInfo(ID, II);
558
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000559 // Set or check the various bits in the IdentifierInfo structure.
560 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000561 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000562 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000563 "Incorrect extension token flag");
564 (void)ExtensionToken;
565 II->setIsPoisoned(Poisoned);
566 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
567 "Incorrect C++ operator keyword flag");
568 (void)CPlusPlusOperatorKeyword;
569
Douglas Gregorc3366a52009-04-21 23:56:24 +0000570 // If this identifier is a macro, deserialize the macro
571 // definition.
572 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000573 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000574 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000575 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000576 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000577
578 // Read all of the declarations visible at global scope with this
579 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000580 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000581 if (DataLen > 0) {
582 llvm::SmallVector<uint32_t, 4> DeclIDs;
583 for (; DataLen > 0; DataLen -= 4)
584 DeclIDs.push_back(ReadUnalignedLE32(d));
585 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000586 }
Mike Stump11289f42009-09-09 15:08:12 +0000587
Douglas Gregora868bbd2009-04-21 22:25:48 +0000588 return II;
589 }
590};
Mike Stump11289f42009-09-09 15:08:12 +0000591
592} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000593
594/// \brief The on-disk hash table used to contain information about
595/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000596typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000597 PCHIdentifierLookupTable;
598
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000599bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000600 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
601 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000602 return true;
603}
604
Douglas Gregor92863e42009-04-10 23:10:45 +0000605/// \brief Check the contents of the predefines buffer against the
606/// contents of the predefines buffer used to build the PCH file.
607///
608/// The contents of the two predefines buffers should be the same. If
609/// not, then some command-line option changed the preprocessor state
610/// and we must reject the PCH file.
611///
612/// \param PCHPredef The start of the predefines buffer in the PCH
613/// file.
614///
615/// \param PCHPredefLen The length of the predefines buffer in the PCH
616/// file.
617///
618/// \param PCHBufferID The FileID for the PCH predefines buffer.
619///
620/// \returns true if there was a mismatch (in which case the PCH file
621/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000622bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000623 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000624 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000625 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000626 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000627 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000628 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000629}
630
Douglas Gregorc5046832009-04-27 18:38:38 +0000631//===----------------------------------------------------------------------===//
632// Source Manager Deserialization
633//===----------------------------------------------------------------------===//
634
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000635/// \brief Read the line table in the source manager block.
636/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000637bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000638 unsigned Idx = 0;
639 LineTableInfo &LineTable = SourceMgr.getLineTable();
640
641 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000642 std::map<int, int> FileIDs;
643 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000644 // Extract the file name
645 unsigned FilenameLen = Record[Idx++];
646 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
647 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000648 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000649 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000650 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000651 }
652
653 // Parse the line entries
654 std::vector<LineEntry> Entries;
655 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000656 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000657
658 // Extract the line entries
659 unsigned NumEntries = Record[Idx++];
660 Entries.clear();
661 Entries.reserve(NumEntries);
662 for (unsigned I = 0; I != NumEntries; ++I) {
663 unsigned FileOffset = Record[Idx++];
664 unsigned LineNo = Record[Idx++];
665 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000666 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000667 = (SrcMgr::CharacteristicKind)Record[Idx++];
668 unsigned IncludeOffset = Record[Idx++];
669 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
670 FileKind, IncludeOffset));
671 }
672 LineTable.AddEntry(FID, Entries);
673 }
674
675 return false;
676}
677
Douglas Gregorc5046832009-04-27 18:38:38 +0000678namespace {
679
Benjamin Kramer16634c22009-11-28 10:07:24 +0000680class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000681public:
682 const bool hasStat;
683 const ino_t ino;
684 const dev_t dev;
685 const mode_t mode;
686 const time_t mtime;
687 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000688
Douglas Gregorc5046832009-04-27 18:38:38 +0000689 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000690 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
691
Douglas Gregorc5046832009-04-27 18:38:38 +0000692 PCHStatData()
693 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
694};
695
Benjamin Kramer16634c22009-11-28 10:07:24 +0000696class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000697 public:
698 typedef const char *external_key_type;
699 typedef const char *internal_key_type;
700
701 typedef PCHStatData data_type;
702
703 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000704 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000705 }
706
707 static internal_key_type GetInternalKey(const char *path) { return path; }
708
709 static bool EqualKey(internal_key_type a, internal_key_type b) {
710 return strcmp(a, b) == 0;
711 }
712
713 static std::pair<unsigned, unsigned>
714 ReadKeyDataLength(const unsigned char*& d) {
715 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
716 unsigned DataLen = (unsigned) *d++;
717 return std::make_pair(KeyLen + 1, DataLen);
718 }
719
720 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
721 return (const char *)d;
722 }
723
724 static data_type ReadData(const internal_key_type, const unsigned char *d,
725 unsigned /*DataLen*/) {
726 using namespace clang::io;
727
728 if (*d++ == 1)
729 return data_type();
730
731 ino_t ino = (ino_t) ReadUnalignedLE32(d);
732 dev_t dev = (dev_t) ReadUnalignedLE32(d);
733 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000734 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000735 off_t size = (off_t) ReadUnalignedLE64(d);
736 return data_type(ino, dev, mode, mtime, size);
737 }
738};
739
740/// \brief stat() cache for precompiled headers.
741///
742/// This cache is very similar to the stat cache used by pretokenized
743/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000744class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000745 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
746 CacheTy *Cache;
747
748 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000749public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000750 PCHStatCache(const unsigned char *Buckets,
751 const unsigned char *Base,
752 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000753 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000754 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
755 Cache = CacheTy::Create(Buckets, Base);
756 }
757
758 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000759
Douglas Gregorc5046832009-04-27 18:38:38 +0000760 int stat(const char *path, struct stat *buf) {
761 // Do the lookup for the file's data in the PCH file.
762 CacheTy::iterator I = Cache->find(path);
763
764 // If we don't get a hit in the PCH file just forward to 'stat'.
765 if (I == Cache->end()) {
766 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000767 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000768 }
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregorc5046832009-04-27 18:38:38 +0000770 ++NumStatHits;
771 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Douglas Gregorc5046832009-04-27 18:38:38 +0000773 if (!Data.hasStat)
774 return 1;
775
776 buf->st_ino = Data.ino;
777 buf->st_dev = Data.dev;
778 buf->st_mtime = Data.mtime;
779 buf->st_mode = Data.mode;
780 buf->st_size = Data.size;
781 return 0;
782 }
783};
784} // end anonymous namespace
785
786
Douglas Gregora7f71a92009-04-10 03:52:48 +0000787/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000788PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000789 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000790
791 // Set the source-location entry cursor to the current position in
792 // the stream. This cursor will be used to read the contents of the
793 // source manager block initially, and then lazily read
794 // source-location entries as needed.
795 SLocEntryCursor = Stream;
796
797 // The stream itself is going to skip over the source manager block.
798 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000799 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000800 return Failure;
801 }
802
803 // Enter the source manager block.
804 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000805 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000806 return Failure;
807 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000808
Douglas Gregora7f71a92009-04-10 03:52:48 +0000809 RecordData Record;
810 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000811 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000812 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000813 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000814 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000815 return Failure;
816 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000817 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000818 }
Mike Stump11289f42009-09-09 15:08:12 +0000819
Douglas Gregora7f71a92009-04-10 03:52:48 +0000820 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
821 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000822 SLocEntryCursor.ReadSubBlockID();
823 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000824 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000825 return Failure;
826 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000827 continue;
828 }
Mike Stump11289f42009-09-09 15:08:12 +0000829
Douglas Gregora7f71a92009-04-10 03:52:48 +0000830 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000831 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000832 continue;
833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregora7f71a92009-04-10 03:52:48 +0000835 // Read a record.
836 const char *BlobStart;
837 unsigned BlobLen;
838 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000839 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000840 default: // Default behavior: ignore.
841 break;
842
Chris Lattner184e65d2009-04-14 23:22:57 +0000843 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000844 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000845 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000846 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000847
848 case pch::SM_HEADER_FILE_INFO: {
849 HeaderFileInfo HFI;
850 HFI.isImport = Record[0];
851 HFI.DirInfo = Record[1];
852 HFI.NumIncludes = Record[2];
853 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000854 if (Listener)
855 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000856 break;
857 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000858
859 case pch::SM_SLOC_FILE_ENTRY:
860 case pch::SM_SLOC_BUFFER_ENTRY:
861 case pch::SM_SLOC_INSTANTIATION_ENTRY:
862 // Once we hit one of the source location entries, we're done.
863 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000864 }
865 }
866}
867
Douglas Gregor258ae542009-04-27 06:38:32 +0000868/// \brief Read in the source location entry with the given ID.
869PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
870 if (ID == 0)
871 return Success;
872
873 if (ID > TotalNumSLocEntries) {
874 Error("source location entry ID out-of-range for PCH file");
875 return Failure;
876 }
877
878 ++NumSLocEntriesRead;
879 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
880 unsigned Code = SLocEntryCursor.ReadCode();
881 if (Code == llvm::bitc::END_BLOCK ||
882 Code == llvm::bitc::ENTER_SUBBLOCK ||
883 Code == llvm::bitc::DEFINE_ABBREV) {
884 Error("incorrectly-formatted source location entry in PCH file");
885 return Failure;
886 }
887
Douglas Gregor258ae542009-04-27 06:38:32 +0000888 RecordData Record;
889 const char *BlobStart;
890 unsigned BlobLen;
891 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
892 default:
893 Error("incorrectly-formatted source location entry in PCH file");
894 return Failure;
895
896 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000897 std::string Filename(BlobStart, BlobStart + BlobLen);
898 MaybeAddSystemRootToFilename(Filename);
899 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000900 if (File == 0) {
901 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000902 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000903 ErrorStr += "' referenced by PCH file";
904 Error(ErrorStr.c_str());
905 return Failure;
906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor258ae542009-04-27 06:38:32 +0000908 FileID FID = SourceMgr.createFileID(File,
909 SourceLocation::getFromRawEncoding(Record[1]),
910 (SrcMgr::CharacteristicKind)Record[2],
911 ID, Record[0]);
912 if (Record[3])
913 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
914 .setHasLineDirectives();
915
916 break;
917 }
918
919 case pch::SM_SLOC_BUFFER_ENTRY: {
920 const char *Name = BlobStart;
921 unsigned Offset = Record[0];
922 unsigned Code = SLocEntryCursor.ReadCode();
923 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000924 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000925 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
926 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
927 (void)RecCode;
928 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000929 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000930 BlobStart + BlobLen - 1,
931 Name);
932 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000933
Douglas Gregore6648fb2009-04-28 20:33:11 +0000934 if (strcmp(Name, "<built-in>") == 0) {
935 PCHPredefinesBufferID = BufferID;
936 PCHPredefines = BlobStart;
937 PCHPredefinesLen = BlobLen - 1;
938 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000939
940 break;
941 }
942
943 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000944 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000945 = SourceLocation::getFromRawEncoding(Record[1]);
946 SourceMgr.createInstantiationLoc(SpellingLoc,
947 SourceLocation::getFromRawEncoding(Record[2]),
948 SourceLocation::getFromRawEncoding(Record[3]),
949 Record[4],
950 ID,
951 Record[0]);
952 break;
Mike Stump11289f42009-09-09 15:08:12 +0000953 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000954 }
955
956 return Success;
957}
958
Chris Lattnere78a6be2009-04-27 01:05:14 +0000959/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
960/// specified cursor. Read the abbreviations that are at the top of the block
961/// and then leave the cursor pointing into the block.
962bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
963 unsigned BlockID) {
964 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000965 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000966 return Failure;
967 }
Mike Stump11289f42009-09-09 15:08:12 +0000968
Chris Lattnere78a6be2009-04-27 01:05:14 +0000969 while (true) {
970 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattnere78a6be2009-04-27 01:05:14 +0000972 // We expect all abbrevs to be at the start of the block.
973 if (Code != llvm::bitc::DEFINE_ABBREV)
974 return false;
975 Cursor.ReadAbbrevRecord();
976 }
977}
978
Douglas Gregorc3366a52009-04-21 23:56:24 +0000979void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000980 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregorc3366a52009-04-21 23:56:24 +0000982 // Keep track of where we are in the stream, then jump back there
983 // after reading this macro.
984 SavedStreamPosition SavedPosition(Stream);
985
986 Stream.JumpToBit(Offset);
987 RecordData Record;
988 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
989 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000990
Douglas Gregorc3366a52009-04-21 23:56:24 +0000991 while (true) {
992 unsigned Code = Stream.ReadCode();
993 switch (Code) {
994 case llvm::bitc::END_BLOCK:
995 return;
996
997 case llvm::bitc::ENTER_SUBBLOCK:
998 // No known subblocks, always skip them.
999 Stream.ReadSubBlockID();
1000 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001001 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001002 return;
1003 }
1004 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001005
Douglas Gregorc3366a52009-04-21 23:56:24 +00001006 case llvm::bitc::DEFINE_ABBREV:
1007 Stream.ReadAbbrevRecord();
1008 continue;
1009 default: break;
1010 }
1011
1012 // Read a record.
1013 Record.clear();
1014 pch::PreprocessorRecordTypes RecType =
1015 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1016 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001017 case pch::PP_MACRO_OBJECT_LIKE:
1018 case pch::PP_MACRO_FUNCTION_LIKE: {
1019 // If we already have a macro, that means that we've hit the end
1020 // of the definition of the macro we were looking for. We're
1021 // done.
1022 if (Macro)
1023 return;
1024
1025 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1026 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001027 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001028 return;
1029 }
1030 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1031 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001032
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001033 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001034 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregorc3366a52009-04-21 23:56:24 +00001036 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1037 // Decode function-like macro info.
1038 bool isC99VarArgs = Record[3];
1039 bool isGNUVarArgs = Record[4];
1040 MacroArgs.clear();
1041 unsigned NumArgs = Record[5];
1042 for (unsigned i = 0; i != NumArgs; ++i)
1043 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1044
1045 // Install function-like macro info.
1046 MI->setIsFunctionLike();
1047 if (isC99VarArgs) MI->setIsC99Varargs();
1048 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001049 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001050 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001051 }
1052
1053 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001054 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001055
1056 // Remember that we saw this macro last so that we add the tokens that
1057 // form its body to it.
1058 Macro = MI;
1059 ++NumMacrosRead;
1060 break;
1061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Douglas Gregorc3366a52009-04-21 23:56:24 +00001063 case pch::PP_TOKEN: {
1064 // If we see a TOKEN before a PP_MACRO_*, then the file is
1065 // erroneous, just pretend we didn't see this.
1066 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregorc3366a52009-04-21 23:56:24 +00001068 Token Tok;
1069 Tok.startToken();
1070 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1071 Tok.setLength(Record[1]);
1072 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1073 Tok.setIdentifierInfo(II);
1074 Tok.setKind((tok::TokenKind)Record[3]);
1075 Tok.setFlag((Token::TokenFlags)Record[4]);
1076 Macro->AddTokenToBody(Tok);
1077 break;
1078 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001079 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001080 }
1081}
1082
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001083void PCHReader::ReadDefinedMacros() {
1084 // If there was no preprocessor block, do nothing.
1085 if (!MacroCursor.getBitStreamReader())
1086 return;
1087
1088 llvm::BitstreamCursor Cursor = MacroCursor;
1089 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1090 Error("malformed preprocessor block record in PCH file");
1091 return;
1092 }
1093
1094 RecordData Record;
1095 while (true) {
1096 unsigned Code = Cursor.ReadCode();
1097 if (Code == llvm::bitc::END_BLOCK) {
1098 if (Cursor.ReadBlockEnd())
1099 Error("error at end of preprocessor block in PCH file");
1100 return;
1101 }
1102
1103 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1104 // No known subblocks, always skip them.
1105 Cursor.ReadSubBlockID();
1106 if (Cursor.SkipBlock()) {
1107 Error("malformed block record in PCH file");
1108 return;
1109 }
1110 continue;
1111 }
1112
1113 if (Code == llvm::bitc::DEFINE_ABBREV) {
1114 Cursor.ReadAbbrevRecord();
1115 continue;
1116 }
1117
1118 // Read a record.
1119 const char *BlobStart;
1120 unsigned BlobLen;
1121 Record.clear();
1122 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1123 default: // Default behavior: ignore.
1124 break;
1125
1126 case pch::PP_MACRO_OBJECT_LIKE:
1127 case pch::PP_MACRO_FUNCTION_LIKE:
1128 DecodeIdentifierInfo(Record[0]);
1129 break;
1130
1131 case pch::PP_TOKEN:
1132 // Ignore tokens.
1133 break;
1134 }
1135 }
1136}
1137
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001138/// \brief If we are loading a relocatable PCH file, and the filename is
1139/// not an absolute path, add the system root to the beginning of the file
1140/// name.
1141void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1142 // If this is not a relocatable PCH file, there's nothing to do.
1143 if (!RelocatablePCH)
1144 return;
Mike Stump11289f42009-09-09 15:08:12 +00001145
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001146 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001147 return;
1148
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001149 if (isysroot == 0) {
1150 // If no system root was given, default to '/'
1151 Filename.insert(Filename.begin(), '/');
1152 return;
1153 }
Mike Stump11289f42009-09-09 15:08:12 +00001154
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001155 unsigned Length = strlen(isysroot);
1156 if (isysroot[Length - 1] != '/')
1157 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001158
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001159 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1160}
1161
Mike Stump11289f42009-09-09 15:08:12 +00001162PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001163PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001164 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001165 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001166 return Failure;
1167 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001168
1169 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001170 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001171 while (!Stream.AtEndOfStream()) {
1172 unsigned Code = Stream.ReadCode();
1173 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001174 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001175 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001176 return Failure;
1177 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001178
Douglas Gregor55abb232009-04-10 20:39:37 +00001179 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001180 }
1181
1182 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1183 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001184 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001185 // We lazily load the decls block, but we want to set up the
1186 // DeclsCursor cursor to point into it. Clone our current bitcode
1187 // cursor to it, enter the block and read the abbrevs in that block.
1188 // With the main cursor, we just skip over it.
1189 DeclsCursor = Stream;
1190 if (Stream.SkipBlock() || // Skip with the main cursor.
1191 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001192 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001193 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001194 return Failure;
1195 }
1196 break;
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001198 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001199 MacroCursor = Stream;
1200 if (PP)
1201 PP->setExternalSource(this);
1202
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001203 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001204 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001205 return Failure;
1206 }
1207 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001208
Douglas Gregora7f71a92009-04-10 03:52:48 +00001209 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001210 switch (ReadSourceManagerBlock()) {
1211 case Success:
1212 break;
1213
1214 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001215 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001216 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001217
1218 case IgnorePCH:
1219 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001220 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001221 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001222 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001223 continue;
1224 }
1225
1226 if (Code == llvm::bitc::DEFINE_ABBREV) {
1227 Stream.ReadAbbrevRecord();
1228 continue;
1229 }
1230
1231 // Read and process a record.
1232 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001233 const char *BlobStart = 0;
1234 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001235 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001236 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001237 default: // Default behavior: ignore.
1238 break;
1239
1240 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001241 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001242 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001243 return Failure;
1244 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001245 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001246 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001247 break;
1248
1249 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001250 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001251 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001252 return Failure;
1253 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001254 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001255 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001256 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001257
1258 case pch::LANGUAGE_OPTIONS:
1259 if (ParseLanguageOptions(Record))
1260 return IgnorePCH;
1261 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001262
Douglas Gregor7b71e632009-04-27 22:23:34 +00001263 case pch::METADATA: {
1264 if (Record[0] != pch::VERSION_MAJOR) {
1265 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1266 : diag::warn_pch_version_too_new);
1267 return IgnorePCH;
1268 }
1269
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001270 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001271 if (Listener) {
1272 std::string TargetTriple(BlobStart, BlobLen);
1273 if (Listener->ReadTargetTriple(TargetTriple))
1274 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001275 }
1276 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001277 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001278
1279 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001280 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001281 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001283 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001284 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001285 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001286 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001287 if (PP)
1288 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001289 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001290 break;
1291
1292 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001293 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001294 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001295 return Failure;
1296 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001297 IdentifierOffsets = (const uint32_t *)BlobStart;
1298 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001299 if (PP)
1300 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001301 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001302
1303 case pch::EXTERNAL_DEFINITIONS:
1304 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001305 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001306 return Failure;
1307 }
1308 ExternalDefinitions.swap(Record);
1309 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001310
Douglas Gregor652d82a2009-04-18 05:55:16 +00001311 case pch::SPECIAL_TYPES:
1312 SpecialTypes.swap(Record);
1313 break;
1314
Douglas Gregor08f01292009-04-17 22:13:46 +00001315 case pch::STATISTICS:
1316 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001317 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001318 TotalLexicalDeclContexts = Record[2];
1319 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001320 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001321
Douglas Gregord4df8652009-04-22 22:02:47 +00001322 case pch::TENTATIVE_DEFINITIONS:
1323 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001324 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001325 return Failure;
1326 }
1327 TentativeDefinitions.swap(Record);
1328 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001329
1330 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1331 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001332 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001333 return Failure;
1334 }
1335 LocallyScopedExternalDecls.swap(Record);
1336 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001337
Douglas Gregor95c13f52009-04-25 17:48:32 +00001338 case pch::SELECTOR_OFFSETS:
1339 SelectorOffsets = (const uint32_t *)BlobStart;
1340 TotalNumSelectors = Record[0];
1341 SelectorsLoaded.resize(TotalNumSelectors);
1342 break;
1343
Douglas Gregorc78d3462009-04-24 21:10:55 +00001344 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001345 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1346 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001347 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001348 = PCHMethodPoolLookupTable::Create(
1349 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001350 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001351 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001352 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001353 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001354
1355 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001356 if (!Record.empty() && Listener)
1357 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001358 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001359
1360 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001361 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001362 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001363 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001364 break;
1365
1366 case pch::SOURCE_LOCATION_PRELOADS:
1367 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1368 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1369 if (Result != Success)
1370 return Result;
1371 }
1372 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001373
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001374 case pch::STAT_CACHE: {
1375 PCHStatCache *MyStatCache =
1376 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1377 (const unsigned char *)BlobStart,
1378 NumStatHits, NumStatMisses);
1379 FileMgr.addStatCache(MyStatCache);
1380 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001381 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001382 }
1383
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001384 case pch::EXT_VECTOR_DECLS:
1385 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001386 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001387 return Failure;
1388 }
1389 ExtVectorDecls.swap(Record);
1390 break;
1391
Douglas Gregor45fe0362009-05-12 01:31:05 +00001392 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001393 ActualOriginalFileName.assign(BlobStart, BlobLen);
1394 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001395 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001396 break;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001398 case pch::COMMENT_RANGES:
1399 Comments = (SourceRange *)BlobStart;
1400 NumComments = BlobLen / sizeof(SourceRange);
1401 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001402
Ted Kremenek17437132010-01-22 20:59:36 +00001403 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek18e066f2010-01-22 22:12:47 +00001404 llvm::StringRef CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001405 llvm::StringRef PCHBranch(BlobStart, BlobLen);
1406 if (CurBranch != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001407 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1408 return IgnorePCH;
1409 }
1410 break;
1411 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001412 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001413 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001414 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001415 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001416}
1417
Douglas Gregor92863e42009-04-10 23:10:45 +00001418PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001419 // Set the PCH file name.
1420 this->FileName = FileName;
1421
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001422 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001423 //
1424 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001425 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001426 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001427 if (!Buffer) {
1428 Error(ErrStr.c_str());
1429 return IgnorePCH;
1430 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001431
1432 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001433 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001434 (const unsigned char *)Buffer->getBufferEnd());
1435 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001436
1437 // Sniff for the signature.
1438 if (Stream.Read(8) != 'C' ||
1439 Stream.Read(8) != 'P' ||
1440 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001441 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001442 Diag(diag::err_not_a_pch_file) << FileName;
1443 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001444 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001445
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001446 while (!Stream.AtEndOfStream()) {
1447 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001448
Douglas Gregor92863e42009-04-10 23:10:45 +00001449 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001450 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001451 return Failure;
1452 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001453
1454 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001455
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001456 // We only know the PCH subblock ID.
1457 switch (BlockID) {
1458 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001459 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001460 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001461 return Failure;
1462 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001463 break;
1464 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001465 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001466 case Success:
1467 break;
1468
1469 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001470 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001471
1472 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001473 // FIXME: We could consider reading through to the end of this
1474 // PCH block, skipping subblocks, to see if there are other
1475 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001476
1477 // Clear out any preallocated source location entries, so that
1478 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001479 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001480
1481 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001482 if (StatCache)
1483 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001484
Douglas Gregor92863e42009-04-10 23:10:45 +00001485 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001486 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001487 break;
1488 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001489 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001490 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001491 return Failure;
1492 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001493 break;
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495 }
1496
Douglas Gregore6648fb2009-04-28 20:33:11 +00001497 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001498 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001499 PCHPredefinesBufferID))
1500 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001501
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001502 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001503 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001504 // PCH file is read, so there may be some identifiers that were
1505 // loaded into the IdentifierTable before we intercepted the
1506 // creation of identifiers. Iterate through the list of known
1507 // identifiers and determine whether we have to establish
1508 // preprocessor definitions or top-level identifier declaration
1509 // chains for those identifiers.
1510 //
1511 // We copy the IdentifierInfo pointers to a small vector first,
1512 // since de-serializing declarations or macro definitions can add
1513 // new entries into the identifier table, invalidating the
1514 // iterators.
1515 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1516 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1517 IdEnd = PP->getIdentifierTable().end();
1518 Id != IdEnd; ++Id)
1519 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001520 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001521 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1522 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1523 IdentifierInfo *II = Identifiers[I];
1524 // Look in the on-disk hash table for an entry for
1525 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001526 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001527 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1528 if (Pos == IdTable->end())
1529 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001530
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001531 // Dereferencing the iterator has the effect of populating the
1532 // IdentifierInfo node with the various declarations it needs.
1533 (void)*Pos;
1534 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001535 }
1536
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001537 if (Context)
1538 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001539
Douglas Gregora868bbd2009-04-21 22:25:48 +00001540 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001541}
1542
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001543void PCHReader::InitializeContext(ASTContext &Ctx) {
1544 Context = &Ctx;
1545 assert(Context && "Passed null context!");
1546
1547 assert(PP && "Forgot to set Preprocessor ?");
1548 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1549 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001550 PP->setExternalSource(this);
1551
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001552 // Load the translation unit declaration
1553 ReadDeclRecord(DeclOffsets[0], 0);
1554
1555 // Load the special types.
1556 Context->setBuiltinVaListType(
1557 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1558 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1559 Context->setObjCIdType(GetType(Id));
1560 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1561 Context->setObjCSelType(GetType(Sel));
1562 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1563 Context->setObjCProtoType(GetType(Proto));
1564 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1565 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001566
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001567 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1568 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001570 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1571 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001572 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1573 QualType FileType = GetType(File);
1574 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001575 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001576 Context->setFILEDecl(Typedef->getDecl());
1577 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001578 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001579 assert(Tag && "Invalid FILE type in PCH file");
1580 Context->setFILEDecl(Tag->getDecl());
1581 }
1582 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001583 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1584 QualType Jmp_bufType = GetType(Jmp_buf);
1585 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001586 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001587 Context->setjmp_bufDecl(Typedef->getDecl());
1588 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001589 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001590 assert(Tag && "Invalid jmp_bug type in PCH file");
1591 Context->setjmp_bufDecl(Tag->getDecl());
1592 }
1593 }
1594 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1595 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1596 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001597 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001598 Context->setsigjmp_bufDecl(Typedef->getDecl());
1599 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001600 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001601 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1602 Context->setsigjmp_bufDecl(Tag->getDecl());
1603 }
1604 }
Mike Stump11289f42009-09-09 15:08:12 +00001605 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001606 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1607 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001608 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001609 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1610 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001611#if 0
1612 // FIXME. Accommodate for this in several PCH/Index tests
1613 if (unsigned ObjCSelRedef
1614 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001615 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001616#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001617 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1618 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001619 if (unsigned String
1620 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1621 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001622}
1623
Douglas Gregor45fe0362009-05-12 01:31:05 +00001624/// \brief Retrieve the name of the original source file name
1625/// directly from the PCH file, without actually loading the PCH
1626/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001627std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1628 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001629 // Open the PCH file.
1630 std::string ErrStr;
1631 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1632 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1633 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001634 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001635 return std::string();
1636 }
1637
1638 // Initialize the stream
1639 llvm::BitstreamReader StreamFile;
1640 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001641 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001642 (const unsigned char *)Buffer->getBufferEnd());
1643 Stream.init(StreamFile);
1644
1645 // Sniff for the signature.
1646 if (Stream.Read(8) != 'C' ||
1647 Stream.Read(8) != 'P' ||
1648 Stream.Read(8) != 'C' ||
1649 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001650 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001651 return std::string();
1652 }
1653
1654 RecordData Record;
1655 while (!Stream.AtEndOfStream()) {
1656 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregor45fe0362009-05-12 01:31:05 +00001658 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1659 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001660
Douglas Gregor45fe0362009-05-12 01:31:05 +00001661 // We only know the PCH subblock ID.
1662 switch (BlockID) {
1663 case pch::PCH_BLOCK_ID:
1664 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001665 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001666 return std::string();
1667 }
1668 break;
Mike Stump11289f42009-09-09 15:08:12 +00001669
Douglas Gregor45fe0362009-05-12 01:31:05 +00001670 default:
1671 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001672 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001673 return std::string();
1674 }
1675 break;
1676 }
1677 continue;
1678 }
1679
1680 if (Code == llvm::bitc::END_BLOCK) {
1681 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001682 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001683 return std::string();
1684 }
1685 continue;
1686 }
1687
1688 if (Code == llvm::bitc::DEFINE_ABBREV) {
1689 Stream.ReadAbbrevRecord();
1690 continue;
1691 }
1692
1693 Record.clear();
1694 const char *BlobStart = 0;
1695 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001696 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001697 == pch::ORIGINAL_FILE_NAME)
1698 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001699 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001700
1701 return std::string();
1702}
1703
Douglas Gregor55abb232009-04-10 20:39:37 +00001704/// \brief Parse the record that corresponds to a LangOptions data
1705/// structure.
1706///
1707/// This routine compares the language options used to generate the
1708/// PCH file against the language options set for the current
1709/// compilation. For each option, we classify differences between the
1710/// two compiler states as either "benign" or "important". Benign
1711/// differences don't matter, and we accept them without complaint
1712/// (and without modifying the language options). Differences between
1713/// the states for important options cause the PCH file to be
1714/// unusable, so we emit a warning and return true to indicate that
1715/// there was an error.
1716///
1717/// \returns true if the PCH file is unacceptable, false otherwise.
1718bool PCHReader::ParseLanguageOptions(
1719 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001720 if (Listener) {
1721 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001723 #define PARSE_LANGOPT(Option) \
1724 LangOpts.Option = Record[Idx]; \
1725 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001726
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001727 unsigned Idx = 0;
1728 PARSE_LANGOPT(Trigraphs);
1729 PARSE_LANGOPT(BCPLComment);
1730 PARSE_LANGOPT(DollarIdents);
1731 PARSE_LANGOPT(AsmPreprocessor);
1732 PARSE_LANGOPT(GNUMode);
1733 PARSE_LANGOPT(ImplicitInt);
1734 PARSE_LANGOPT(Digraphs);
1735 PARSE_LANGOPT(HexFloats);
1736 PARSE_LANGOPT(C99);
1737 PARSE_LANGOPT(Microsoft);
1738 PARSE_LANGOPT(CPlusPlus);
1739 PARSE_LANGOPT(CPlusPlus0x);
1740 PARSE_LANGOPT(CXXOperatorNames);
1741 PARSE_LANGOPT(ObjC1);
1742 PARSE_LANGOPT(ObjC2);
1743 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001744 PARSE_LANGOPT(ObjCNonFragileABI2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001745 PARSE_LANGOPT(PascalStrings);
1746 PARSE_LANGOPT(WritableStrings);
1747 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001748 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001749 PARSE_LANGOPT(Exceptions);
1750 PARSE_LANGOPT(NeXTRuntime);
1751 PARSE_LANGOPT(Freestanding);
1752 PARSE_LANGOPT(NoBuiltin);
1753 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001754 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001755 PARSE_LANGOPT(Blocks);
1756 PARSE_LANGOPT(EmitAllDecls);
1757 PARSE_LANGOPT(MathErrno);
1758 PARSE_LANGOPT(OverflowChecking);
1759 PARSE_LANGOPT(HeinousExtensions);
1760 PARSE_LANGOPT(Optimize);
1761 PARSE_LANGOPT(OptimizeSize);
1762 PARSE_LANGOPT(Static);
1763 PARSE_LANGOPT(PICLevel);
1764 PARSE_LANGOPT(GNUInline);
1765 PARSE_LANGOPT(NoInline);
1766 PARSE_LANGOPT(AccessControl);
1767 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001768 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001769 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1770 ++Idx;
1771 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1772 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001773 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1774 Record[Idx]);
1775 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001776 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001777 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00001778 PARSE_LANGOPT(CatchUndefined);
1779 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001780 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001781
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001782 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001783 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001784
1785 return false;
1786}
1787
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001788void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1789 Comments.resize(NumComments);
1790 std::copy(this->Comments, this->Comments + NumComments,
1791 Comments.begin());
1792}
1793
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001794/// \brief Read and return the type at the given offset.
1795///
1796/// This routine actually reads the record corresponding to the type
1797/// at the given offset in the bitstream. It is a helper routine for
1798/// GetType, which deals with reading type IDs.
1799QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001800 // Keep track of where we are in the stream, then jump back there
1801 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001802 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001803
Douglas Gregor1342e842009-07-06 18:54:52 +00001804 // Note that we are loading a type record.
1805 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001806
Douglas Gregor12bfa382009-10-17 00:13:19 +00001807 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001808 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001809 unsigned Code = DeclsCursor.ReadCode();
1810 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001811 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001812 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001813 "Incorrect encoding of extended qualifier type");
1814 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001815 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1816 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001817 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001818
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001819 case pch::TYPE_COMPLEX: {
1820 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1821 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001822 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001823 }
1824
1825 case pch::TYPE_POINTER: {
1826 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1827 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001828 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001829 }
1830
1831 case pch::TYPE_BLOCK_POINTER: {
1832 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1833 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001834 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001835 }
1836
1837 case pch::TYPE_LVALUE_REFERENCE: {
1838 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1839 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001840 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001841 }
1842
1843 case pch::TYPE_RVALUE_REFERENCE: {
1844 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1845 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001846 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001847 }
1848
1849 case pch::TYPE_MEMBER_POINTER: {
1850 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1851 QualType PointeeType = GetType(Record[0]);
1852 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001853 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001854 }
1855
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001856 case pch::TYPE_CONSTANT_ARRAY: {
1857 QualType ElementType = GetType(Record[0]);
1858 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1859 unsigned IndexTypeQuals = Record[2];
1860 unsigned Idx = 3;
1861 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001862 return Context->getConstantArrayType(ElementType, Size,
1863 ASM, IndexTypeQuals);
1864 }
1865
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001866 case pch::TYPE_INCOMPLETE_ARRAY: {
1867 QualType ElementType = GetType(Record[0]);
1868 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1869 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001870 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001871 }
1872
1873 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001874 QualType ElementType = GetType(Record[0]);
1875 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1876 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001877 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1878 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001879 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001880 ASM, IndexTypeQuals,
1881 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001882 }
1883
1884 case pch::TYPE_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001885 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001886 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001887 return QualType();
1888 }
1889
1890 QualType ElementType = GetType(Record[0]);
1891 unsigned NumElements = Record[1];
John Thompson22334602010-02-05 00:12:22 +00001892 bool AltiVec = Record[2];
1893 bool Pixel = Record[3];
1894 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001895 }
1896
1897 case pch::TYPE_EXT_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001898 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001899 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001900 return QualType();
1901 }
1902
1903 QualType ElementType = GetType(Record[0]);
1904 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001905 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001906 }
1907
1908 case pch::TYPE_FUNCTION_NO_PROTO: {
Douglas Gregor8c940862010-01-18 17:14:39 +00001909 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001910 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001911 return QualType();
1912 }
1913 QualType ResultType = GetType(Record[0]);
Douglas Gregor8c940862010-01-18 17:14:39 +00001914 return Context->getFunctionNoProtoType(ResultType, Record[1],
1915 (CallingConv)Record[2]);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001916 }
1917
1918 case pch::TYPE_FUNCTION_PROTO: {
1919 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00001920 bool NoReturn = Record[1];
Douglas Gregor8c940862010-01-18 17:14:39 +00001921 CallingConv CallConv = (CallingConv)Record[2];
1922 unsigned Idx = 3;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001923 unsigned NumParams = Record[Idx++];
1924 llvm::SmallVector<QualType, 16> ParamTypes;
1925 for (unsigned I = 0; I != NumParams; ++I)
1926 ParamTypes.push_back(GetType(Record[Idx++]));
1927 bool isVariadic = Record[Idx++];
1928 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001929 bool hasExceptionSpec = Record[Idx++];
1930 bool hasAnyExceptionSpec = Record[Idx++];
1931 unsigned NumExceptions = Record[Idx++];
1932 llvm::SmallVector<QualType, 2> Exceptions;
1933 for (unsigned I = 0; I != NumExceptions; ++I)
1934 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001935 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001936 isVariadic, Quals, hasExceptionSpec,
1937 hasAnyExceptionSpec, NumExceptions,
Douglas Gregor8c940862010-01-18 17:14:39 +00001938 Exceptions.data(), NoReturn, CallConv);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001939 }
1940
John McCallb96ec562009-12-04 22:46:56 +00001941 case pch::TYPE_UNRESOLVED_USING:
1942 return Context->getTypeDeclType(
1943 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1944
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001945 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001946 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001947 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001948
1949 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001950 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001951
1952 case pch::TYPE_TYPEOF: {
1953 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001954 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001955 return QualType();
1956 }
1957 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001958 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Anders Carlsson81df7b82009-06-24 19:06:50 +00001961 case pch::TYPE_DECLTYPE:
1962 return Context->getDecltypeType(ReadTypeExpr());
1963
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001964 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001965 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001966 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001967
Douglas Gregor1daeb692009-04-13 18:14:40 +00001968 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001969 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001970 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001971
John McCallfcc33b02009-09-05 00:15:47 +00001972 case pch::TYPE_ELABORATED: {
1973 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1974 unsigned Tag = Record[1];
1975 return Context->getElaboratedType(GetType(Record[0]),
1976 (ElaboratedType::TagKind) Tag);
1977 }
1978
Steve Naroffc277ad12009-07-18 15:33:26 +00001979 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001980 unsigned Idx = 0;
1981 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1982 unsigned NumProtos = Record[Idx++];
1983 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1984 for (unsigned I = 0; I != NumProtos; ++I)
1985 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001986 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001987 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001988
Steve Narofffb4330f2009-06-17 22:40:22 +00001989 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001990 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001991 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001992 unsigned NumProtos = Record[Idx++];
1993 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1994 for (unsigned I = 0; I != NumProtos; ++I)
1995 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001996 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001997 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00001998
John McCallcebee162009-10-18 09:09:24 +00001999 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2000 unsigned Idx = 0;
2001 QualType Parm = GetType(Record[Idx++]);
2002 QualType Replacement = GetType(Record[Idx++]);
2003 return
2004 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2005 Replacement);
2006 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002007 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002008 // Suppress a GCC warning
2009 return QualType();
2010}
2011
John McCall8f115c62009-10-16 21:56:05 +00002012namespace {
2013
2014class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2015 PCHReader &Reader;
2016 const PCHReader::RecordData &Record;
2017 unsigned &Idx;
2018
2019public:
2020 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2021 unsigned &Idx)
2022 : Reader(Reader), Record(Record), Idx(Idx) { }
2023
John McCall17001972009-10-18 01:05:36 +00002024 // We want compile-time assurance that we've enumerated all of
2025 // these, so unfortunately we have to declare them first, then
2026 // define them out-of-line.
2027#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002028#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002029 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002030#include "clang/AST/TypeLocNodes.def"
2031
John McCall17001972009-10-18 01:05:36 +00002032 void VisitFunctionTypeLoc(FunctionTypeLoc);
2033 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002034};
2035
2036}
2037
John McCall17001972009-10-18 01:05:36 +00002038void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002039 // nothing to do
2040}
John McCall17001972009-10-18 01:05:36 +00002041void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002042 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2043 if (TL.needsExtraLocalData()) {
2044 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2045 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2046 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2047 TL.setModeAttr(Record[Idx++]);
2048 }
John McCall8f115c62009-10-16 21:56:05 +00002049}
John McCall17001972009-10-18 01:05:36 +00002050void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2051 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002052}
John McCall17001972009-10-18 01:05:36 +00002053void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2054 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002055}
John McCall17001972009-10-18 01:05:36 +00002056void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2057 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002058}
John McCall17001972009-10-18 01:05:36 +00002059void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2060 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002061}
John McCall17001972009-10-18 01:05:36 +00002062void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2063 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002064}
John McCall17001972009-10-18 01:05:36 +00002065void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2066 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002067}
John McCall17001972009-10-18 01:05:36 +00002068void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2069 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002071 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002072 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002073 else
John McCall17001972009-10-18 01:05:36 +00002074 TL.setSizeExpr(0);
2075}
2076void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2077 VisitArrayTypeLoc(TL);
2078}
2079void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2080 VisitArrayTypeLoc(TL);
2081}
2082void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2083 VisitArrayTypeLoc(TL);
2084}
2085void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2086 DependentSizedArrayTypeLoc TL) {
2087 VisitArrayTypeLoc(TL);
2088}
2089void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2090 DependentSizedExtVectorTypeLoc TL) {
2091 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092}
2093void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2094 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095}
2096void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2097 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098}
2099void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2100 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2102 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002103 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002104 }
2105}
2106void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2107 VisitFunctionTypeLoc(TL);
2108}
2109void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2110 VisitFunctionTypeLoc(TL);
2111}
John McCallb96ec562009-12-04 22:46:56 +00002112void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2113 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2114}
John McCall17001972009-10-18 01:05:36 +00002115void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2116 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2117}
2118void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002119 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2120 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002122}
2123void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002124 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2125 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2126 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002128}
2129void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2130 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2131}
2132void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2133 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2134}
2135void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2136 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2137}
2138void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2139 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2140}
2141void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2142 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2143}
John McCallcebee162009-10-18 09:09:24 +00002144void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2145 SubstTemplateTypeParmTypeLoc TL) {
2146 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2147}
John McCall17001972009-10-18 01:05:36 +00002148void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2149 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002150 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2151 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2152 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2153 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2154 TL.setArgLocInfo(i,
2155 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2156 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002157}
2158void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2159 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2160}
2161void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2162 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2163}
2164void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2165 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002166 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2167 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2168 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2169 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002170}
John McCallfc93cf92009-10-22 22:37:11 +00002171void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2172 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2173 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2174 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2175 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2176 TL.setHasProtocolsAsWritten(Record[Idx++]);
2177 if (TL.hasProtocolsAsWritten())
2178 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2179 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2180}
John McCall8f115c62009-10-16 21:56:05 +00002181
John McCallbcd03502009-12-07 02:54:59 +00002182TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002183 unsigned &Idx) {
2184 QualType InfoTy = GetType(Record[Idx++]);
2185 if (InfoTy.isNull())
2186 return 0;
2187
John McCallbcd03502009-12-07 02:54:59 +00002188 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002189 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002190 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002191 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002192 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002193}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002194
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002195QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002196 unsigned FastQuals = ID & Qualifiers::FastMask;
2197 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002198
2199 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2200 QualType T;
2201 switch ((pch::PredefinedTypeIDs)Index) {
2202 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002203 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2204 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002205
2206 case pch::PREDEF_TYPE_CHAR_U_ID:
2207 case pch::PREDEF_TYPE_CHAR_S_ID:
2208 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002209 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002210 break;
2211
Chris Lattner8575daa2009-04-27 21:45:14 +00002212 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2213 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2214 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2215 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2216 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002217 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002218 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2219 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2220 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2221 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2222 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2223 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002224 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002225 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2226 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2227 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2228 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2229 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002230 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002231 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2232 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002233 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2234 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002235 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002236 }
2237
2238 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002239 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002240 }
2241
2242 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002243 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002244 if (TypesLoaded[Index].isNull())
2245 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002246
John McCall8ccfcb52009-09-24 19:53:00 +00002247 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002248}
2249
John McCall0ad16662009-10-29 08:12:44 +00002250TemplateArgumentLocInfo
2251PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2252 const RecordData &Record,
2253 unsigned &Index) {
2254 switch (Kind) {
2255 case TemplateArgument::Expression:
2256 return ReadDeclExpr();
2257 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002258 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002259 case TemplateArgument::Template: {
2260 SourceLocation
2261 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2262 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2263 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2264 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2265 TemplateNameLoc);
2266 }
John McCall0ad16662009-10-29 08:12:44 +00002267 case TemplateArgument::Null:
2268 case TemplateArgument::Integral:
2269 case TemplateArgument::Declaration:
2270 case TemplateArgument::Pack:
2271 return TemplateArgumentLocInfo();
2272 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002273 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002274 return TemplateArgumentLocInfo();
2275}
2276
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002277Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002278 if (ID == 0)
2279 return 0;
2280
Douglas Gregor745ed142009-04-25 18:35:21 +00002281 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002282 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002283 return 0;
2284 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002285
Douglas Gregor745ed142009-04-25 18:35:21 +00002286 unsigned Index = ID - 1;
2287 if (!DeclsLoaded[Index])
2288 ReadDeclRecord(DeclOffsets[Index], Index);
2289
2290 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002291}
2292
Chris Lattner9c28af02009-04-27 05:46:25 +00002293/// \brief Resolve the offset of a statement into a statement.
2294///
2295/// This operation will read a new statement from the external
2296/// source each time it is called, and is meant to be used via a
2297/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2298Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002299 // Since we know tha this statement is part of a decl, make sure to use the
2300 // decl cursor to read it.
2301 DeclsCursor.JumpToBit(Offset);
2302 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002303}
2304
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002305bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002306 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002307 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002308 "DeclContext has no lexical decls in storage");
2309 uint64_t Offset = DeclContextOffsets[DC].first;
2310 assert(Offset && "DeclContext has no lexical decls in storage");
2311
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002312 // Keep track of where we are in the stream, then jump back there
2313 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002314 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002315
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002316 // Load the record containing all of the declarations lexically in
2317 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002318 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002319 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002320 unsigned Code = DeclsCursor.ReadCode();
2321 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002322 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002323 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2324
2325 // Load all of the declaration IDs
2326 Decls.clear();
2327 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002328 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002329 return false;
2330}
2331
2332bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002333 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002334 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002335 "DeclContext has no visible decls in storage");
2336 uint64_t Offset = DeclContextOffsets[DC].second;
2337 assert(Offset && "DeclContext has no visible decls in storage");
2338
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002339 // Keep track of where we are in the stream, then jump back there
2340 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002341 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002342
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002343 // Load the record containing all of the declarations visible in
2344 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002345 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002346 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002347 unsigned Code = DeclsCursor.ReadCode();
2348 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002349 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002350 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2351 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002352 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002353
2354 Decls.clear();
2355
2356 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002357 while (Idx < Record.size()) {
2358 Decls.push_back(VisibleDeclaration());
2359 Decls.back().Name = ReadDeclarationName(Record, Idx);
2360
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002361 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002362 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002363 LoadedDecls.reserve(Size);
2364 for (unsigned I = 0; I < Size; ++I)
2365 LoadedDecls.push_back(Record[Idx++]);
2366 }
2367
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002368 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002369 return false;
2370}
2371
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002372void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002373 this->Consumer = Consumer;
2374
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002375 if (!Consumer)
2376 return;
2377
2378 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002379 // Force deserialization of this decl, which will cause it to be passed to
2380 // the consumer (or queued).
2381 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002382 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002383
2384 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2385 DeclGroupRef DG(InterestingDecls[I]);
2386 Consumer->HandleTopLevelDecl(DG);
2387 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002388}
2389
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002390void PCHReader::PrintStats() {
2391 std::fprintf(stderr, "*** PCH Statistics:\n");
2392
Mike Stump11289f42009-09-09 15:08:12 +00002393 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002394 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002395 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002396 unsigned NumDeclsLoaded
2397 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2398 (Decl *)0);
2399 unsigned NumIdentifiersLoaded
2400 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2401 IdentifiersLoaded.end(),
2402 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002403 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002404 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2405 SelectorsLoaded.end(),
2406 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002407
Douglas Gregorc5046832009-04-27 18:38:38 +00002408 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2409 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002410 if (TotalNumSLocEntries)
2411 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2412 NumSLocEntriesRead, TotalNumSLocEntries,
2413 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002414 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002415 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002416 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2417 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2418 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002419 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002420 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2421 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002422 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002423 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002424 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2425 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002426 if (TotalNumSelectors)
2427 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2428 NumSelectorsLoaded, TotalNumSelectors,
2429 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2430 if (TotalNumStatements)
2431 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2432 NumStatementsRead, TotalNumStatements,
2433 ((float)NumStatementsRead/TotalNumStatements * 100));
2434 if (TotalNumMacros)
2435 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2436 NumMacrosRead, TotalNumMacros,
2437 ((float)NumMacrosRead/TotalNumMacros * 100));
2438 if (TotalLexicalDeclContexts)
2439 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2440 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2441 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2442 * 100));
2443 if (TotalVisibleDeclContexts)
2444 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2445 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2446 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2447 * 100));
2448 if (TotalSelectorsInMethodPool) {
2449 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2450 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2451 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2452 * 100));
2453 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2454 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002455 std::fprintf(stderr, "\n");
2456}
2457
Douglas Gregora868bbd2009-04-21 22:25:48 +00002458void PCHReader::InitializeSema(Sema &S) {
2459 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002460 S.ExternalSource = this;
2461
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002462 // Makes sure any declarations that were deserialized "too early"
2463 // still get added to the identifier's declaration chains.
2464 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2465 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2466 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002467 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002468 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002469
2470 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002471 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002472 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2473 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002474 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002475 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002476
2477 // If there were any locally-scoped external declarations,
2478 // deserialize them and add them to Sema's table of locally-scoped
2479 // external declarations.
2480 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2481 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2482 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2483 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002484
2485 // If there were any ext_vector type declarations, deserialize them
2486 // and add them to Sema's vector of such declarations.
2487 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2488 SemaObj->ExtVectorDecls.push_back(
2489 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002490}
2491
2492IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2493 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002494 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002495 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2496 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2497 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2498 if (Pos == IdTable->end())
2499 return 0;
2500
2501 // Dereferencing the iterator has the effect of building the
2502 // IdentifierInfo node and populating it with the various
2503 // declarations it needs.
2504 return *Pos;
2505}
2506
Mike Stump11289f42009-09-09 15:08:12 +00002507std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002508PCHReader::ReadMethodPool(Selector Sel) {
2509 if (!MethodPoolLookupTable)
2510 return std::pair<ObjCMethodList, ObjCMethodList>();
2511
2512 // Try to find this selector within our on-disk hash table.
2513 PCHMethodPoolLookupTable *PoolTable
2514 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2515 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002516 if (Pos == PoolTable->end()) {
2517 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002518 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002519 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002520
Douglas Gregor95c13f52009-04-25 17:48:32 +00002521 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002522 return *Pos;
2523}
2524
Douglas Gregor0e149972009-04-25 19:10:14 +00002525void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002526 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002527 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002528 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002529}
2530
Douglas Gregor1342e842009-07-06 18:54:52 +00002531/// \brief Set the globally-visible declarations associated with the given
2532/// identifier.
2533///
2534/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002535/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002536/// them.
2537///
2538/// \param II an IdentifierInfo that refers to one or more globally-visible
2539/// declarations.
2540///
2541/// \param DeclIDs the set of declaration IDs with the name @p II that are
2542/// visible at global scope.
2543///
2544/// \param Nonrecursive should be true to indicate that the caller knows that
2545/// this call is non-recursive, and therefore the globally-visible declarations
2546/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002547void
2548PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002549 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2550 bool Nonrecursive) {
2551 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2552 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2553 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2554 PII.II = II;
2555 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2556 PII.DeclIDs.push_back(DeclIDs[I]);
2557 return;
2558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor1342e842009-07-06 18:54:52 +00002560 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2561 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2562 if (SemaObj) {
2563 // Introduce this declaration into the translation-unit scope
2564 // and add it to the declaration chain for this identifier, so
2565 // that (unqualified) name lookup will find it.
2566 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2567 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2568 } else {
2569 // Queue this declaration so that it will be added to the
2570 // translation unit scope and identifier's declaration chain
2571 // once a Sema object is known.
2572 PreloadedDecls.push_back(D);
2573 }
2574 }
2575}
2576
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002577IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002578 if (ID == 0)
2579 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregor0e149972009-04-25 19:10:14 +00002581 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002582 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002583 return 0;
2584 }
Mike Stump11289f42009-09-09 15:08:12 +00002585
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002586 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002587 if (!IdentifiersLoaded[ID - 1]) {
2588 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002589 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002590
Douglas Gregorab4df582009-04-28 20:01:51 +00002591 // All of the strings in the PCH file are preceded by a 16-bit
2592 // length. Extract that 16-bit length to avoid having to execute
2593 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002594 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2595 // unsigned integers. This is important to avoid integer overflow when
2596 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002597 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002598 unsigned StrLen = (((unsigned) StrLenPtr[0])
2599 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002600 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002601 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002602 }
Mike Stump11289f42009-09-09 15:08:12 +00002603
Douglas Gregor0e149972009-04-25 19:10:14 +00002604 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002605}
2606
Douglas Gregor258ae542009-04-27 06:38:32 +00002607void PCHReader::ReadSLocEntry(unsigned ID) {
2608 ReadSLocEntryRecord(ID);
2609}
2610
Steve Naroff2ddea052009-04-23 10:39:46 +00002611Selector PCHReader::DecodeSelector(unsigned ID) {
2612 if (ID == 0)
2613 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002614
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002615 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002616 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002617
2618 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002619 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002620 return Selector();
2621 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002622
2623 unsigned Index = ID - 1;
2624 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2625 // Load this selector from the selector table.
2626 // FIXME: endianness portability issues with SelectorOffsets table
2627 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002628 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002629 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2630 }
2631
2632 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002633}
2634
Mike Stump11289f42009-09-09 15:08:12 +00002635DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002636PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2637 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2638 switch (Kind) {
2639 case DeclarationName::Identifier:
2640 return DeclarationName(GetIdentifierInfo(Record, Idx));
2641
2642 case DeclarationName::ObjCZeroArgSelector:
2643 case DeclarationName::ObjCOneArgSelector:
2644 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002645 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002646
2647 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002648 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002649 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002650
2651 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002652 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002653 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002654
2655 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002656 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002657 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002658
2659 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002660 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002661 (OverloadedOperatorKind)Record[Idx++]);
2662
Alexis Hunt3d221f22009-11-29 07:34:05 +00002663 case DeclarationName::CXXLiteralOperatorName:
2664 return Context->DeclarationNames.getCXXLiteralOperatorName(
2665 GetIdentifierInfo(Record, Idx));
2666
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002667 case DeclarationName::CXXUsingDirective:
2668 return DeclarationName::getUsingDirectiveName();
2669 }
2670
2671 // Required to silence GCC warning
2672 return DeclarationName();
2673}
Douglas Gregor55abb232009-04-10 20:39:37 +00002674
Douglas Gregor1daeb692009-04-13 18:14:40 +00002675/// \brief Read an integral value
2676llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2677 unsigned BitWidth = Record[Idx++];
2678 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2679 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2680 Idx += NumWords;
2681 return Result;
2682}
2683
2684/// \brief Read a signed integral value
2685llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2686 bool isUnsigned = Record[Idx++];
2687 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2688}
2689
Douglas Gregore0a3a512009-04-14 21:55:33 +00002690/// \brief Read a floating-point value
2691llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002692 return llvm::APFloat(ReadAPInt(Record, Idx));
2693}
2694
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002695// \brief Read a string
2696std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2697 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002698 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002699 Idx += Len;
2700 return Result;
2701}
2702
Douglas Gregor55abb232009-04-10 20:39:37 +00002703DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002704 return Diag(SourceLocation(), DiagID);
2705}
2706
2707DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002708 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002709}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002710
Douglas Gregora868bbd2009-04-21 22:25:48 +00002711/// \brief Retrieve the identifier table associated with the
2712/// preprocessor.
2713IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002714 assert(PP && "Forgot to set Preprocessor ?");
2715 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002716}
2717
Douglas Gregora9af1d12009-04-17 00:04:06 +00002718/// \brief Record that the given ID maps to the given switch-case
2719/// statement.
2720void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2721 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2722 SwitchCaseStmts[ID] = SC;
2723}
2724
2725/// \brief Retrieve the switch-case statement with the given ID.
2726SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2727 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2728 return SwitchCaseStmts[ID];
2729}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002730
2731/// \brief Record that the given label statement has been
2732/// deserialized and has the given ID.
2733void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002734 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002735 "Deserialized label twice");
2736 LabelStmts[ID] = S;
2737
2738 // If we've already seen any goto statements that point to this
2739 // label, resolve them now.
2740 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2741 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2742 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2743 Goto->second->setLabel(S);
2744 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002745
2746 // If we've already seen any address-label statements that point to
2747 // this label, resolve them now.
2748 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002749 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002750 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002751 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002752 AddrLabel != AddrLabels.second; ++AddrLabel)
2753 AddrLabel->second->setLabel(S);
2754 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002755}
2756
2757/// \brief Set the label of the given statement to the label
2758/// identified by ID.
2759///
2760/// Depending on the order in which the label and other statements
2761/// referencing that label occur, this operation may complete
2762/// immediately (updating the statement) or it may queue the
2763/// statement to be back-patched later.
2764void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2765 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2766 if (Label != LabelStmts.end()) {
2767 // We've already seen this label, so set the label of the goto and
2768 // we're done.
2769 S->setLabel(Label->second);
2770 } else {
2771 // We haven't seen this label yet, so add this goto to the set of
2772 // unresolved goto statements.
2773 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2774 }
2775}
Douglas Gregor779d8652009-04-17 18:58:21 +00002776
2777/// \brief Set the label of the given expression to the label
2778/// identified by ID.
2779///
2780/// Depending on the order in which the label and other statements
2781/// referencing that label occur, this operation may complete
2782/// immediately (updating the statement) or it may queue the
2783/// statement to be back-patched later.
2784void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2785 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2786 if (Label != LabelStmts.end()) {
2787 // We've already seen this label, so set the label of the
2788 // label-address expression and we're done.
2789 S->setLabel(Label->second);
2790 } else {
2791 // We haven't seen this label yet, so add this label-address
2792 // expression to the set of unresolved label-address expressions.
2793 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2794 }
2795}
Douglas Gregor1342e842009-07-06 18:54:52 +00002796
2797
Mike Stump11289f42009-09-09 15:08:12 +00002798PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002799 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2800 Reader.CurrentlyLoadingTypeOrDecl = this;
2801}
2802
2803PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2804 if (!Parent) {
2805 // If any identifiers with corresponding top-level declarations have
2806 // been loaded, load those declarations now.
2807 while (!Reader.PendingIdentifierInfos.empty()) {
2808 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2809 Reader.PendingIdentifierInfos.front().DeclIDs,
2810 true);
2811 Reader.PendingIdentifierInfos.pop_front();
2812 }
2813 }
2814
Mike Stump11289f42009-09-09 15:08:12 +00002815 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002816}