blob: 2a22132ea844138aaf60dd97259b7d9be2af16a2 [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);
Daniel Dunbar925152c2010-02-10 18:48:44 +000082 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
84 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
85 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000086 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000087 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000088 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000089 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
90 PARSE_LANGOPT_BENIGN(EmitAllDecls);
91 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
92 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000093 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000094 diag::warn_pch_heinous_extensions);
95 // FIXME: Most of the options below are benign if the macro wasn't
96 // used. Unfortunately, this means that a PCH compiled without
97 // optimization can't be used with optimization turned on, even
98 // though the only thing that changes is whether __OPTIMIZE__ was
99 // defined... but if __OPTIMIZE__ never showed up in the header, it
100 // doesn't matter. We could consider making this some special kind
101 // of check.
102 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
103 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
104 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
105 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
106 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
107 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
108 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
109 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000110 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000111 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000112 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000113 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
114 return true;
115 }
116 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000117 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
118 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000119 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000120 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000121 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000123#undef PARSE_LANGOPT_IRRELEVANT
124#undef PARSE_LANGOPT_BENIGN
125
126 return false;
127}
128
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000129bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
130 if (Triple == PP.getTargetInfo().getTriple().str())
131 return false;
132
133 Reader.Diag(diag::warn_pch_target_triple)
134 << Triple << PP.getTargetInfo().getTriple().str();
135 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000136}
137
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000138bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000139 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000140 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000141 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000142 // We are in the context of an implicit include, so the predefines buffer will
143 // have a #include entry for the PCH file itself (as normalized by the
144 // preprocessor initialization). Find it and skip over it in the checking
145 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000146 llvm::SmallString<256> PCHInclude;
147 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000148 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000149 PCHInclude += "\"\n";
150 std::pair<llvm::StringRef,llvm::StringRef> Split =
151 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
152 llvm::StringRef Left = Split.first, Right = Split.second;
153 assert(Left != PP.getPredefines() && "Missing PCH include entry!");
154
155 // If the predefines is equal to the joined left and right halves, we're done!
156 if (Left.size() + Right.size() == PCHPredef.size() &&
157 PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000158 return false;
159
160 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000161
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000162 // The predefines buffers are different. Determine what the differences are,
163 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000164 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
165 PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
166
167 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
168 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
169 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000170
Daniel Dunbar499baed2009-11-11 05:26:28 +0000171 // Sort both sets of predefined buffer lines, since we allow some extra
172 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000173 std::sort(CmdLineLines.begin(), CmdLineLines.end());
174 std::sort(PCHLines.begin(), PCHLines.end());
175
Daniel Dunbar499baed2009-11-11 05:26:28 +0000176 // Determine which predefines that were used to build the PCH file are missing
177 // from the command line.
178 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000179 std::set_difference(PCHLines.begin(), PCHLines.end(),
180 CmdLineLines.begin(), CmdLineLines.end(),
181 std::back_inserter(MissingPredefines));
182
183 bool MissingDefines = false;
184 bool ConflictingDefines = false;
185 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000186 llvm::StringRef Missing = MissingPredefines[I];
187 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000188 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
189 return true;
190 }
Mike Stump11289f42009-09-09 15:08:12 +0000191
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000192 // This is a macro definition. Determine the name of the macro we're
193 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000194 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000195 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000196 = Missing.find_first_of("( \n\r", StartOfMacroName);
197 assert(EndOfMacroName != std::string::npos &&
198 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000199 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000200
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000201 // Determine whether this macro was given a different definition on the
202 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000203 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000204 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000205 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000206 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
207 MacroDefStart);
208 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000209 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000210 // Different macro; we're done.
211 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000212 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000213 }
Mike Stump11289f42009-09-09 15:08:12 +0000214
215 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000216 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000217 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000218 (*ConflictPos)[MacroDefLen] != '(')
219 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000220
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000221 // We found a conflicting macro definition.
222 break;
223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000225 if (ConflictPos != CmdLineLines.end()) {
226 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
227 << MacroName;
228
229 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000230 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
231 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
232 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
233 .getFileLocWithOffset(Offset);
234 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000235
236 ConflictingDefines = true;
237 continue;
238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000240 // If the macro doesn't conflict, then we'll just pick up the macro
241 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000242 if (ConflictingDefines)
243 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000244
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000245 if (!MissingDefines) {
246 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
247 MissingDefines = true;
248 }
249
250 // Show the definition of this macro within the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000251 llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
252 assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
253 SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000254 .getFileLocWithOffset(Offset);
255 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000258 if (ConflictingDefines)
259 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000261 // Determine what predefines were introduced based on command-line
262 // parameters that were not present when building the PCH
263 // file. Extra #defines are okay, so long as the identifiers being
264 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000265 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000266 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
267 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000268 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000269 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000270 llvm::StringRef &Extra = ExtraPredefines[I];
271 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000272 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
273 return true;
274 }
275
276 // This is an extra macro definition. Determine the name of the
277 // macro we're defining.
278 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000279 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000280 = Extra.find_first_of("( \n\r", StartOfMacroName);
281 assert(EndOfMacroName != std::string::npos &&
282 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000283 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000284
285 // Check whether this name was used somewhere in the PCH file. If
286 // so, defining it as a macro could change behavior, so we reject
287 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000288 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000289 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000290 return true;
291 }
292
293 // Add this definition to the suggested predefines buffer.
294 SuggestedPredefines += Extra;
295 SuggestedPredefines += '\n';
296 }
297
298 // If we get here, it's because the predefines buffer had compatible
299 // contents. Accept the PCH file.
300 return false;
301}
302
303void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
304 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
305}
306
307void PCHValidator::ReadCounter(unsigned Value) {
308 PP.setCounterValue(Value);
309}
310
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000312// PCH reader implementation
313//===----------------------------------------------------------------------===//
314
Mike Stump11289f42009-09-09 15:08:12 +0000315PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
316 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000317 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
318 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000319 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320 IdentifierTableData(0), IdentifierLookupTable(0),
321 IdentifierOffsets(0),
322 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
323 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000324 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000325 NumStatHits(0), NumStatMisses(0),
326 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000327 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000328 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000329 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000330 RelocatablePCH = false;
331}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332
333PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000334 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000335 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000336 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000337 IdentifierTableData(0), IdentifierLookupTable(0),
338 IdentifierOffsets(0),
339 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
340 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000341 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000342 NumStatHits(0), NumStatMisses(0),
343 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000344 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000345 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000346 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000347 RelocatablePCH = false;
348}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000349
350PCHReader::~PCHReader() {}
351
Chris Lattner1de76db2009-04-27 05:58:23 +0000352Expr *PCHReader::ReadDeclExpr() {
353 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
354}
355
356Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000357 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000358}
359
360
Douglas Gregora868bbd2009-04-21 22:25:48 +0000361namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000362class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000363 PCHReader &Reader;
364
365public:
366 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
367
368 typedef Selector external_key_type;
369 typedef external_key_type internal_key_type;
370
371 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000372
Douglas Gregorc78d3462009-04-24 21:10:55 +0000373 static bool EqualKey(const internal_key_type& a,
374 const internal_key_type& b) {
375 return a == b;
376 }
Mike Stump11289f42009-09-09 15:08:12 +0000377
Douglas Gregorc78d3462009-04-24 21:10:55 +0000378 static unsigned ComputeHash(Selector Sel) {
379 unsigned N = Sel.getNumArgs();
380 if (N == 0)
381 ++N;
382 unsigned R = 5381;
383 for (unsigned I = 0; I != N; ++I)
384 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000385 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000386 return R;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Douglas Gregorc78d3462009-04-24 21:10:55 +0000389 // This hopefully will just get inlined and removed by the optimizer.
390 static const internal_key_type&
391 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregorc78d3462009-04-24 21:10:55 +0000393 static std::pair<unsigned, unsigned>
394 ReadKeyDataLength(const unsigned char*& d) {
395 using namespace clang::io;
396 unsigned KeyLen = ReadUnalignedLE16(d);
397 unsigned DataLen = ReadUnalignedLE16(d);
398 return std::make_pair(KeyLen, DataLen);
399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Douglas Gregor95c13f52009-04-25 17:48:32 +0000401 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000402 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000403 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000404 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000405 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000406 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
407 if (N == 0)
408 return SelTable.getNullarySelector(FirstII);
409 else if (N == 1)
410 return SelTable.getUnarySelector(FirstII);
411
412 llvm::SmallVector<IdentifierInfo *, 16> Args;
413 Args.push_back(FirstII);
414 for (unsigned I = 1; I != N; ++I)
415 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
416
Douglas Gregor038c3382009-05-22 22:45:36 +0000417 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Douglas Gregorc78d3462009-04-24 21:10:55 +0000420 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
421 using namespace clang::io;
422 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
423 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
424
425 data_type Result;
426
427 // Load instance methods
428 ObjCMethodList *Prev = 0;
429 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000430 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000431 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
432 if (!Result.first.Method) {
433 // This is the first method, which is the easy case.
434 Result.first.Method = Method;
435 Prev = &Result.first;
436 continue;
437 }
438
Ted Kremenekda4abf12010-02-11 00:53:01 +0000439 ObjCMethodList *Mem =
440 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
441 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000442 Prev = Prev->Next;
443 }
444
445 // Load factory methods
446 Prev = 0;
447 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000448 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000449 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
450 if (!Result.second.Method) {
451 // This is the first method, which is the easy case.
452 Result.second.Method = Method;
453 Prev = &Result.second;
454 continue;
455 }
456
Ted Kremenekda4abf12010-02-11 00:53:01 +0000457 ObjCMethodList *Mem =
458 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
459 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000460 Prev = Prev->Next;
461 }
462
463 return Result;
464 }
465};
Mike Stump11289f42009-09-09 15:08:12 +0000466
467} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000468
469/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000470typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000471 PCHMethodPoolLookupTable;
472
473namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000474class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000475 PCHReader &Reader;
476
477 // If we know the IdentifierInfo in advance, it is here and we will
478 // not build a new one. Used when deserializing information about an
479 // identifier that was constructed before the PCH file was read.
480 IdentifierInfo *KnownII;
481
482public:
483 typedef IdentifierInfo * data_type;
484
485 typedef const std::pair<const char*, unsigned> external_key_type;
486
487 typedef external_key_type internal_key_type;
488
Mike Stump11289f42009-09-09 15:08:12 +0000489 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000490 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregora868bbd2009-04-21 22:25:48 +0000492 static bool EqualKey(const internal_key_type& a,
493 const internal_key_type& b) {
494 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
495 : false;
496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
Douglas Gregora868bbd2009-04-21 22:25:48 +0000498 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000499 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Douglas Gregora868bbd2009-04-21 22:25:48 +0000502 // This hopefully will just get inlined and removed by the optimizer.
503 static const internal_key_type&
504 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregora868bbd2009-04-21 22:25:48 +0000506 static std::pair<unsigned, unsigned>
507 ReadKeyDataLength(const unsigned char*& d) {
508 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000509 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000510 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000511 return std::make_pair(KeyLen, DataLen);
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Douglas Gregora868bbd2009-04-21 22:25:48 +0000514 static std::pair<const char*, unsigned>
515 ReadKey(const unsigned char* d, unsigned n) {
516 assert(n >= 2 && d[n-1] == '\0');
517 return std::make_pair((const char*) d, n-1);
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
520 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000521 const unsigned char* d,
522 unsigned DataLen) {
523 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000524 pch::IdentID ID = ReadUnalignedLE32(d);
525 bool IsInteresting = ID & 0x01;
526
527 // Wipe out the "is interesting" bit.
528 ID = ID >> 1;
529
530 if (!IsInteresting) {
531 // For unintersting identifiers, just build the IdentifierInfo
532 // and associate it with the persistent ID.
533 IdentifierInfo *II = KnownII;
534 if (!II)
535 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
536 k.first, k.first + k.second);
537 Reader.SetIdentifierInfo(ID, II);
538 return II;
539 }
540
Douglas Gregorb9256522009-04-28 21:32:13 +0000541 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000542 bool CPlusPlusOperatorKeyword = Bits & 0x01;
543 Bits >>= 1;
544 bool Poisoned = Bits & 0x01;
545 Bits >>= 1;
546 bool ExtensionToken = Bits & 0x01;
547 Bits >>= 1;
548 bool hasMacroDefinition = Bits & 0x01;
549 Bits >>= 1;
550 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
551 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000553 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000554 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000555
556 // Build the IdentifierInfo itself and link the identifier ID with
557 // the new IdentifierInfo.
558 IdentifierInfo *II = KnownII;
559 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000560 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
561 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000562 Reader.SetIdentifierInfo(ID, II);
563
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000564 // Set or check the various bits in the IdentifierInfo structure.
565 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000566 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000567 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000568 "Incorrect extension token flag");
569 (void)ExtensionToken;
570 II->setIsPoisoned(Poisoned);
571 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
572 "Incorrect C++ operator keyword flag");
573 (void)CPlusPlusOperatorKeyword;
574
Douglas Gregorc3366a52009-04-21 23:56:24 +0000575 // If this identifier is a macro, deserialize the macro
576 // definition.
577 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000578 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000579 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000580 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000581 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000582
583 // Read all of the declarations visible at global scope with this
584 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000585 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000586 if (DataLen > 0) {
587 llvm::SmallVector<uint32_t, 4> DeclIDs;
588 for (; DataLen > 0; DataLen -= 4)
589 DeclIDs.push_back(ReadUnalignedLE32(d));
590 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000591 }
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregora868bbd2009-04-21 22:25:48 +0000593 return II;
594 }
595};
Mike Stump11289f42009-09-09 15:08:12 +0000596
597} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000598
599/// \brief The on-disk hash table used to contain information about
600/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000601typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000602 PCHIdentifierLookupTable;
603
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000604bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000605 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
606 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000607 return true;
608}
609
Douglas Gregor92863e42009-04-10 23:10:45 +0000610/// \brief Check the contents of the predefines buffer against the
611/// contents of the predefines buffer used to build the PCH file.
612///
613/// The contents of the two predefines buffers should be the same. If
614/// not, then some command-line option changed the preprocessor state
615/// and we must reject the PCH file.
616///
617/// \param PCHPredef The start of the predefines buffer in the PCH
618/// file.
619///
620/// \param PCHPredefLen The length of the predefines buffer in the PCH
621/// file.
622///
623/// \param PCHBufferID The FileID for the PCH predefines buffer.
624///
625/// \returns true if there was a mismatch (in which case the PCH file
626/// should be ignored), or false otherwise.
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000627bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000628 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000629 if (Listener)
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000630 return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000631 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000632 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000633 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000634}
635
Douglas Gregorc5046832009-04-27 18:38:38 +0000636//===----------------------------------------------------------------------===//
637// Source Manager Deserialization
638//===----------------------------------------------------------------------===//
639
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000640/// \brief Read the line table in the source manager block.
641/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000642bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000643 unsigned Idx = 0;
644 LineTableInfo &LineTable = SourceMgr.getLineTable();
645
646 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000647 std::map<int, int> FileIDs;
648 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000649 // Extract the file name
650 unsigned FilenameLen = Record[Idx++];
651 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
652 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000653 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000654 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000655 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000656 }
657
658 // Parse the line entries
659 std::vector<LineEntry> Entries;
660 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000661 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000662
663 // Extract the line entries
664 unsigned NumEntries = Record[Idx++];
665 Entries.clear();
666 Entries.reserve(NumEntries);
667 for (unsigned I = 0; I != NumEntries; ++I) {
668 unsigned FileOffset = Record[Idx++];
669 unsigned LineNo = Record[Idx++];
670 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000671 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000672 = (SrcMgr::CharacteristicKind)Record[Idx++];
673 unsigned IncludeOffset = Record[Idx++];
674 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
675 FileKind, IncludeOffset));
676 }
677 LineTable.AddEntry(FID, Entries);
678 }
679
680 return false;
681}
682
Douglas Gregorc5046832009-04-27 18:38:38 +0000683namespace {
684
Benjamin Kramer16634c22009-11-28 10:07:24 +0000685class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000686public:
687 const bool hasStat;
688 const ino_t ino;
689 const dev_t dev;
690 const mode_t mode;
691 const time_t mtime;
692 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000693
Douglas Gregorc5046832009-04-27 18:38:38 +0000694 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000695 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
696
Douglas Gregorc5046832009-04-27 18:38:38 +0000697 PCHStatData()
698 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
699};
700
Benjamin Kramer16634c22009-11-28 10:07:24 +0000701class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000702 public:
703 typedef const char *external_key_type;
704 typedef const char *internal_key_type;
705
706 typedef PCHStatData data_type;
707
708 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000709 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000710 }
711
712 static internal_key_type GetInternalKey(const char *path) { return path; }
713
714 static bool EqualKey(internal_key_type a, internal_key_type b) {
715 return strcmp(a, b) == 0;
716 }
717
718 static std::pair<unsigned, unsigned>
719 ReadKeyDataLength(const unsigned char*& d) {
720 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
721 unsigned DataLen = (unsigned) *d++;
722 return std::make_pair(KeyLen + 1, DataLen);
723 }
724
725 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
726 return (const char *)d;
727 }
728
729 static data_type ReadData(const internal_key_type, const unsigned char *d,
730 unsigned /*DataLen*/) {
731 using namespace clang::io;
732
733 if (*d++ == 1)
734 return data_type();
735
736 ino_t ino = (ino_t) ReadUnalignedLE32(d);
737 dev_t dev = (dev_t) ReadUnalignedLE32(d);
738 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000739 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000740 off_t size = (off_t) ReadUnalignedLE64(d);
741 return data_type(ino, dev, mode, mtime, size);
742 }
743};
744
745/// \brief stat() cache for precompiled headers.
746///
747/// This cache is very similar to the stat cache used by pretokenized
748/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000749class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000750 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
751 CacheTy *Cache;
752
753 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000754public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000755 PCHStatCache(const unsigned char *Buckets,
756 const unsigned char *Base,
757 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000758 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000759 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
760 Cache = CacheTy::Create(Buckets, Base);
761 }
762
763 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000764
Douglas Gregorc5046832009-04-27 18:38:38 +0000765 int stat(const char *path, struct stat *buf) {
766 // Do the lookup for the file's data in the PCH file.
767 CacheTy::iterator I = Cache->find(path);
768
769 // If we don't get a hit in the PCH file just forward to 'stat'.
770 if (I == Cache->end()) {
771 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000772 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000773 }
Mike Stump11289f42009-09-09 15:08:12 +0000774
Douglas Gregorc5046832009-04-27 18:38:38 +0000775 ++NumStatHits;
776 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregorc5046832009-04-27 18:38:38 +0000778 if (!Data.hasStat)
779 return 1;
780
781 buf->st_ino = Data.ino;
782 buf->st_dev = Data.dev;
783 buf->st_mtime = Data.mtime;
784 buf->st_mode = Data.mode;
785 buf->st_size = Data.size;
786 return 0;
787 }
788};
789} // end anonymous namespace
790
791
Douglas Gregora7f71a92009-04-10 03:52:48 +0000792/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000793PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000794 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000795
796 // Set the source-location entry cursor to the current position in
797 // the stream. This cursor will be used to read the contents of the
798 // source manager block initially, and then lazily read
799 // source-location entries as needed.
800 SLocEntryCursor = Stream;
801
802 // The stream itself is going to skip over the source manager block.
803 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000804 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000805 return Failure;
806 }
807
808 // Enter the source manager block.
809 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000810 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000811 return Failure;
812 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000813
Douglas Gregora7f71a92009-04-10 03:52:48 +0000814 RecordData Record;
815 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000816 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000817 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000818 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000819 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000820 return Failure;
821 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000822 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Douglas Gregora7f71a92009-04-10 03:52:48 +0000825 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
826 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000827 SLocEntryCursor.ReadSubBlockID();
828 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000830 return Failure;
831 }
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 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000836 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000837 continue;
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Douglas Gregora7f71a92009-04-10 03:52:48 +0000840 // Read a record.
841 const char *BlobStart;
842 unsigned BlobLen;
843 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000844 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000845 default: // Default behavior: ignore.
846 break;
847
Chris Lattner184e65d2009-04-14 23:22:57 +0000848 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000849 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000850 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000851 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000852
853 case pch::SM_HEADER_FILE_INFO: {
854 HeaderFileInfo HFI;
855 HFI.isImport = Record[0];
856 HFI.DirInfo = Record[1];
857 HFI.NumIncludes = Record[2];
858 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000859 if (Listener)
860 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000861 break;
862 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000863
864 case pch::SM_SLOC_FILE_ENTRY:
865 case pch::SM_SLOC_BUFFER_ENTRY:
866 case pch::SM_SLOC_INSTANTIATION_ENTRY:
867 // Once we hit one of the source location entries, we're done.
868 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000869 }
870 }
871}
872
Douglas Gregor258ae542009-04-27 06:38:32 +0000873/// \brief Read in the source location entry with the given ID.
874PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
875 if (ID == 0)
876 return Success;
877
878 if (ID > TotalNumSLocEntries) {
879 Error("source location entry ID out-of-range for PCH file");
880 return Failure;
881 }
882
883 ++NumSLocEntriesRead;
884 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
885 unsigned Code = SLocEntryCursor.ReadCode();
886 if (Code == llvm::bitc::END_BLOCK ||
887 Code == llvm::bitc::ENTER_SUBBLOCK ||
888 Code == llvm::bitc::DEFINE_ABBREV) {
889 Error("incorrectly-formatted source location entry in PCH file");
890 return Failure;
891 }
892
Douglas Gregor258ae542009-04-27 06:38:32 +0000893 RecordData Record;
894 const char *BlobStart;
895 unsigned BlobLen;
896 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
897 default:
898 Error("incorrectly-formatted source location entry in PCH file");
899 return Failure;
900
901 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000902 std::string Filename(BlobStart, BlobStart + BlobLen);
903 MaybeAddSystemRootToFilename(Filename);
904 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000905 if (File == 0) {
906 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000907 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000908 ErrorStr += "' referenced by PCH file";
909 Error(ErrorStr.c_str());
910 return Failure;
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregor258ae542009-04-27 06:38:32 +0000913 FileID FID = SourceMgr.createFileID(File,
914 SourceLocation::getFromRawEncoding(Record[1]),
915 (SrcMgr::CharacteristicKind)Record[2],
916 ID, Record[0]);
917 if (Record[3])
918 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
919 .setHasLineDirectives();
920
921 break;
922 }
923
924 case pch::SM_SLOC_BUFFER_ENTRY: {
925 const char *Name = BlobStart;
926 unsigned Offset = Record[0];
927 unsigned Code = SLocEntryCursor.ReadCode();
928 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000929 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000930 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
931 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
932 (void)RecCode;
933 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000934 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000935 BlobStart + BlobLen - 1,
936 Name);
937 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000938
Douglas Gregore6648fb2009-04-28 20:33:11 +0000939 if (strcmp(Name, "<built-in>") == 0) {
940 PCHPredefinesBufferID = BufferID;
941 PCHPredefines = BlobStart;
942 PCHPredefinesLen = BlobLen - 1;
943 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000944
945 break;
946 }
947
948 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000949 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000950 = SourceLocation::getFromRawEncoding(Record[1]);
951 SourceMgr.createInstantiationLoc(SpellingLoc,
952 SourceLocation::getFromRawEncoding(Record[2]),
953 SourceLocation::getFromRawEncoding(Record[3]),
954 Record[4],
955 ID,
956 Record[0]);
957 break;
Mike Stump11289f42009-09-09 15:08:12 +0000958 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000959 }
960
961 return Success;
962}
963
Chris Lattnere78a6be2009-04-27 01:05:14 +0000964/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
965/// specified cursor. Read the abbreviations that are at the top of the block
966/// and then leave the cursor pointing into the block.
967bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
968 unsigned BlockID) {
969 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000970 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000971 return Failure;
972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Chris Lattnere78a6be2009-04-27 01:05:14 +0000974 while (true) {
975 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +0000976
Chris Lattnere78a6be2009-04-27 01:05:14 +0000977 // We expect all abbrevs to be at the start of the block.
978 if (Code != llvm::bitc::DEFINE_ABBREV)
979 return false;
980 Cursor.ReadAbbrevRecord();
981 }
982}
983
Douglas Gregorc3366a52009-04-21 23:56:24 +0000984void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000985 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +0000986
Douglas Gregorc3366a52009-04-21 23:56:24 +0000987 // Keep track of where we are in the stream, then jump back there
988 // after reading this macro.
989 SavedStreamPosition SavedPosition(Stream);
990
991 Stream.JumpToBit(Offset);
992 RecordData Record;
993 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
994 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000995
Douglas Gregorc3366a52009-04-21 23:56:24 +0000996 while (true) {
997 unsigned Code = Stream.ReadCode();
998 switch (Code) {
999 case llvm::bitc::END_BLOCK:
1000 return;
1001
1002 case llvm::bitc::ENTER_SUBBLOCK:
1003 // No known subblocks, always skip them.
1004 Stream.ReadSubBlockID();
1005 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001006 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001007 return;
1008 }
1009 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregorc3366a52009-04-21 23:56:24 +00001011 case llvm::bitc::DEFINE_ABBREV:
1012 Stream.ReadAbbrevRecord();
1013 continue;
1014 default: break;
1015 }
1016
1017 // Read a record.
1018 Record.clear();
1019 pch::PreprocessorRecordTypes RecType =
1020 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1021 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001022 case pch::PP_MACRO_OBJECT_LIKE:
1023 case pch::PP_MACRO_FUNCTION_LIKE: {
1024 // If we already have a macro, that means that we've hit the end
1025 // of the definition of the macro we were looking for. We're
1026 // done.
1027 if (Macro)
1028 return;
1029
1030 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1031 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001032 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001033 return;
1034 }
1035 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1036 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001037
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001038 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001039 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001040
Douglas Gregorc3366a52009-04-21 23:56:24 +00001041 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1042 // Decode function-like macro info.
1043 bool isC99VarArgs = Record[3];
1044 bool isGNUVarArgs = Record[4];
1045 MacroArgs.clear();
1046 unsigned NumArgs = Record[5];
1047 for (unsigned i = 0; i != NumArgs; ++i)
1048 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1049
1050 // Install function-like macro info.
1051 MI->setIsFunctionLike();
1052 if (isC99VarArgs) MI->setIsC99Varargs();
1053 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001054 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001055 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001056 }
1057
1058 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001059 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001060
1061 // Remember that we saw this macro last so that we add the tokens that
1062 // form its body to it.
1063 Macro = MI;
1064 ++NumMacrosRead;
1065 break;
1066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregorc3366a52009-04-21 23:56:24 +00001068 case pch::PP_TOKEN: {
1069 // If we see a TOKEN before a PP_MACRO_*, then the file is
1070 // erroneous, just pretend we didn't see this.
1071 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregorc3366a52009-04-21 23:56:24 +00001073 Token Tok;
1074 Tok.startToken();
1075 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1076 Tok.setLength(Record[1]);
1077 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1078 Tok.setIdentifierInfo(II);
1079 Tok.setKind((tok::TokenKind)Record[3]);
1080 Tok.setFlag((Token::TokenFlags)Record[4]);
1081 Macro->AddTokenToBody(Tok);
1082 break;
1083 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001084 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001085 }
1086}
1087
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001088void PCHReader::ReadDefinedMacros() {
1089 // If there was no preprocessor block, do nothing.
1090 if (!MacroCursor.getBitStreamReader())
1091 return;
1092
1093 llvm::BitstreamCursor Cursor = MacroCursor;
1094 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1095 Error("malformed preprocessor block record in PCH file");
1096 return;
1097 }
1098
1099 RecordData Record;
1100 while (true) {
1101 unsigned Code = Cursor.ReadCode();
1102 if (Code == llvm::bitc::END_BLOCK) {
1103 if (Cursor.ReadBlockEnd())
1104 Error("error at end of preprocessor block in PCH file");
1105 return;
1106 }
1107
1108 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1109 // No known subblocks, always skip them.
1110 Cursor.ReadSubBlockID();
1111 if (Cursor.SkipBlock()) {
1112 Error("malformed block record in PCH file");
1113 return;
1114 }
1115 continue;
1116 }
1117
1118 if (Code == llvm::bitc::DEFINE_ABBREV) {
1119 Cursor.ReadAbbrevRecord();
1120 continue;
1121 }
1122
1123 // Read a record.
1124 const char *BlobStart;
1125 unsigned BlobLen;
1126 Record.clear();
1127 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1128 default: // Default behavior: ignore.
1129 break;
1130
1131 case pch::PP_MACRO_OBJECT_LIKE:
1132 case pch::PP_MACRO_FUNCTION_LIKE:
1133 DecodeIdentifierInfo(Record[0]);
1134 break;
1135
1136 case pch::PP_TOKEN:
1137 // Ignore tokens.
1138 break;
1139 }
1140 }
1141}
1142
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001143/// \brief If we are loading a relocatable PCH file, and the filename is
1144/// not an absolute path, add the system root to the beginning of the file
1145/// name.
1146void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1147 // If this is not a relocatable PCH file, there's nothing to do.
1148 if (!RelocatablePCH)
1149 return;
Mike Stump11289f42009-09-09 15:08:12 +00001150
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001151 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001152 return;
1153
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001154 if (isysroot == 0) {
1155 // If no system root was given, default to '/'
1156 Filename.insert(Filename.begin(), '/');
1157 return;
1158 }
Mike Stump11289f42009-09-09 15:08:12 +00001159
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001160 unsigned Length = strlen(isysroot);
1161 if (isysroot[Length - 1] != '/')
1162 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001163
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001164 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1165}
1166
Mike Stump11289f42009-09-09 15:08:12 +00001167PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001168PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001169 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001170 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001171 return Failure;
1172 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001173
1174 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001175 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001176 while (!Stream.AtEndOfStream()) {
1177 unsigned Code = Stream.ReadCode();
1178 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001179 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001180 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001181 return Failure;
1182 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001183
Douglas Gregor55abb232009-04-10 20:39:37 +00001184 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001185 }
1186
1187 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1188 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001189 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001190 // We lazily load the decls block, but we want to set up the
1191 // DeclsCursor cursor to point into it. Clone our current bitcode
1192 // cursor to it, enter the block and read the abbrevs in that block.
1193 // With the main cursor, we just skip over it.
1194 DeclsCursor = Stream;
1195 if (Stream.SkipBlock() || // Skip with the main cursor.
1196 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001197 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001198 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001199 return Failure;
1200 }
1201 break;
Mike Stump11289f42009-09-09 15:08:12 +00001202
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001203 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001204 MacroCursor = Stream;
1205 if (PP)
1206 PP->setExternalSource(this);
1207
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001208 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001209 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001210 return Failure;
1211 }
1212 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001213
Douglas Gregora7f71a92009-04-10 03:52:48 +00001214 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001215 switch (ReadSourceManagerBlock()) {
1216 case Success:
1217 break;
1218
1219 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001220 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001221 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001222
1223 case IgnorePCH:
1224 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001225 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001226 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001227 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001228 continue;
1229 }
1230
1231 if (Code == llvm::bitc::DEFINE_ABBREV) {
1232 Stream.ReadAbbrevRecord();
1233 continue;
1234 }
1235
1236 // Read and process a record.
1237 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001238 const char *BlobStart = 0;
1239 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001240 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001241 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001242 default: // Default behavior: ignore.
1243 break;
1244
1245 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001246 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001247 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001248 return Failure;
1249 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001250 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001251 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001252 break;
1253
1254 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001255 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001256 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001257 return Failure;
1258 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001259 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001260 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001261 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001262
1263 case pch::LANGUAGE_OPTIONS:
1264 if (ParseLanguageOptions(Record))
1265 return IgnorePCH;
1266 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001267
Douglas Gregor7b71e632009-04-27 22:23:34 +00001268 case pch::METADATA: {
1269 if (Record[0] != pch::VERSION_MAJOR) {
1270 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1271 : diag::warn_pch_version_too_new);
1272 return IgnorePCH;
1273 }
1274
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001275 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001276 if (Listener) {
1277 std::string TargetTriple(BlobStart, BlobLen);
1278 if (Listener->ReadTargetTriple(TargetTriple))
1279 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001280 }
1281 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001282 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001283
1284 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001285 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001286 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001287 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001288 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001289 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001290 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001291 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001292 if (PP)
1293 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001294 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001295 break;
1296
1297 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001298 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001299 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001300 return Failure;
1301 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001302 IdentifierOffsets = (const uint32_t *)BlobStart;
1303 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001304 if (PP)
1305 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001306 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001307
1308 case pch::EXTERNAL_DEFINITIONS:
1309 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001310 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001311 return Failure;
1312 }
1313 ExternalDefinitions.swap(Record);
1314 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001315
Douglas Gregor652d82a2009-04-18 05:55:16 +00001316 case pch::SPECIAL_TYPES:
1317 SpecialTypes.swap(Record);
1318 break;
1319
Douglas Gregor08f01292009-04-17 22:13:46 +00001320 case pch::STATISTICS:
1321 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001322 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001323 TotalLexicalDeclContexts = Record[2];
1324 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001325 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001326
Douglas Gregord4df8652009-04-22 22:02:47 +00001327 case pch::TENTATIVE_DEFINITIONS:
1328 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001329 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001330 return Failure;
1331 }
1332 TentativeDefinitions.swap(Record);
1333 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001334
1335 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1336 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001337 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001338 return Failure;
1339 }
1340 LocallyScopedExternalDecls.swap(Record);
1341 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001342
Douglas Gregor95c13f52009-04-25 17:48:32 +00001343 case pch::SELECTOR_OFFSETS:
1344 SelectorOffsets = (const uint32_t *)BlobStart;
1345 TotalNumSelectors = Record[0];
1346 SelectorsLoaded.resize(TotalNumSelectors);
1347 break;
1348
Douglas Gregorc78d3462009-04-24 21:10:55 +00001349 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001350 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1351 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001352 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001353 = PCHMethodPoolLookupTable::Create(
1354 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001355 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001356 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001357 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001358 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001359
1360 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001361 if (!Record.empty() && Listener)
1362 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001363 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001364
1365 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001366 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001367 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001368 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001369 break;
1370
1371 case pch::SOURCE_LOCATION_PRELOADS:
1372 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1373 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1374 if (Result != Success)
1375 return Result;
1376 }
1377 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001378
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001379 case pch::STAT_CACHE: {
1380 PCHStatCache *MyStatCache =
1381 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1382 (const unsigned char *)BlobStart,
1383 NumStatHits, NumStatMisses);
1384 FileMgr.addStatCache(MyStatCache);
1385 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001386 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001387 }
1388
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001389 case pch::EXT_VECTOR_DECLS:
1390 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001391 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001392 return Failure;
1393 }
1394 ExtVectorDecls.swap(Record);
1395 break;
1396
Douglas Gregor45fe0362009-05-12 01:31:05 +00001397 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001398 ActualOriginalFileName.assign(BlobStart, BlobLen);
1399 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001400 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001401 break;
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001403 case pch::COMMENT_RANGES:
1404 Comments = (SourceRange *)BlobStart;
1405 NumComments = BlobLen / sizeof(SourceRange);
1406 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001407
Ted Kremenek17437132010-01-22 20:59:36 +00001408 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek18e066f2010-01-22 22:12:47 +00001409 llvm::StringRef CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001410 llvm::StringRef PCHBranch(BlobStart, BlobLen);
1411 if (CurBranch != PCHBranch) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001412 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1413 return IgnorePCH;
1414 }
1415 break;
1416 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001417 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001418 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001419 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001420 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001421}
1422
Douglas Gregor92863e42009-04-10 23:10:45 +00001423PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001424 // Set the PCH file name.
1425 this->FileName = FileName;
1426
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001427 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001428 //
1429 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001430 std::string ErrStr;
Daniel Dunbar69914f42009-11-10 00:46:19 +00001431 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001432 if (!Buffer) {
1433 Error(ErrStr.c_str());
1434 return IgnorePCH;
1435 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001436
1437 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001438 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001439 (const unsigned char *)Buffer->getBufferEnd());
1440 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001441
1442 // Sniff for the signature.
1443 if (Stream.Read(8) != 'C' ||
1444 Stream.Read(8) != 'P' ||
1445 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001446 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001447 Diag(diag::err_not_a_pch_file) << FileName;
1448 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001449 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001450
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001451 while (!Stream.AtEndOfStream()) {
1452 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregor92863e42009-04-10 23:10:45 +00001454 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001455 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001456 return Failure;
1457 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001458
1459 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001460
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001461 // We only know the PCH subblock ID.
1462 switch (BlockID) {
1463 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001464 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001465 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001466 return Failure;
1467 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001468 break;
1469 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001470 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001471 case Success:
1472 break;
1473
1474 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001475 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001476
1477 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001478 // FIXME: We could consider reading through to the end of this
1479 // PCH block, skipping subblocks, to see if there are other
1480 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001481
1482 // Clear out any preallocated source location entries, so that
1483 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001484 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001485
1486 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001487 if (StatCache)
1488 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001489
Douglas Gregor92863e42009-04-10 23:10:45 +00001490 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001491 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001492 break;
1493 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001494 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001495 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001496 return Failure;
1497 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001498 break;
1499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500 }
1501
Douglas Gregore6648fb2009-04-28 20:33:11 +00001502 // Check the predefines buffer.
Daniel Dunbar20a682d2009-11-11 00:52:11 +00001503 if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
Douglas Gregore6648fb2009-04-28 20:33:11 +00001504 PCHPredefinesBufferID))
1505 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001506
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001507 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001508 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001509 // PCH file is read, so there may be some identifiers that were
1510 // loaded into the IdentifierTable before we intercepted the
1511 // creation of identifiers. Iterate through the list of known
1512 // identifiers and determine whether we have to establish
1513 // preprocessor definitions or top-level identifier declaration
1514 // chains for those identifiers.
1515 //
1516 // We copy the IdentifierInfo pointers to a small vector first,
1517 // since de-serializing declarations or macro definitions can add
1518 // new entries into the identifier table, invalidating the
1519 // iterators.
1520 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1521 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1522 IdEnd = PP->getIdentifierTable().end();
1523 Id != IdEnd; ++Id)
1524 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001525 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001526 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1527 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1528 IdentifierInfo *II = Identifiers[I];
1529 // Look in the on-disk hash table for an entry for
1530 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001531 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001532 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1533 if (Pos == IdTable->end())
1534 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001535
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001536 // Dereferencing the iterator has the effect of populating the
1537 // IdentifierInfo node with the various declarations it needs.
1538 (void)*Pos;
1539 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001540 }
1541
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001542 if (Context)
1543 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001544
Douglas Gregora868bbd2009-04-21 22:25:48 +00001545 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001546}
1547
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001548void PCHReader::InitializeContext(ASTContext &Ctx) {
1549 Context = &Ctx;
1550 assert(Context && "Passed null context!");
1551
1552 assert(PP && "Forgot to set Preprocessor ?");
1553 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1554 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001555 PP->setExternalSource(this);
1556
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001557 // Load the translation unit declaration
1558 ReadDeclRecord(DeclOffsets[0], 0);
1559
1560 // Load the special types.
1561 Context->setBuiltinVaListType(
1562 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1563 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1564 Context->setObjCIdType(GetType(Id));
1565 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1566 Context->setObjCSelType(GetType(Sel));
1567 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1568 Context->setObjCProtoType(GetType(Proto));
1569 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1570 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001571
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001572 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1573 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001574 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001575 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1576 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001577 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1578 QualType FileType = GetType(File);
1579 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001580 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001581 Context->setFILEDecl(Typedef->getDecl());
1582 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001583 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001584 assert(Tag && "Invalid FILE type in PCH file");
1585 Context->setFILEDecl(Tag->getDecl());
1586 }
1587 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001588 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1589 QualType Jmp_bufType = GetType(Jmp_buf);
1590 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001591 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001592 Context->setjmp_bufDecl(Typedef->getDecl());
1593 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001594 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001595 assert(Tag && "Invalid jmp_bug type in PCH file");
1596 Context->setjmp_bufDecl(Tag->getDecl());
1597 }
1598 }
1599 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1600 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1601 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001602 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001603 Context->setsigjmp_bufDecl(Typedef->getDecl());
1604 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001605 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001606 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1607 Context->setsigjmp_bufDecl(Tag->getDecl());
1608 }
1609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001611 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1612 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001613 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001614 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1615 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001616#if 0
1617 // FIXME. Accommodate for this in several PCH/Index tests
1618 if (unsigned ObjCSelRedef
1619 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001620 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001621#endif
Mike Stumpd0153282009-10-20 02:12:22 +00001622 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1623 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001624 if (unsigned String
1625 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1626 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001627}
1628
Douglas Gregor45fe0362009-05-12 01:31:05 +00001629/// \brief Retrieve the name of the original source file name
1630/// directly from the PCH file, without actually loading the PCH
1631/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00001632std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1633 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00001634 // Open the PCH file.
1635 std::string ErrStr;
1636 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1637 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1638 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001639 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001640 return std::string();
1641 }
1642
1643 // Initialize the stream
1644 llvm::BitstreamReader StreamFile;
1645 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001646 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001647 (const unsigned char *)Buffer->getBufferEnd());
1648 Stream.init(StreamFile);
1649
1650 // Sniff for the signature.
1651 if (Stream.Read(8) != 'C' ||
1652 Stream.Read(8) != 'P' ||
1653 Stream.Read(8) != 'C' ||
1654 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001655 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001656 return std::string();
1657 }
1658
1659 RecordData Record;
1660 while (!Stream.AtEndOfStream()) {
1661 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001662
Douglas Gregor45fe0362009-05-12 01:31:05 +00001663 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1664 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001665
Douglas Gregor45fe0362009-05-12 01:31:05 +00001666 // We only know the PCH subblock ID.
1667 switch (BlockID) {
1668 case pch::PCH_BLOCK_ID:
1669 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001670 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001671 return std::string();
1672 }
1673 break;
Mike Stump11289f42009-09-09 15:08:12 +00001674
Douglas Gregor45fe0362009-05-12 01:31:05 +00001675 default:
1676 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001677 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001678 return std::string();
1679 }
1680 break;
1681 }
1682 continue;
1683 }
1684
1685 if (Code == llvm::bitc::END_BLOCK) {
1686 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00001687 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00001688 return std::string();
1689 }
1690 continue;
1691 }
1692
1693 if (Code == llvm::bitc::DEFINE_ABBREV) {
1694 Stream.ReadAbbrevRecord();
1695 continue;
1696 }
1697
1698 Record.clear();
1699 const char *BlobStart = 0;
1700 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001702 == pch::ORIGINAL_FILE_NAME)
1703 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001704 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001705
1706 return std::string();
1707}
1708
Douglas Gregor55abb232009-04-10 20:39:37 +00001709/// \brief Parse the record that corresponds to a LangOptions data
1710/// structure.
1711///
1712/// This routine compares the language options used to generate the
1713/// PCH file against the language options set for the current
1714/// compilation. For each option, we classify differences between the
1715/// two compiler states as either "benign" or "important". Benign
1716/// differences don't matter, and we accept them without complaint
1717/// (and without modifying the language options). Differences between
1718/// the states for important options cause the PCH file to be
1719/// unusable, so we emit a warning and return true to indicate that
1720/// there was an error.
1721///
1722/// \returns true if the PCH file is unacceptable, false otherwise.
1723bool PCHReader::ParseLanguageOptions(
1724 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001725 if (Listener) {
1726 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001727
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001728 #define PARSE_LANGOPT(Option) \
1729 LangOpts.Option = Record[Idx]; \
1730 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001731
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001732 unsigned Idx = 0;
1733 PARSE_LANGOPT(Trigraphs);
1734 PARSE_LANGOPT(BCPLComment);
1735 PARSE_LANGOPT(DollarIdents);
1736 PARSE_LANGOPT(AsmPreprocessor);
1737 PARSE_LANGOPT(GNUMode);
1738 PARSE_LANGOPT(ImplicitInt);
1739 PARSE_LANGOPT(Digraphs);
1740 PARSE_LANGOPT(HexFloats);
1741 PARSE_LANGOPT(C99);
1742 PARSE_LANGOPT(Microsoft);
1743 PARSE_LANGOPT(CPlusPlus);
1744 PARSE_LANGOPT(CPlusPlus0x);
1745 PARSE_LANGOPT(CXXOperatorNames);
1746 PARSE_LANGOPT(ObjC1);
1747 PARSE_LANGOPT(ObjC2);
1748 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00001749 PARSE_LANGOPT(ObjCNonFragileABI2);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001750 PARSE_LANGOPT(PascalStrings);
1751 PARSE_LANGOPT(WritableStrings);
1752 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001753 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001754 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00001755 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001756 PARSE_LANGOPT(NeXTRuntime);
1757 PARSE_LANGOPT(Freestanding);
1758 PARSE_LANGOPT(NoBuiltin);
1759 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001760 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001761 PARSE_LANGOPT(Blocks);
1762 PARSE_LANGOPT(EmitAllDecls);
1763 PARSE_LANGOPT(MathErrno);
1764 PARSE_LANGOPT(OverflowChecking);
1765 PARSE_LANGOPT(HeinousExtensions);
1766 PARSE_LANGOPT(Optimize);
1767 PARSE_LANGOPT(OptimizeSize);
1768 PARSE_LANGOPT(Static);
1769 PARSE_LANGOPT(PICLevel);
1770 PARSE_LANGOPT(GNUInline);
1771 PARSE_LANGOPT(NoInline);
1772 PARSE_LANGOPT(AccessControl);
1773 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00001774 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001775 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1776 ++Idx;
1777 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1778 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001779 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1780 Record[Idx]);
1781 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001782 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001783 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00001784 PARSE_LANGOPT(CatchUndefined);
1785 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001786 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001787
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001788 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001789 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001790
1791 return false;
1792}
1793
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001794void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1795 Comments.resize(NumComments);
1796 std::copy(this->Comments, this->Comments + NumComments,
1797 Comments.begin());
1798}
1799
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001800/// \brief Read and return the type at the given offset.
1801///
1802/// This routine actually reads the record corresponding to the type
1803/// at the given offset in the bitstream. It is a helper routine for
1804/// GetType, which deals with reading type IDs.
1805QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001806 // Keep track of where we are in the stream, then jump back there
1807 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001808 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001809
Douglas Gregor1342e842009-07-06 18:54:52 +00001810 // Note that we are loading a type record.
1811 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregor12bfa382009-10-17 00:13:19 +00001813 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001814 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001815 unsigned Code = DeclsCursor.ReadCode();
1816 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001817 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001818 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001819 "Incorrect encoding of extended qualifier type");
1820 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001821 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1822 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001823 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001824
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001825 case pch::TYPE_COMPLEX: {
1826 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1827 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001828 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001829 }
1830
1831 case pch::TYPE_POINTER: {
1832 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1833 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001834 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001835 }
1836
1837 case pch::TYPE_BLOCK_POINTER: {
1838 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1839 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001840 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001841 }
1842
1843 case pch::TYPE_LVALUE_REFERENCE: {
1844 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1845 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001846 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001847 }
1848
1849 case pch::TYPE_RVALUE_REFERENCE: {
1850 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1851 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001852 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001853 }
1854
1855 case pch::TYPE_MEMBER_POINTER: {
1856 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1857 QualType PointeeType = GetType(Record[0]);
1858 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001859 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001860 }
1861
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001862 case pch::TYPE_CONSTANT_ARRAY: {
1863 QualType ElementType = GetType(Record[0]);
1864 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1865 unsigned IndexTypeQuals = Record[2];
1866 unsigned Idx = 3;
1867 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001868 return Context->getConstantArrayType(ElementType, Size,
1869 ASM, IndexTypeQuals);
1870 }
1871
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001872 case pch::TYPE_INCOMPLETE_ARRAY: {
1873 QualType ElementType = GetType(Record[0]);
1874 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1875 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001876 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001877 }
1878
1879 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001880 QualType ElementType = GetType(Record[0]);
1881 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1882 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001883 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1884 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001885 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001886 ASM, IndexTypeQuals,
1887 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001888 }
1889
1890 case pch::TYPE_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001891 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001892 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001893 return QualType();
1894 }
1895
1896 QualType ElementType = GetType(Record[0]);
1897 unsigned NumElements = Record[1];
John Thompson22334602010-02-05 00:12:22 +00001898 bool AltiVec = Record[2];
1899 bool Pixel = Record[3];
1900 return Context->getVectorType(ElementType, NumElements, AltiVec, Pixel);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001901 }
1902
1903 case pch::TYPE_EXT_VECTOR: {
John Thompson22334602010-02-05 00:12:22 +00001904 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001905 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001906 return QualType();
1907 }
1908
1909 QualType ElementType = GetType(Record[0]);
1910 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001911 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001912 }
1913
1914 case pch::TYPE_FUNCTION_NO_PROTO: {
Douglas Gregor8c940862010-01-18 17:14:39 +00001915 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001916 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001917 return QualType();
1918 }
1919 QualType ResultType = GetType(Record[0]);
Douglas Gregor8c940862010-01-18 17:14:39 +00001920 return Context->getFunctionNoProtoType(ResultType, Record[1],
1921 (CallingConv)Record[2]);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001922 }
1923
1924 case pch::TYPE_FUNCTION_PROTO: {
1925 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00001926 bool NoReturn = Record[1];
Douglas Gregor8c940862010-01-18 17:14:39 +00001927 CallingConv CallConv = (CallingConv)Record[2];
1928 unsigned Idx = 3;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001929 unsigned NumParams = Record[Idx++];
1930 llvm::SmallVector<QualType, 16> ParamTypes;
1931 for (unsigned I = 0; I != NumParams; ++I)
1932 ParamTypes.push_back(GetType(Record[Idx++]));
1933 bool isVariadic = Record[Idx++];
1934 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001935 bool hasExceptionSpec = Record[Idx++];
1936 bool hasAnyExceptionSpec = Record[Idx++];
1937 unsigned NumExceptions = Record[Idx++];
1938 llvm::SmallVector<QualType, 2> Exceptions;
1939 for (unsigned I = 0; I != NumExceptions; ++I)
1940 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001941 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001942 isVariadic, Quals, hasExceptionSpec,
1943 hasAnyExceptionSpec, NumExceptions,
Douglas Gregor8c940862010-01-18 17:14:39 +00001944 Exceptions.data(), NoReturn, CallConv);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001945 }
1946
John McCallb96ec562009-12-04 22:46:56 +00001947 case pch::TYPE_UNRESOLVED_USING:
1948 return Context->getTypeDeclType(
1949 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1950
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001951 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001952 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001953 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001954
1955 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001956 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001957
1958 case pch::TYPE_TYPEOF: {
1959 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001960 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001961 return QualType();
1962 }
1963 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001964 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001965 }
Mike Stump11289f42009-09-09 15:08:12 +00001966
Anders Carlsson81df7b82009-06-24 19:06:50 +00001967 case pch::TYPE_DECLTYPE:
1968 return Context->getDecltypeType(ReadTypeExpr());
1969
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001970 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001971 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001972 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001973
Douglas Gregor1daeb692009-04-13 18:14:40 +00001974 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001975 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001976 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001977
John McCallfcc33b02009-09-05 00:15:47 +00001978 case pch::TYPE_ELABORATED: {
1979 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1980 unsigned Tag = Record[1];
1981 return Context->getElaboratedType(GetType(Record[0]),
1982 (ElaboratedType::TagKind) Tag);
1983 }
1984
Steve Naroffc277ad12009-07-18 15:33:26 +00001985 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001986 unsigned Idx = 0;
1987 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1988 unsigned NumProtos = Record[Idx++];
1989 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1990 for (unsigned I = 0; I != NumProtos; ++I)
1991 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001992 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001993 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001994
Steve Narofffb4330f2009-06-17 22:40:22 +00001995 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001996 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001997 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001998 unsigned NumProtos = Record[Idx++];
1999 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2000 for (unsigned I = 0; I != NumProtos; ++I)
2001 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00002002 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00002003 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002004
John McCallcebee162009-10-18 09:09:24 +00002005 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2006 unsigned Idx = 0;
2007 QualType Parm = GetType(Record[Idx++]);
2008 QualType Replacement = GetType(Record[Idx++]);
2009 return
2010 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2011 Replacement);
2012 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002013 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002014 // Suppress a GCC warning
2015 return QualType();
2016}
2017
John McCall8f115c62009-10-16 21:56:05 +00002018namespace {
2019
2020class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2021 PCHReader &Reader;
2022 const PCHReader::RecordData &Record;
2023 unsigned &Idx;
2024
2025public:
2026 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2027 unsigned &Idx)
2028 : Reader(Reader), Record(Record), Idx(Idx) { }
2029
John McCall17001972009-10-18 01:05:36 +00002030 // We want compile-time assurance that we've enumerated all of
2031 // these, so unfortunately we have to declare them first, then
2032 // define them out-of-line.
2033#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002034#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002035 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002036#include "clang/AST/TypeLocNodes.def"
2037
John McCall17001972009-10-18 01:05:36 +00002038 void VisitFunctionTypeLoc(FunctionTypeLoc);
2039 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002040};
2041
2042}
2043
John McCall17001972009-10-18 01:05:36 +00002044void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002045 // nothing to do
2046}
John McCall17001972009-10-18 01:05:36 +00002047void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002048 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2049 if (TL.needsExtraLocalData()) {
2050 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2051 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2052 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2053 TL.setModeAttr(Record[Idx++]);
2054 }
John McCall8f115c62009-10-16 21:56:05 +00002055}
John McCall17001972009-10-18 01:05:36 +00002056void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2057 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002058}
John McCall17001972009-10-18 01:05:36 +00002059void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2060 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002061}
John McCall17001972009-10-18 01:05:36 +00002062void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2063 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002064}
John McCall17001972009-10-18 01:05:36 +00002065void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2066 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002067}
John McCall17001972009-10-18 01:05:36 +00002068void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2069 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002070}
John McCall17001972009-10-18 01:05:36 +00002071void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2072 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002073}
John McCall17001972009-10-18 01:05:36 +00002074void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2075 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2076 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002077 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002078 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002079 else
John McCall17001972009-10-18 01:05:36 +00002080 TL.setSizeExpr(0);
2081}
2082void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2083 VisitArrayTypeLoc(TL);
2084}
2085void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2086 VisitArrayTypeLoc(TL);
2087}
2088void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2089 VisitArrayTypeLoc(TL);
2090}
2091void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2092 DependentSizedArrayTypeLoc TL) {
2093 VisitArrayTypeLoc(TL);
2094}
2095void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2096 DependentSizedExtVectorTypeLoc TL) {
2097 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098}
2099void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2100 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101}
2102void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2103 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2104}
2105void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2106 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2107 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2108 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002109 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002110 }
2111}
2112void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2113 VisitFunctionTypeLoc(TL);
2114}
2115void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2116 VisitFunctionTypeLoc(TL);
2117}
John McCallb96ec562009-12-04 22:46:56 +00002118void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2119 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2120}
John McCall17001972009-10-18 01:05:36 +00002121void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2122 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2123}
2124void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002125 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2126 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002128}
2129void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002130 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2131 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2132 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2133 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002134}
2135void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2136 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2137}
2138void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2139 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2140}
2141void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2142 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2143}
2144void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2145 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2146}
2147void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2148 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2149}
John McCallcebee162009-10-18 09:09:24 +00002150void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2151 SubstTemplateTypeParmTypeLoc TL) {
2152 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2153}
John McCall17001972009-10-18 01:05:36 +00002154void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2155 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002156 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2157 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2158 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2159 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2160 TL.setArgLocInfo(i,
2161 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2162 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002163}
2164void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2165 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2166}
2167void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2168 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2169}
2170void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2171 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002172 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2173 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2174 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2175 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002176}
John McCallfc93cf92009-10-22 22:37:11 +00002177void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2178 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2179 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2180 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2181 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2182 TL.setHasProtocolsAsWritten(Record[Idx++]);
2183 if (TL.hasProtocolsAsWritten())
2184 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2185 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2186}
John McCall8f115c62009-10-16 21:56:05 +00002187
John McCallbcd03502009-12-07 02:54:59 +00002188TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002189 unsigned &Idx) {
2190 QualType InfoTy = GetType(Record[Idx++]);
2191 if (InfoTy.isNull())
2192 return 0;
2193
John McCallbcd03502009-12-07 02:54:59 +00002194 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCall8f115c62009-10-16 21:56:05 +00002195 TypeLocReader TLR(*this, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002196 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002197 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002198 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002199}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002200
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002201QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002202 unsigned FastQuals = ID & Qualifiers::FastMask;
2203 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002204
2205 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2206 QualType T;
2207 switch ((pch::PredefinedTypeIDs)Index) {
2208 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002209 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2210 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002211
2212 case pch::PREDEF_TYPE_CHAR_U_ID:
2213 case pch::PREDEF_TYPE_CHAR_S_ID:
2214 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002215 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002216 break;
2217
Chris Lattner8575daa2009-04-27 21:45:14 +00002218 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2219 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2220 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2221 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2222 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002223 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002224 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2225 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2226 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2227 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2228 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2229 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002230 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002231 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2232 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2233 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2234 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2235 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002236 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002237 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2238 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002239 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2240 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002241 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002242 }
2243
2244 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002245 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002246 }
2247
2248 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002249 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002250 if (TypesLoaded[Index].isNull())
2251 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002252
John McCall8ccfcb52009-09-24 19:53:00 +00002253 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002254}
2255
John McCall0ad16662009-10-29 08:12:44 +00002256TemplateArgumentLocInfo
2257PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2258 const RecordData &Record,
2259 unsigned &Index) {
2260 switch (Kind) {
2261 case TemplateArgument::Expression:
2262 return ReadDeclExpr();
2263 case TemplateArgument::Type:
John McCallbcd03502009-12-07 02:54:59 +00002264 return GetTypeSourceInfo(Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002265 case TemplateArgument::Template: {
2266 SourceLocation
2267 QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2268 QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2269 TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2270 return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2271 TemplateNameLoc);
2272 }
John McCall0ad16662009-10-29 08:12:44 +00002273 case TemplateArgument::Null:
2274 case TemplateArgument::Integral:
2275 case TemplateArgument::Declaration:
2276 case TemplateArgument::Pack:
2277 return TemplateArgumentLocInfo();
2278 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002279 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002280 return TemplateArgumentLocInfo();
2281}
2282
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002283Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002284 if (ID == 0)
2285 return 0;
2286
Douglas Gregor745ed142009-04-25 18:35:21 +00002287 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002288 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002289 return 0;
2290 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002291
Douglas Gregor745ed142009-04-25 18:35:21 +00002292 unsigned Index = ID - 1;
2293 if (!DeclsLoaded[Index])
2294 ReadDeclRecord(DeclOffsets[Index], Index);
2295
2296 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002297}
2298
Chris Lattner9c28af02009-04-27 05:46:25 +00002299/// \brief Resolve the offset of a statement into a statement.
2300///
2301/// This operation will read a new statement from the external
2302/// source each time it is called, and is meant to be used via a
2303/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2304Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002305 // Since we know tha this statement is part of a decl, make sure to use the
2306 // decl cursor to read it.
2307 DeclsCursor.JumpToBit(Offset);
2308 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002309}
2310
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002311bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002312 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002313 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002314 "DeclContext has no lexical decls in storage");
2315 uint64_t Offset = DeclContextOffsets[DC].first;
2316 assert(Offset && "DeclContext has no lexical decls in storage");
2317
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002318 // Keep track of where we are in the stream, then jump back there
2319 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002320 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002321
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002322 // Load the record containing all of the declarations lexically in
2323 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002324 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002325 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002326 unsigned Code = DeclsCursor.ReadCode();
2327 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002328 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002329 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2330
2331 // Load all of the declaration IDs
2332 Decls.clear();
2333 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002334 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002335 return false;
2336}
2337
2338bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002339 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002340 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002341 "DeclContext has no visible decls in storage");
2342 uint64_t Offset = DeclContextOffsets[DC].second;
2343 assert(Offset && "DeclContext has no visible decls in storage");
2344
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002345 // Keep track of where we are in the stream, then jump back there
2346 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002347 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002348
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002349 // Load the record containing all of the declarations visible in
2350 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002351 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002352 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002353 unsigned Code = DeclsCursor.ReadCode();
2354 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002355 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002356 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2357 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002358 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002359
2360 Decls.clear();
2361
2362 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002363 while (Idx < Record.size()) {
2364 Decls.push_back(VisibleDeclaration());
2365 Decls.back().Name = ReadDeclarationName(Record, Idx);
2366
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002367 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002368 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002369 LoadedDecls.reserve(Size);
2370 for (unsigned I = 0; I < Size; ++I)
2371 LoadedDecls.push_back(Record[Idx++]);
2372 }
2373
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002374 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002375 return false;
2376}
2377
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002378void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002379 this->Consumer = Consumer;
2380
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002381 if (!Consumer)
2382 return;
2383
2384 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002385 // Force deserialization of this decl, which will cause it to be passed to
2386 // the consumer (or queued).
2387 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002388 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002389
2390 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2391 DeclGroupRef DG(InterestingDecls[I]);
2392 Consumer->HandleTopLevelDecl(DG);
2393 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002394}
2395
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002396void PCHReader::PrintStats() {
2397 std::fprintf(stderr, "*** PCH Statistics:\n");
2398
Mike Stump11289f42009-09-09 15:08:12 +00002399 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002400 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002401 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002402 unsigned NumDeclsLoaded
2403 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2404 (Decl *)0);
2405 unsigned NumIdentifiersLoaded
2406 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2407 IdentifiersLoaded.end(),
2408 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002409 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002410 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2411 SelectorsLoaded.end(),
2412 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002413
Douglas Gregorc5046832009-04-27 18:38:38 +00002414 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2415 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002416 if (TotalNumSLocEntries)
2417 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2418 NumSLocEntriesRead, TotalNumSLocEntries,
2419 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002420 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002421 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002422 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2423 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2424 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002425 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002426 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2427 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002428 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002429 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002430 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2431 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002432 if (TotalNumSelectors)
2433 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2434 NumSelectorsLoaded, TotalNumSelectors,
2435 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2436 if (TotalNumStatements)
2437 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2438 NumStatementsRead, TotalNumStatements,
2439 ((float)NumStatementsRead/TotalNumStatements * 100));
2440 if (TotalNumMacros)
2441 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2442 NumMacrosRead, TotalNumMacros,
2443 ((float)NumMacrosRead/TotalNumMacros * 100));
2444 if (TotalLexicalDeclContexts)
2445 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2446 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2447 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2448 * 100));
2449 if (TotalVisibleDeclContexts)
2450 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2451 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2452 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2453 * 100));
2454 if (TotalSelectorsInMethodPool) {
2455 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2456 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2457 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2458 * 100));
2459 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2460 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002461 std::fprintf(stderr, "\n");
2462}
2463
Douglas Gregora868bbd2009-04-21 22:25:48 +00002464void PCHReader::InitializeSema(Sema &S) {
2465 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002466 S.ExternalSource = this;
2467
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002468 // Makes sure any declarations that were deserialized "too early"
2469 // still get added to the identifier's declaration chains.
2470 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2471 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2472 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002473 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002474 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002475
2476 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00002477 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00002478 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2479 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00002480 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00002481 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002482
2483 // If there were any locally-scoped external declarations,
2484 // deserialize them and add them to Sema's table of locally-scoped
2485 // external declarations.
2486 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2487 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2488 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2489 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002490
2491 // If there were any ext_vector type declarations, deserialize them
2492 // and add them to Sema's vector of such declarations.
2493 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2494 SemaObj->ExtVectorDecls.push_back(
2495 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002496}
2497
2498IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2499 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002500 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002501 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2502 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2503 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2504 if (Pos == IdTable->end())
2505 return 0;
2506
2507 // Dereferencing the iterator has the effect of building the
2508 // IdentifierInfo node and populating it with the various
2509 // declarations it needs.
2510 return *Pos;
2511}
2512
Mike Stump11289f42009-09-09 15:08:12 +00002513std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002514PCHReader::ReadMethodPool(Selector Sel) {
2515 if (!MethodPoolLookupTable)
2516 return std::pair<ObjCMethodList, ObjCMethodList>();
2517
2518 // Try to find this selector within our on-disk hash table.
2519 PCHMethodPoolLookupTable *PoolTable
2520 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2521 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002522 if (Pos == PoolTable->end()) {
2523 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002524 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002525 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002526
Douglas Gregor95c13f52009-04-25 17:48:32 +00002527 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002528 return *Pos;
2529}
2530
Douglas Gregor0e149972009-04-25 19:10:14 +00002531void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002532 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002533 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002534 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002535}
2536
Douglas Gregor1342e842009-07-06 18:54:52 +00002537/// \brief Set the globally-visible declarations associated with the given
2538/// identifier.
2539///
2540/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002541/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002542/// them.
2543///
2544/// \param II an IdentifierInfo that refers to one or more globally-visible
2545/// declarations.
2546///
2547/// \param DeclIDs the set of declaration IDs with the name @p II that are
2548/// visible at global scope.
2549///
2550/// \param Nonrecursive should be true to indicate that the caller knows that
2551/// this call is non-recursive, and therefore the globally-visible declarations
2552/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002553void
2554PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002555 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2556 bool Nonrecursive) {
2557 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2558 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2559 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2560 PII.II = II;
2561 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2562 PII.DeclIDs.push_back(DeclIDs[I]);
2563 return;
2564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregor1342e842009-07-06 18:54:52 +00002566 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2567 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2568 if (SemaObj) {
2569 // Introduce this declaration into the translation-unit scope
2570 // and add it to the declaration chain for this identifier, so
2571 // that (unqualified) name lookup will find it.
2572 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2573 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2574 } else {
2575 // Queue this declaration so that it will be added to the
2576 // translation unit scope and identifier's declaration chain
2577 // once a Sema object is known.
2578 PreloadedDecls.push_back(D);
2579 }
2580 }
2581}
2582
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002583IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002584 if (ID == 0)
2585 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Douglas Gregor0e149972009-04-25 19:10:14 +00002587 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002588 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002589 return 0;
2590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002592 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002593 if (!IdentifiersLoaded[ID - 1]) {
2594 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002595 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002596
Douglas Gregorab4df582009-04-28 20:01:51 +00002597 // All of the strings in the PCH file are preceded by a 16-bit
2598 // length. Extract that 16-bit length to avoid having to execute
2599 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00002600 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2601 // unsigned integers. This is important to avoid integer overflow when
2602 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00002603 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00002604 unsigned StrLen = (((unsigned) StrLenPtr[0])
2605 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002606 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002607 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregor0e149972009-04-25 19:10:14 +00002610 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002611}
2612
Douglas Gregor258ae542009-04-27 06:38:32 +00002613void PCHReader::ReadSLocEntry(unsigned ID) {
2614 ReadSLocEntryRecord(ID);
2615}
2616
Steve Naroff2ddea052009-04-23 10:39:46 +00002617Selector PCHReader::DecodeSelector(unsigned ID) {
2618 if (ID == 0)
2619 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002620
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002621 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002622 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002623
2624 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002625 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002626 return Selector();
2627 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002628
2629 unsigned Index = ID - 1;
2630 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2631 // Load this selector from the selector table.
2632 // FIXME: endianness portability issues with SelectorOffsets table
2633 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002634 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002635 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2636 }
2637
2638 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002639}
2640
Mike Stump11289f42009-09-09 15:08:12 +00002641DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002642PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2643 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2644 switch (Kind) {
2645 case DeclarationName::Identifier:
2646 return DeclarationName(GetIdentifierInfo(Record, Idx));
2647
2648 case DeclarationName::ObjCZeroArgSelector:
2649 case DeclarationName::ObjCOneArgSelector:
2650 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002651 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002652
2653 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002654 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002655 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002656
2657 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002658 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002659 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002660
2661 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002662 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002663 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002664
2665 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002666 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002667 (OverloadedOperatorKind)Record[Idx++]);
2668
Alexis Hunt3d221f22009-11-29 07:34:05 +00002669 case DeclarationName::CXXLiteralOperatorName:
2670 return Context->DeclarationNames.getCXXLiteralOperatorName(
2671 GetIdentifierInfo(Record, Idx));
2672
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002673 case DeclarationName::CXXUsingDirective:
2674 return DeclarationName::getUsingDirectiveName();
2675 }
2676
2677 // Required to silence GCC warning
2678 return DeclarationName();
2679}
Douglas Gregor55abb232009-04-10 20:39:37 +00002680
Douglas Gregor1daeb692009-04-13 18:14:40 +00002681/// \brief Read an integral value
2682llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2683 unsigned BitWidth = Record[Idx++];
2684 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2685 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2686 Idx += NumWords;
2687 return Result;
2688}
2689
2690/// \brief Read a signed integral value
2691llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2692 bool isUnsigned = Record[Idx++];
2693 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2694}
2695
Douglas Gregore0a3a512009-04-14 21:55:33 +00002696/// \brief Read a floating-point value
2697llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002698 return llvm::APFloat(ReadAPInt(Record, Idx));
2699}
2700
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002701// \brief Read a string
2702std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2703 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002704 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002705 Idx += Len;
2706 return Result;
2707}
2708
Douglas Gregor55abb232009-04-10 20:39:37 +00002709DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002710 return Diag(SourceLocation(), DiagID);
2711}
2712
2713DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002714 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002715}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002716
Douglas Gregora868bbd2009-04-21 22:25:48 +00002717/// \brief Retrieve the identifier table associated with the
2718/// preprocessor.
2719IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002720 assert(PP && "Forgot to set Preprocessor ?");
2721 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002722}
2723
Douglas Gregora9af1d12009-04-17 00:04:06 +00002724/// \brief Record that the given ID maps to the given switch-case
2725/// statement.
2726void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2727 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2728 SwitchCaseStmts[ID] = SC;
2729}
2730
2731/// \brief Retrieve the switch-case statement with the given ID.
2732SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2733 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2734 return SwitchCaseStmts[ID];
2735}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002736
2737/// \brief Record that the given label statement has been
2738/// deserialized and has the given ID.
2739void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002740 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002741 "Deserialized label twice");
2742 LabelStmts[ID] = S;
2743
2744 // If we've already seen any goto statements that point to this
2745 // label, resolve them now.
2746 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2747 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2748 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2749 Goto->second->setLabel(S);
2750 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002751
2752 // If we've already seen any address-label statements that point to
2753 // this label, resolve them now.
2754 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002755 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002756 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002757 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002758 AddrLabel != AddrLabels.second; ++AddrLabel)
2759 AddrLabel->second->setLabel(S);
2760 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002761}
2762
2763/// \brief Set the label of the given statement to the label
2764/// identified by ID.
2765///
2766/// Depending on the order in which the label and other statements
2767/// referencing that label occur, this operation may complete
2768/// immediately (updating the statement) or it may queue the
2769/// statement to be back-patched later.
2770void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2771 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2772 if (Label != LabelStmts.end()) {
2773 // We've already seen this label, so set the label of the goto and
2774 // we're done.
2775 S->setLabel(Label->second);
2776 } else {
2777 // We haven't seen this label yet, so add this goto to the set of
2778 // unresolved goto statements.
2779 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2780 }
2781}
Douglas Gregor779d8652009-04-17 18:58:21 +00002782
2783/// \brief Set the label of the given expression to the label
2784/// identified by ID.
2785///
2786/// Depending on the order in which the label and other statements
2787/// referencing that label occur, this operation may complete
2788/// immediately (updating the statement) or it may queue the
2789/// statement to be back-patched later.
2790void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2791 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2792 if (Label != LabelStmts.end()) {
2793 // We've already seen this label, so set the label of the
2794 // label-address expression and we're done.
2795 S->setLabel(Label->second);
2796 } else {
2797 // We haven't seen this label yet, so add this label-address
2798 // expression to the set of unresolved label-address expressions.
2799 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2800 }
2801}
Douglas Gregor1342e842009-07-06 18:54:52 +00002802
2803
Mike Stump11289f42009-09-09 15:08:12 +00002804PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002805 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2806 Reader.CurrentlyLoadingTypeOrDecl = this;
2807}
2808
2809PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2810 if (!Parent) {
2811 // If any identifiers with corresponding top-level declarations have
2812 // been loaded, load those declarations now.
2813 while (!Reader.PendingIdentifierInfos.empty()) {
2814 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2815 Reader.PendingIdentifierInfos.front().DeclIDs,
2816 true);
2817 Reader.PendingIdentifierInfos.pop_front();
2818 }
2819 }
2820
Mike Stump11289f42009-09-09 15:08:12 +00002821 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002822}