blob: 9b23e9ab4f23047fbd2214438c3ae18192f86122 [file] [log] [blame]
Sebastian Redl3b3c8742010-08-18 23:57:11 +00001//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
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//
Sebastian Redl2c499f62010-08-18 23:56:43 +000010// This file defines the ASTReader class, which reads AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Sebastian Redlf5b13462010-08-18 23:57:17 +000014#include "clang/Serialization/ASTReader.h"
15#include "clang/Serialization/ASTDeserializationListener.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000016#include "ASTCommon.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000017#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000018#include "clang/Frontend/Utils.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/Sema.h"
John McCallcc14d1f2010-08-24 08:50:51 +000020#include "clang/Sema/Scope.h"
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000021#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ASTContext.h"
John McCall19c1bfd2010-08-25 05:32:35 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000024#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor9b272512011-02-28 23:58:31 +000026#include "clang/AST/NestedNameSpecifier.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000028#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000029#include "clang/Lex/MacroInfo.h"
Douglas Gregoraae92242010-03-19 21:51:54 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000031#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000032#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000033#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000034#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000035#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000036#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000037#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000038#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000039#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000040#include "clang/Basic/VersionTuple.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000041#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000042#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000043#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000044#include "llvm/Support/ErrorHandling.h"
Douglas Gregor09b69892011-02-10 17:09:37 +000045#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000046#include "llvm/Support/Path.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000047#include "llvm/Support/system_error.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000048#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000049#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000050#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000051#include <sys/stat.h>
Douglas Gregor09b69892011-02-10 17:09:37 +000052
Douglas Gregoref84c4b2009-04-09 22:27:44 +000053using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000054using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000055
56//===----------------------------------------------------------------------===//
Sebastian Redld44cd6a2010-08-18 23:57:06 +000057// PCH validator implementation
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000058//===----------------------------------------------------------------------===//
59
Sebastian Redl3e31c722010-08-18 23:56:56 +000060ASTReaderListener::~ASTReaderListener() {}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000061
62bool
63PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
64 const LangOptions &PPLangOpts = PP.getLangOptions();
65#define PARSE_LANGOPT_BENIGN(Option)
66#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
67 if (PPLangOpts.Option != LangOpts.Option) { \
68 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
69 return true; \
70 }
71
72 PARSE_LANGOPT_BENIGN(Trigraphs);
73 PARSE_LANGOPT_BENIGN(BCPLComment);
74 PARSE_LANGOPT_BENIGN(DollarIdents);
75 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
76 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carruthe03aa552010-04-17 20:17:31 +000077 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000078 PARSE_LANGOPT_BENIGN(ImplicitInt);
79 PARSE_LANGOPT_BENIGN(Digraphs);
80 PARSE_LANGOPT_BENIGN(HexFloats);
81 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
Peter Collingbournea686b5f2011-04-15 00:35:23 +000082 PARSE_LANGOPT_IMPORTANT(C1X, diag::warn_pch_c1x);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
Michael J. Spencer4992ca4b2010-10-21 05:21:48 +000084 PARSE_LANGOPT_BENIGN(MSCVersion);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000085 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
86 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
87 PARSE_LANGOPT_BENIGN(CXXOperatorName);
88 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
89 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
90 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000091 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian13f3b2f2011-01-07 18:59:25 +000092 PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext);
Ted Kremenek1d56c9e2010-12-23 21:35:43 +000093 PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties,
94 diag::warn_pch_objc_auto_properties);
Douglas Gregora860e6a2011-06-14 23:20:43 +000095 PARSE_LANGOPT_BENIGN(ObjCInferRelatedResultType)
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +000096 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
Fariborz Jahanian62c56022010-04-22 21:01:59 +000097 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000098 PARSE_LANGOPT_BENIGN(PascalStrings);
99 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +0000100 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000101 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +0000102 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000103 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Anders Carlssonce8dd3a2011-02-19 23:53:54 +0000104 PARSE_LANGOPT_IMPORTANT(ObjCExceptions, diag::warn_pch_objc_exceptions);
Anders Carlsson6bbd2682011-02-23 03:04:54 +0000105 PARSE_LANGOPT_IMPORTANT(CXXExceptions, diag::warn_pch_cxx_exceptions);
106 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Douglas Gregordbe39272011-02-01 15:15:22 +0000107 PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000108 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
109 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
110 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +0000111 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000112 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +0000113 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000114 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
115 PARSE_LANGOPT_BENIGN(EmitAllDecls);
116 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattner51924e512010-06-26 21:25:03 +0000117 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump11289f42009-09-09 15:08:12 +0000118 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000119 diag::warn_pch_heinous_extensions);
120 // FIXME: Most of the options below are benign if the macro wasn't
121 // used. Unfortunately, this means that a PCH compiled without
122 // optimization can't be used with optimization turned on, even
123 // though the only thing that changes is whether __OPTIMIZE__ was
124 // defined... but if __OPTIMIZE__ never showed up in the header, it
125 // doesn't matter. We could consider making this some special kind
126 // of check.
127 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
128 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
129 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
130 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
131 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
132 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
Chandler Carruth7ffce732011-04-23 20:05:38 +0000133 PARSE_LANGOPT_IMPORTANT(Deprecated, diag::warn_pch_deprecated);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000134 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
135 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000136 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +0000137 PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000138 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000139 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000140 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
141 return true;
142 }
143 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000144 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
145 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000146 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000147 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Peter Collingbourne546d0792010-12-01 19:14:57 +0000148 PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda);
Mike Stumpd9546382009-12-12 01:27:46 +0000149 PARSE_LANGOPT_BENIGN(CatchUndefined);
John McCall31168b02011-06-15 23:02:42 +0000150 PARSE_LANGOPT_BENIGN(DefaultFPContract);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000151 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +0000152 PARSE_LANGOPT_BENIGN(SpellChecking);
John McCall31168b02011-06-15 23:02:42 +0000153 PARSE_LANGOPT_IMPORTANT(ObjCAutoRefCount, diag::warn_pch_auto_ref_count);
154 PARSE_LANGOPT_BENIGN(ObjCInferRelatedReturnType);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000155#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000156#undef PARSE_LANGOPT_BENIGN
157
158 return false;
159}
160
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000161bool PCHValidator::ReadTargetTriple(StringRef Triple) {
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000162 if (Triple == PP.getTargetInfo().getTriple().str())
163 return false;
164
165 Reader.Diag(diag::warn_pch_target_triple)
166 << Triple << PP.getTargetInfo().getTriple().str();
167 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000168}
169
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000170namespace {
171 struct EmptyStringRef {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000172 bool operator ()(StringRef r) const { return r.empty(); }
Benjamin Kramer90b5b682010-11-25 18:29:30 +0000173 };
174 struct EmptyBlock {
175 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
176 };
177}
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000178
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000179static bool EqualConcatenations(SmallVector<StringRef, 2> L,
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000180 PCHPredefinesBlocks R) {
181 // First, sum up the lengths.
182 unsigned LL = 0, RL = 0;
183 for (unsigned I = 0, N = L.size(); I != N; ++I) {
184 LL += L[I].size();
185 }
186 for (unsigned I = 0, N = R.size(); I != N; ++I) {
187 RL += R[I].Data.size();
188 }
189 if (LL != RL)
190 return false;
191 if (LL == 0 && RL == 0)
192 return true;
193
194 // Kick out empty parts, they confuse the algorithm below.
195 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
196 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
197
198 // Do it the hard way. At this point, both vectors must be non-empty.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000199 StringRef LR = L[0], RR = R[0].Data;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000200 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbar01ad0a72010-07-16 00:00:11 +0000201 (void) RN;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000202 for (;;) {
203 // Compare the current pieces.
204 if (LR.size() == RR.size()) {
205 // If they're the same length, it's pretty easy.
206 if (LR != RR)
207 return false;
208 // Both pieces are done, advance.
209 ++LI;
210 ++RI;
211 // If either string is done, they're both done, since they're the same
212 // length.
213 if (LI == LN) {
214 assert(RI == RN && "Strings not the same length after all?");
215 return true;
216 }
217 LR = L[LI];
218 RR = R[RI].Data;
219 } else if (LR.size() < RR.size()) {
220 // Right piece is longer.
221 if (!RR.startswith(LR))
222 return false;
223 ++LI;
224 assert(LI != LN && "Strings not the same length after all?");
225 RR = RR.substr(LR.size());
226 LR = L[LI];
227 } else {
228 // Left piece is longer.
229 if (!LR.startswith(RR))
230 return false;
231 ++RI;
232 assert(RI != RN && "Strings not the same length after all?");
233 LR = LR.substr(RR.size());
234 RR = R[RI].Data;
235 }
236 }
237}
238
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000239static std::pair<FileID, StringRef::size_type>
240FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
241 std::pair<FileID, StringRef::size_type> Res;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000242 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
243 Res.second = Buffers[I].Data.find(MacroDef);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000244 if (Res.second != StringRef::npos) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000245 Res.first = Buffers[I].BufferID;
246 break;
247 }
248 }
249 return Res;
250}
251
252bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000253 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000254 std::string &SuggestedPredefines,
255 FileManager &FileMgr) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000256 // We are in the context of an implicit include, so the predefines buffer will
257 // have a #include entry for the PCH file itself (as normalized by the
258 // preprocessor initialization). Find it and skip over it in the checking
259 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000260 llvm::SmallString<256> PCHInclude;
261 PCHInclude += "#include \"";
Nick Lewycky36079892011-02-23 21:16:44 +0000262 PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000263 PCHInclude += "\"\n";
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264 std::pair<StringRef,StringRef> Split =
265 StringRef(PP.getPredefines()).split(PCHInclude.str());
266 StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000267 if (Left == PP.getPredefines()) {
268 Error("Missing PCH include entry!");
269 return true;
270 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000271
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000272 // If the concatenation of all the PCH buffers is equal to the adjusted
273 // command line, we're done.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000274 SmallVector<StringRef, 2> CommandLine;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000275 CommandLine.push_back(Left);
276 CommandLine.push_back(Right);
277 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000278 return false;
279
280 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000281
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000282 // The predefines buffers are different. Determine what the differences are,
283 // and whether they require us to reject the PCH file.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000284 SmallVector<StringRef, 8> PCHLines;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000285 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
286 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000287
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000288 SmallVector<StringRef, 8> CmdLineLines;
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000289 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis58c65412010-09-30 16:53:50 +0000290
291 // Pick out implicit #includes after the PCH and don't consider them for
292 // validation; we will insert them into SuggestedPredefines so that the
293 // preprocessor includes them.
294 std::string IncludesAfterPCH;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 SmallVector<StringRef, 8> AfterPCHLines;
Argyrios Kyrtzidis58c65412010-09-30 16:53:50 +0000296 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
297 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
298 if (AfterPCHLines[i].startswith("#include ")) {
299 IncludesAfterPCH += AfterPCHLines[i];
300 IncludesAfterPCH += '\n';
301 } else {
302 CmdLineLines.push_back(AfterPCHLines[i]);
303 }
304 }
305
306 // Make sure we add the includes last into SuggestedPredefines before we
307 // exit this function.
308 struct AddIncludesRAII {
309 std::string &SuggestedPredefines;
310 std::string &IncludesAfterPCH;
311
312 AddIncludesRAII(std::string &SuggestedPredefines,
313 std::string &IncludesAfterPCH)
314 : SuggestedPredefines(SuggestedPredefines),
315 IncludesAfterPCH(IncludesAfterPCH) { }
316 ~AddIncludesRAII() {
317 SuggestedPredefines += IncludesAfterPCH;
318 }
319 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320
Daniel Dunbar499baed2009-11-11 05:26:28 +0000321 // Sort both sets of predefined buffer lines, since we allow some extra
322 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000323 std::sort(CmdLineLines.begin(), CmdLineLines.end());
324 std::sort(PCHLines.begin(), PCHLines.end());
325
Daniel Dunbar499baed2009-11-11 05:26:28 +0000326 // Determine which predefines that were used to build the PCH file are missing
327 // from the command line.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 std::vector<StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000329 std::set_difference(PCHLines.begin(), PCHLines.end(),
330 CmdLineLines.begin(), CmdLineLines.end(),
331 std::back_inserter(MissingPredefines));
332
333 bool MissingDefines = false;
334 bool ConflictingDefines = false;
335 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 StringRef Missing = MissingPredefines[I];
Argyrios Kyrtzidis58c65412010-09-30 16:53:50 +0000337 if (Missing.startswith("#include ")) {
338 // An -include was specified when generating the PCH; it is included in
339 // the PCH, just ignore it.
340 continue;
341 }
Daniel Dunbar499baed2009-11-11 05:26:28 +0000342 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000343 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
344 return true;
345 }
Mike Stump11289f42009-09-09 15:08:12 +0000346
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000347 // This is a macro definition. Determine the name of the macro we're
348 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000349 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000350 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000351 = Missing.find_first_of("( \n\r", StartOfMacroName);
352 assert(EndOfMacroName != std::string::npos &&
353 "Couldn't find the end of the macro name");
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000354 StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000355
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000356 // Determine whether this macro was given a different definition on the
357 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000358 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000359 std::string::size_type MacroDefLen = MacroDefStart.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000360 SmallVector<StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000361 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
362 MacroDefStart);
363 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000364 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000365 // Different macro; we're done.
366 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000367 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000368 }
Mike Stump11289f42009-09-09 15:08:12 +0000369
370 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000371 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000372 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000373 (*ConflictPos)[MacroDefLen] != '(')
374 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000375
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000376 // We found a conflicting macro definition.
377 break;
378 }
Mike Stump11289f42009-09-09 15:08:12 +0000379
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000380 if (ConflictPos != CmdLineLines.end()) {
381 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
382 << MacroName;
383
384 // Show the definition of this macro within the PCH file.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000385 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000386 FindMacro(Buffers, Missing);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000387 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000388 SourceLocation PCHMissingLoc =
389 SourceMgr.getLocForStartOfFile(MacroLoc.first)
390 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar499baed2009-11-11 05:26:28 +0000391 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000392
393 ConflictingDefines = true;
394 continue;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000397 // If the macro doesn't conflict, then we'll just pick up the macro
398 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000399 if (ConflictingDefines)
400 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000401
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000402 if (!MissingDefines) {
403 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
404 MissingDefines = true;
405 }
406
407 // Show the definition of this macro within the PCH file.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000408 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000409 FindMacro(Buffers, Missing);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000410 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000411 SourceLocation PCHMissingLoc =
412 SourceMgr.getLocForStartOfFile(MacroLoc.first)
413 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000414 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000417 if (ConflictingDefines)
418 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000419
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000420 // Determine what predefines were introduced based on command-line
421 // parameters that were not present when building the PCH
422 // file. Extra #defines are okay, so long as the identifiers being
423 // defined were not used within the precompiled header.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000424 std::vector<StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000425 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
426 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000427 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000428 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 StringRef &Extra = ExtraPredefines[I];
Daniel Dunbar499baed2009-11-11 05:26:28 +0000430 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000431 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
432 return true;
433 }
434
435 // This is an extra macro definition. Determine the name of the
436 // macro we're defining.
437 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000438 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000439 = Extra.find_first_of("( \n\r", StartOfMacroName);
440 assert(EndOfMacroName != std::string::npos &&
441 "Couldn't find the end of the macro name");
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000442 StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000443
444 // Check whether this name was used somewhere in the PCH file. If
445 // so, defining it as a macro could change behavior, so we reject
446 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000447 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000448 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000449 return true;
450 }
451
452 // Add this definition to the suggested predefines buffer.
453 SuggestedPredefines += Extra;
454 SuggestedPredefines += '\n';
455 }
456
457 // If we get here, it's because the predefines buffer had compatible
458 // contents. Accept the PCH file.
459 return false;
460}
461
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000462void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
463 unsigned ID) {
464 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
465 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000466}
467
468void PCHValidator::ReadCounter(unsigned Value) {
469 PP.setCounterValue(Value);
470}
471
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000472//===----------------------------------------------------------------------===//
Sebastian Redl2c499f62010-08-18 23:56:43 +0000473// AST reader implementation
Douglas Gregora868bbd2009-04-21 22:25:48 +0000474//===----------------------------------------------------------------------===//
475
Sebastian Redl07a89a82010-07-30 00:29:29 +0000476void
Sebastian Redl3e31c722010-08-18 23:56:56 +0000477ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
Sebastian Redl07a89a82010-07-30 00:29:29 +0000478 DeserializationListener = Listener;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000479}
480
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000481
Douglas Gregora868bbd2009-04-21 22:25:48 +0000482namespace {
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000483class ASTSelectorLookupTrait {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000484 ASTReader &Reader;
Douglas Gregora6895d82011-07-22 16:00:58 +0000485 Module &F;
Douglas Gregor7fb09192011-07-21 22:35:25 +0000486
Douglas Gregorc78d3462009-04-24 21:10:55 +0000487public:
Sebastian Redl834bb972010-08-04 17:20:04 +0000488 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +0000489 SelectorID ID;
Douglas Gregorc10edd62011-08-25 14:51:20 +0000490 llvm::SmallVector<ObjCMethodDecl *, 2> Instance;
491 llvm::SmallVector<ObjCMethodDecl *, 2> Factory;
Sebastian Redl834bb972010-08-04 17:20:04 +0000492 };
Douglas Gregorc78d3462009-04-24 21:10:55 +0000493
494 typedef Selector external_key_type;
495 typedef external_key_type internal_key_type;
496
Douglas Gregora6895d82011-07-22 16:00:58 +0000497 ASTSelectorLookupTrait(ASTReader &Reader, Module &F)
Douglas Gregor7fb09192011-07-21 22:35:25 +0000498 : Reader(Reader), F(F) { }
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregorc78d3462009-04-24 21:10:55 +0000500 static bool EqualKey(const internal_key_type& a,
501 const internal_key_type& b) {
502 return a == b;
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregorc78d3462009-04-24 21:10:55 +0000505 static unsigned ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +0000506 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregorc78d3462009-04-24 21:10:55 +0000509 // This hopefully will just get inlined and removed by the optimizer.
510 static const internal_key_type&
511 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Douglas Gregorc78d3462009-04-24 21:10:55 +0000513 static std::pair<unsigned, unsigned>
514 ReadKeyDataLength(const unsigned char*& d) {
515 using namespace clang::io;
516 unsigned KeyLen = ReadUnalignedLE16(d);
517 unsigned DataLen = ReadUnalignedLE16(d);
518 return std::make_pair(KeyLen, DataLen);
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Douglas Gregor95c13f52009-04-25 17:48:32 +0000521 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000522 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000523 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000524 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000525 IdentifierInfo *FirstII
Douglas Gregora3e41532011-07-28 20:55:49 +0000526 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Douglas Gregorc78d3462009-04-24 21:10:55 +0000527 if (N == 0)
528 return SelTable.getNullarySelector(FirstII);
529 else if (N == 1)
530 return SelTable.getUnarySelector(FirstII);
531
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000532 SmallVector<IdentifierInfo *, 16> Args;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000533 Args.push_back(FirstII);
534 for (unsigned I = 1; I != N; ++I)
Douglas Gregora3e41532011-07-28 20:55:49 +0000535 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
Douglas Gregorc78d3462009-04-24 21:10:55 +0000536
Douglas Gregor038c3382009-05-22 22:45:36 +0000537 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregorc78d3462009-04-24 21:10:55 +0000540 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
541 using namespace clang::io;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000542
543 data_type Result;
544
Douglas Gregor074fdc52011-07-28 21:16:51 +0000545 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
Sebastian Redl834bb972010-08-04 17:20:04 +0000546 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
547 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
548
Douglas Gregorc78d3462009-04-24 21:10:55 +0000549 // Load instance methods
550 ObjCMethodList *Prev = 0;
551 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Douglas Gregorc10edd62011-08-25 14:51:20 +0000552 if (ObjCMethodDecl *Method
553 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
554 Result.Instance.push_back(Method);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000555 }
556
557 // Load factory methods
558 Prev = 0;
559 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Douglas Gregorc10edd62011-08-25 14:51:20 +0000560 if (ObjCMethodDecl *Method
561 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
562 Result.Factory.push_back(Method);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000563 }
564
565 return Result;
566 }
567};
Mike Stump11289f42009-09-09 15:08:12 +0000568
569} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000570
571/// \brief The on-disk hash table used for the global method pool.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000572typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
573 ASTSelectorLookupTable;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000574
Sebastian Redl2c373b92010-10-05 15:59:54 +0000575namespace clang {
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000576class ASTIdentifierLookupTrait {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000577 ASTReader &Reader;
Douglas Gregora6895d82011-07-22 16:00:58 +0000578 Module &F;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000579
580 // If we know the IdentifierInfo in advance, it is here and we will
581 // not build a new one. Used when deserializing information about an
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000582 // identifier that was constructed before the AST file was read.
Douglas Gregora868bbd2009-04-21 22:25:48 +0000583 IdentifierInfo *KnownII;
584
585public:
586 typedef IdentifierInfo * data_type;
587
588 typedef const std::pair<const char*, unsigned> external_key_type;
589
590 typedef external_key_type internal_key_type;
591
Douglas Gregora6895d82011-07-22 16:00:58 +0000592 ASTIdentifierLookupTrait(ASTReader &Reader, Module &F,
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000593 IdentifierInfo *II = 0)
Sebastian Redl2c373b92010-10-05 15:59:54 +0000594 : Reader(Reader), F(F), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregora868bbd2009-04-21 22:25:48 +0000596 static bool EqualKey(const internal_key_type& a,
597 const internal_key_type& b) {
598 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
599 : false;
600 }
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregora868bbd2009-04-21 22:25:48 +0000602 static unsigned ComputeHash(const internal_key_type& a) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000603 return llvm::HashString(StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000604 }
Mike Stump11289f42009-09-09 15:08:12 +0000605
Douglas Gregora868bbd2009-04-21 22:25:48 +0000606 // This hopefully will just get inlined and removed by the optimizer.
607 static const internal_key_type&
608 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Douglas Gregor57756ea2010-10-14 22:11:03 +0000610 // This hopefully will just get inlined and removed by the optimizer.
611 static const external_key_type&
612 GetExternalKey(const internal_key_type& x) { return x; }
613
Douglas Gregora868bbd2009-04-21 22:25:48 +0000614 static std::pair<unsigned, unsigned>
615 ReadKeyDataLength(const unsigned char*& d) {
616 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000617 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000618 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000619 return std::make_pair(KeyLen, DataLen);
620 }
Mike Stump11289f42009-09-09 15:08:12 +0000621
Douglas Gregora868bbd2009-04-21 22:25:48 +0000622 static std::pair<const char*, unsigned>
623 ReadKey(const unsigned char* d, unsigned n) {
624 assert(n >= 2 && d[n-1] == '\0');
625 return std::make_pair((const char*) d, n-1);
626 }
Mike Stump11289f42009-09-09 15:08:12 +0000627
628 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000629 const unsigned char* d,
630 unsigned DataLen) {
631 using namespace clang::io;
Douglas Gregor1ab036c2011-08-03 21:49:18 +0000632 unsigned RawID = ReadUnalignedLE32(d);
633 bool IsInteresting = RawID & 0x01;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000634
635 // Wipe out the "is interesting" bit.
Douglas Gregor1ab036c2011-08-03 21:49:18 +0000636 RawID = RawID >> 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000637
Douglas Gregor1ab036c2011-08-03 21:49:18 +0000638 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
Douglas Gregor1d583f22009-04-28 21:18:29 +0000639 if (!IsInteresting) {
Sebastian Redl98912122010-07-27 23:01:28 +0000640 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregor1d583f22009-04-28 21:18:29 +0000641 // and associate it with the persistent ID.
642 IdentifierInfo *II = KnownII;
643 if (!II)
Douglas Gregor1ab036c2011-08-03 21:49:18 +0000644 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregor1d583f22009-04-28 21:18:29 +0000645 Reader.SetIdentifierInfo(ID, II);
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000646 II->setIsFromAST();
Douglas Gregor1d583f22009-04-28 21:18:29 +0000647 return II;
648 }
649
Douglas Gregorb9256522009-04-28 21:32:13 +0000650 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000651 bool CPlusPlusOperatorKeyword = Bits & 0x01;
652 Bits >>= 1;
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +0000653 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
654 Bits >>= 1;
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000655 bool Poisoned = Bits & 0x01;
656 Bits >>= 1;
657 bool ExtensionToken = Bits & 0x01;
658 Bits >>= 1;
659 bool hasMacroDefinition = Bits & 0x01;
660 Bits >>= 1;
661 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
662 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000663
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000664 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000665 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000666
667 // Build the IdentifierInfo itself and link the identifier ID with
668 // the new IdentifierInfo.
669 IdentifierInfo *II = KnownII;
670 if (!II)
Douglas Gregor1ab036c2011-08-03 21:49:18 +0000671 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000672 Reader.SetIdentifierInfo(ID, II);
673
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000674 // Set or check the various bits in the IdentifierInfo structure.
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +0000675 // Token IDs are read-only.
676 if (HasRevertedTokenIDToIdentifier)
677 II->RevertTokenIDToIdentifier();
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000678 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000679 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000680 "Incorrect extension token flag");
681 (void)ExtensionToken;
Douglas Gregorb36fc532011-08-20 05:09:43 +0000682 if (Poisoned)
683 II->setIsPoisoned(true);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000684 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
685 "Incorrect C++ operator keyword flag");
686 (void)CPlusPlusOperatorKeyword;
687
Douglas Gregorc3366a52009-04-21 23:56:24 +0000688 // If this identifier is a macro, deserialize the macro
689 // definition.
690 if (hasMacroDefinition) {
Douglas Gregorb36fc532011-08-20 05:09:43 +0000691 // FIXME: Check for conflicts?
Douglas Gregorb9256522009-04-28 21:32:13 +0000692 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor5ef9e332010-10-30 00:23:06 +0000693 Reader.SetIdentifierIsMacro(II, F, Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000694 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000695 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000696
697 // Read all of the declarations visible at global scope with this
698 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000699 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000700 if (DataLen > 0) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000701 SmallVector<uint32_t, 4> DeclIDs;
Douglas Gregor1342e842009-07-06 18:54:52 +0000702 for (; DataLen > 0; DataLen -= 4)
Douglas Gregorf224ae02011-07-21 23:29:11 +0000703 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
Douglas Gregor1342e842009-07-06 18:54:52 +0000704 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000705 }
Mike Stump11289f42009-09-09 15:08:12 +0000706
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000707 II->setIsFromAST();
Douglas Gregora868bbd2009-04-21 22:25:48 +0000708 return II;
709 }
710};
Mike Stump11289f42009-09-09 15:08:12 +0000711
712} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000713
714/// \brief The on-disk hash table used to contain information about
715/// all of the identifiers in the program.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000716typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
717 ASTIdentifierLookupTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000718
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000719namespace {
720class ASTDeclContextNameLookupTrait {
721 ASTReader &Reader;
Douglas Gregora6895d82011-07-22 16:00:58 +0000722 Module &F;
Douglas Gregor903b7e92011-07-22 00:38:23 +0000723
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000724public:
725 /// \brief Pair of begin/end iterators for DeclIDs.
Douglas Gregor035611e2011-07-28 22:16:57 +0000726 ///
727 /// Note that these declaration IDs are local to the module that contains this
728 /// particular lookup t
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000729 typedef std::pair<DeclID *, DeclID *> data_type;
730
731 /// \brief Special internal key for declaration names.
732 /// The hash table creates keys for comparison; we do not create
733 /// a DeclarationName for the internal key to avoid deserializing types.
734 struct DeclNameKey {
735 DeclarationName::NameKind Kind;
736 uint64_t Data;
737 DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { }
738 };
739
740 typedef DeclarationName external_key_type;
741 typedef DeclNameKey internal_key_type;
742
Douglas Gregor903b7e92011-07-22 00:38:23 +0000743 explicit ASTDeclContextNameLookupTrait(ASTReader &Reader,
Douglas Gregora6895d82011-07-22 16:00:58 +0000744 Module &F)
Douglas Gregor903b7e92011-07-22 00:38:23 +0000745 : Reader(Reader), F(F) { }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000746
747 static bool EqualKey(const internal_key_type& a,
748 const internal_key_type& b) {
749 return a.Kind == b.Kind && a.Data == b.Data;
750 }
751
752 unsigned ComputeHash(const DeclNameKey &Key) const {
753 llvm::FoldingSetNodeID ID;
754 ID.AddInteger(Key.Kind);
755
756 switch (Key.Kind) {
757 case DeclarationName::Identifier:
758 case DeclarationName::CXXLiteralOperatorName:
759 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
760 break;
761 case DeclarationName::ObjCZeroArgSelector:
762 case DeclarationName::ObjCOneArgSelector:
763 case DeclarationName::ObjCMultiArgSelector:
764 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
765 break;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000766 case DeclarationName::CXXOperatorName:
767 ID.AddInteger((OverloadedOperatorKind)Key.Data);
768 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +0000769 case DeclarationName::CXXConstructorName:
770 case DeclarationName::CXXDestructorName:
771 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000772 case DeclarationName::CXXUsingDirective:
773 break;
774 }
775
776 return ID.ComputeHash();
777 }
778
779 internal_key_type GetInternalKey(const external_key_type& Name) const {
780 DeclNameKey Key;
781 Key.Kind = Name.getNameKind();
782 switch (Name.getNameKind()) {
783 case DeclarationName::Identifier:
784 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
785 break;
786 case DeclarationName::ObjCZeroArgSelector:
787 case DeclarationName::ObjCOneArgSelector:
788 case DeclarationName::ObjCMultiArgSelector:
789 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
790 break;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000791 case DeclarationName::CXXOperatorName:
792 Key.Data = Name.getCXXOverloadedOperator();
793 break;
794 case DeclarationName::CXXLiteralOperatorName:
795 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
796 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +0000797 case DeclarationName::CXXConstructorName:
798 case DeclarationName::CXXDestructorName:
799 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000800 case DeclarationName::CXXUsingDirective:
Douglas Gregor3b65ed02011-08-02 18:32:54 +0000801 Key.Data = 0;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000802 break;
803 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +0000804
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000805 return Key;
806 }
807
Argyrios Kyrtzidisd32ee892010-08-20 23:35:55 +0000808 external_key_type GetExternalKey(const internal_key_type& Key) const {
809 ASTContext *Context = Reader.getContext();
810 switch (Key.Kind) {
811 case DeclarationName::Identifier:
812 return DeclarationName((IdentifierInfo*)Key.Data);
813
814 case DeclarationName::ObjCZeroArgSelector:
815 case DeclarationName::ObjCOneArgSelector:
816 case DeclarationName::ObjCMultiArgSelector:
817 return DeclarationName(Selector(Key.Data));
818
819 case DeclarationName::CXXConstructorName:
820 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor903b7e92011-07-22 00:38:23 +0000821 Context->getCanonicalType(Reader.getLocalType(F, Key.Data)));
Argyrios Kyrtzidisd32ee892010-08-20 23:35:55 +0000822
823 case DeclarationName::CXXDestructorName:
824 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor903b7e92011-07-22 00:38:23 +0000825 Context->getCanonicalType(Reader.getLocalType(F, Key.Data)));
Argyrios Kyrtzidisd32ee892010-08-20 23:35:55 +0000826
827 case DeclarationName::CXXConversionFunctionName:
828 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor903b7e92011-07-22 00:38:23 +0000829 Context->getCanonicalType(Reader.getLocalType(F, Key.Data)));
Argyrios Kyrtzidisd32ee892010-08-20 23:35:55 +0000830
831 case DeclarationName::CXXOperatorName:
832 return Context->DeclarationNames.getCXXOperatorName(
833 (OverloadedOperatorKind)Key.Data);
834
835 case DeclarationName::CXXLiteralOperatorName:
836 return Context->DeclarationNames.getCXXLiteralOperatorName(
837 (IdentifierInfo*)Key.Data);
838
839 case DeclarationName::CXXUsingDirective:
840 return DeclarationName::getUsingDirectiveName();
841 }
842
843 llvm_unreachable("Invalid Name Kind ?");
844 }
845
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000846 static std::pair<unsigned, unsigned>
847 ReadKeyDataLength(const unsigned char*& d) {
848 using namespace clang::io;
849 unsigned KeyLen = ReadUnalignedLE16(d);
850 unsigned DataLen = ReadUnalignedLE16(d);
851 return std::make_pair(KeyLen, DataLen);
852 }
853
854 internal_key_type ReadKey(const unsigned char* d, unsigned) {
855 using namespace clang::io;
856
857 DeclNameKey Key;
858 Key.Kind = (DeclarationName::NameKind)*d++;
859 switch (Key.Kind) {
860 case DeclarationName::Identifier:
Douglas Gregora3e41532011-07-28 20:55:49 +0000861 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000862 break;
863 case DeclarationName::ObjCZeroArgSelector:
864 case DeclarationName::ObjCOneArgSelector:
865 case DeclarationName::ObjCMultiArgSelector:
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +0000866 Key.Data =
Douglas Gregor074fdc52011-07-28 21:16:51 +0000867 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
868 .getAsOpaquePtr();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000869 break;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000870 case DeclarationName::CXXOperatorName:
871 Key.Data = *d++; // OverloadedOperatorKind
872 break;
873 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregora3e41532011-07-28 20:55:49 +0000874 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000875 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +0000876 case DeclarationName::CXXConstructorName:
877 case DeclarationName::CXXDestructorName:
878 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000879 case DeclarationName::CXXUsingDirective:
Douglas Gregor3b65ed02011-08-02 18:32:54 +0000880 Key.Data = 0;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000881 break;
882 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +0000883
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +0000884 return Key;
885 }
886
887 data_type ReadData(internal_key_type, const unsigned char* d,
888 unsigned DataLen) {
889 using namespace clang::io;
890 unsigned NumDecls = ReadUnalignedLE16(d);
891 DeclID *Start = (DeclID *)d;
892 return std::make_pair(Start, Start + NumDecls);
893 }
894};
895
896} // end anonymous namespace
897
898/// \brief The on-disk hash table used for the DeclContext's Name lookup table.
899typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
900 ASTDeclContextNameLookupTable;
901
Douglas Gregor94619c82011-08-24 19:03:07 +0000902bool ASTReader::ReadDeclContextStorage(Module &M,
903 llvm::BitstreamCursor &Cursor,
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +0000904 const std::pair<uint64_t, uint64_t> &Offsets,
905 DeclContextInfo &Info) {
906 SavedStreamPosition SavedPosition(Cursor);
907 // First the lexical decls.
908 if (Offsets.first != 0) {
909 Cursor.JumpToBit(Offsets.first);
910
911 RecordData Record;
912 const char *Blob;
913 unsigned BlobLen;
914 unsigned Code = Cursor.ReadCode();
915 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
916 if (RecCode != DECL_CONTEXT_LEXICAL) {
917 Error("Expected lexical block");
918 return true;
919 }
920
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000921 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
922 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +0000923 }
924
925 // Now the lookup table.
926 if (Offsets.second != 0) {
927 Cursor.JumpToBit(Offsets.second);
928
929 RecordData Record;
930 const char *Blob;
931 unsigned BlobLen;
932 unsigned Code = Cursor.ReadCode();
933 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
934 if (RecCode != DECL_CONTEXT_VISIBLE) {
935 Error("Expected visible lookup table block");
936 return true;
937 }
938 Info.NameLookupTableData
939 = ASTDeclContextNameLookupTable::Create(
940 (const unsigned char *)Blob + Record[0],
941 (const unsigned char *)Blob,
Douglas Gregor94619c82011-08-24 19:03:07 +0000942 ASTDeclContextNameLookupTrait(*this, M));
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +0000943 }
944
945 return false;
946}
947
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000948void ASTReader::Error(StringRef Msg) {
Argyrios Kyrtzidisdaa41f52011-04-25 22:23:56 +0000949 Error(diag::err_fe_pch_malformed, Msg);
950}
951
952void ASTReader::Error(unsigned DiagID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000953 StringRef Arg1, StringRef Arg2) {
Argyrios Kyrtzidisdaa41f52011-04-25 22:23:56 +0000954 if (Diags.isDiagnosticInFlight())
955 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
956 else
957 Diag(DiagID) << Arg1 << Arg2;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000958}
959
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000960/// \brief Tell the AST listener about the predefines buffers in the chain.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000961bool ASTReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000962 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000963 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000964 ActualOriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000965 SuggestedPredefines,
966 FileMgr);
Douglas Gregorc379c072009-04-28 18:58:38 +0000967 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000968}
969
Douglas Gregorc5046832009-04-27 18:38:38 +0000970//===----------------------------------------------------------------------===//
971// Source Manager Deserialization
972//===----------------------------------------------------------------------===//
973
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000974/// \brief Read the line table in the source manager block.
Sebastian Redl2c373b92010-10-05 15:59:54 +0000975/// \returns true if there was an error.
Douglas Gregora6895d82011-07-22 16:00:58 +0000976bool ASTReader::ParseLineTable(Module &F,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000977 SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000978 unsigned Idx = 0;
979 LineTableInfo &LineTable = SourceMgr.getLineTable();
980
981 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000982 std::map<int, int> FileIDs;
983 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000984 // Extract the file name
985 unsigned FilenameLen = Record[Idx++];
986 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
987 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000988 MaybeAddSystemRootToFilename(Filename);
Jay Foad9a6b0982011-06-21 15:13:30 +0000989 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000990 }
991
992 // Parse the line entries
993 std::vector<LineEntry> Entries;
994 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000995 int FID = Record[Idx++];
Douglas Gregor925296b2011-07-19 16:10:42 +0000996 assert(FID >= 0 && "Serialized line entries for non-local file.");
997 // Remap FileID from 1-based old view.
998 FID += F.SLocEntryBaseID - 1;
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000999
1000 // Extract the line entries
1001 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +00001002 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +00001003 Entries.clear();
1004 Entries.reserve(NumEntries);
1005 for (unsigned I = 0; I != NumEntries; ++I) {
1006 unsigned FileOffset = Record[Idx++];
1007 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +00001008 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +00001009 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +00001010 = (SrcMgr::CharacteristicKind)Record[Idx++];
1011 unsigned IncludeOffset = Record[Idx++];
1012 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1013 FileKind, IncludeOffset));
1014 }
1015 LineTable.AddEntry(FID, Entries);
1016 }
1017
1018 return false;
1019}
1020
Douglas Gregorc5046832009-04-27 18:38:38 +00001021namespace {
1022
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001023class ASTStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +00001024public:
Douglas Gregorc5046832009-04-27 18:38:38 +00001025 const ino_t ino;
1026 const dev_t dev;
1027 const mode_t mode;
1028 const time_t mtime;
1029 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +00001030
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001031 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Chris Lattner2a6fa472010-11-23 19:28:12 +00001032 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
Douglas Gregorc5046832009-04-27 18:38:38 +00001033};
1034
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001035class ASTStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +00001036 public:
1037 typedef const char *external_key_type;
1038 typedef const char *internal_key_type;
1039
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001040 typedef ASTStatData data_type;
Douglas Gregorc5046832009-04-27 18:38:38 +00001041
1042 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00001043 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +00001044 }
1045
1046 static internal_key_type GetInternalKey(const char *path) { return path; }
1047
1048 static bool EqualKey(internal_key_type a, internal_key_type b) {
1049 return strcmp(a, b) == 0;
1050 }
1051
1052 static std::pair<unsigned, unsigned>
1053 ReadKeyDataLength(const unsigned char*& d) {
1054 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1055 unsigned DataLen = (unsigned) *d++;
1056 return std::make_pair(KeyLen + 1, DataLen);
1057 }
1058
1059 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1060 return (const char *)d;
1061 }
1062
1063 static data_type ReadData(const internal_key_type, const unsigned char *d,
1064 unsigned /*DataLen*/) {
1065 using namespace clang::io;
1066
Douglas Gregorc5046832009-04-27 18:38:38 +00001067 ino_t ino = (ino_t) ReadUnalignedLE32(d);
1068 dev_t dev = (dev_t) ReadUnalignedLE32(d);
1069 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +00001070 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +00001071 off_t size = (off_t) ReadUnalignedLE64(d);
1072 return data_type(ino, dev, mode, mtime, size);
1073 }
1074};
1075
1076/// \brief stat() cache for precompiled headers.
1077///
1078/// This cache is very similar to the stat cache used by pretokenized
1079/// headers.
Chris Lattner226efd32010-11-23 19:19:34 +00001080class ASTStatCache : public FileSystemStatCache {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001081 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
Douglas Gregorc5046832009-04-27 18:38:38 +00001082 CacheTy *Cache;
1083
1084 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +00001085public:
Chris Lattner2a6fa472010-11-23 19:28:12 +00001086 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1087 unsigned &NumStatHits, unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +00001088 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1089 Cache = CacheTy::Create(Buckets, Base);
1090 }
1091
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001092 ~ASTStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +00001093
Chris Lattnerdd278432010-11-23 21:17:56 +00001094 LookupResult getStat(const char *Path, struct stat &StatBuf,
1095 int *FileDescriptor) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001096 // Do the lookup for the file's data in the AST file.
Chris Lattner226efd32010-11-23 19:19:34 +00001097 CacheTy::iterator I = Cache->find(Path);
Douglas Gregorc5046832009-04-27 18:38:38 +00001098
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001099 // If we don't get a hit in the AST file just forward to 'stat'.
Douglas Gregorc5046832009-04-27 18:38:38 +00001100 if (I == Cache->end()) {
1101 ++NumStatMisses;
Chris Lattnerdd278432010-11-23 21:17:56 +00001102 return statChained(Path, StatBuf, FileDescriptor);
Douglas Gregorc5046832009-04-27 18:38:38 +00001103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
Douglas Gregorc5046832009-04-27 18:38:38 +00001105 ++NumStatHits;
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001106 ASTStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner226efd32010-11-23 19:19:34 +00001108 StatBuf.st_ino = Data.ino;
1109 StatBuf.st_dev = Data.dev;
1110 StatBuf.st_mtime = Data.mtime;
1111 StatBuf.st_mode = Data.mode;
1112 StatBuf.st_size = Data.size;
Chris Lattner8f0583d2010-11-23 20:05:15 +00001113 return CacheExists;
Douglas Gregorc5046832009-04-27 18:38:38 +00001114 }
1115};
1116} // end anonymous namespace
1117
1118
Sebastian Redl393f8b72010-07-19 20:52:06 +00001119/// \brief Read a source manager block
Douglas Gregora6895d82011-07-22 16:00:58 +00001120ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(Module &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001121 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +00001122
Sebastian Redl393f8b72010-07-19 20:52:06 +00001123 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001124
Douglas Gregor258ae542009-04-27 06:38:32 +00001125 // Set the source-location entry cursor to the current position in
1126 // the stream. This cursor will be used to read the contents of the
1127 // source manager block initially, and then lazily read
1128 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +00001129 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +00001130
1131 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +00001132 if (F.Stream.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001133 Error("malformed block record in AST file");
Douglas Gregor258ae542009-04-27 06:38:32 +00001134 return Failure;
1135 }
1136
1137 // Enter the source manager block.
Sebastian Redl539c5062010-08-18 23:57:32 +00001138 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001139 Error("malformed source manager block record in AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001140 return Failure;
1141 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001142
Douglas Gregora7f71a92009-04-10 03:52:48 +00001143 RecordData Record;
1144 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001145 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +00001146 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001147 if (SLocEntryCursor.ReadBlockEnd()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001148 Error("error at end of Source Manager block in AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001149 return Failure;
1150 }
Douglas Gregor92863e42009-04-10 23:10:45 +00001151 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +00001152 }
Mike Stump11289f42009-09-09 15:08:12 +00001153
Douglas Gregora7f71a92009-04-10 03:52:48 +00001154 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1155 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +00001156 SLocEntryCursor.ReadSubBlockID();
1157 if (SLocEntryCursor.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001158 Error("malformed block record in AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001159 return Failure;
1160 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001161 continue;
1162 }
Mike Stump11289f42009-09-09 15:08:12 +00001163
Douglas Gregora7f71a92009-04-10 03:52:48 +00001164 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001165 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +00001166 continue;
1167 }
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregora7f71a92009-04-10 03:52:48 +00001169 // Read a record.
1170 const char *BlobStart;
1171 unsigned BlobLen;
1172 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +00001173 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001174 default: // Default behavior: ignore.
1175 break;
1176
Sebastian Redl539c5062010-08-18 23:57:32 +00001177 case SM_SLOC_FILE_ENTRY:
1178 case SM_SLOC_BUFFER_ENTRY:
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001179 case SM_SLOC_EXPANSION_ENTRY:
Douglas Gregor258ae542009-04-27 06:38:32 +00001180 // Once we hit one of the source location entries, we're done.
1181 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +00001182 }
1183 }
1184}
1185
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001186/// \brief If a header file is not found at the path that we expect it to be
1187/// and the PCH file was moved from its original location, try to resolve the
1188/// file by assuming that header+PCH were moved together and the header is in
1189/// the same place relative to the PCH.
1190static std::string
1191resolveFileRelativeToOriginalDir(const std::string &Filename,
1192 const std::string &OriginalDir,
1193 const std::string &CurrDir) {
1194 assert(OriginalDir != CurrDir &&
1195 "No point trying to resolve the file if the PCH dir didn't change");
1196 using namespace llvm::sys;
1197 llvm::SmallString<128> filePath(Filename);
1198 fs::make_absolute(filePath);
1199 assert(path::is_absolute(OriginalDir));
1200 llvm::SmallString<128> currPCHPath(CurrDir);
1201
1202 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1203 fileDirE = path::end(path::parent_path(filePath));
1204 path::const_iterator origDirI = path::begin(OriginalDir),
1205 origDirE = path::end(OriginalDir);
1206 // Skip the common path components from filePath and OriginalDir.
1207 while (fileDirI != fileDirE && origDirI != origDirE &&
1208 *fileDirI == *origDirI) {
1209 ++fileDirI;
1210 ++origDirI;
1211 }
1212 for (; origDirI != origDirE; ++origDirI)
1213 path::append(currPCHPath, "..");
1214 path::append(currPCHPath, fileDirI, fileDirE);
1215 path::append(currPCHPath, path::filename(Filename));
1216 return currPCHPath.str();
1217}
1218
Douglas Gregor258ae542009-04-27 06:38:32 +00001219/// \brief Read in the source location entry with the given ID.
Douglas Gregor925296b2011-07-19 16:10:42 +00001220ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001221 if (ID == 0)
1222 return Success;
1223
Douglas Gregor49bf76b2011-07-21 18:46:38 +00001224 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001225 Error("source location entry ID out-of-range for AST file");
Douglas Gregor258ae542009-04-27 06:38:32 +00001226 return Failure;
1227 }
1228
Douglas Gregora6895d82011-07-22 16:00:58 +00001229 Module *F = GlobalSLocEntryMap.find(-ID)->second;
Douglas Gregor925296b2011-07-19 16:10:42 +00001230 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Sebastian Redl2c373b92010-10-05 15:59:54 +00001231 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Douglas Gregor925296b2011-07-19 16:10:42 +00001232 unsigned BaseOffset = F->SLocEntryBaseOffset;
Sebastian Redl34522812010-07-16 17:50:48 +00001233
Douglas Gregor258ae542009-04-27 06:38:32 +00001234 ++NumSLocEntriesRead;
Douglas Gregor258ae542009-04-27 06:38:32 +00001235 unsigned Code = SLocEntryCursor.ReadCode();
1236 if (Code == llvm::bitc::END_BLOCK ||
1237 Code == llvm::bitc::ENTER_SUBBLOCK ||
1238 Code == llvm::bitc::DEFINE_ABBREV) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001239 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor258ae542009-04-27 06:38:32 +00001240 return Failure;
1241 }
1242
Douglas Gregor258ae542009-04-27 06:38:32 +00001243 RecordData Record;
1244 const char *BlobStart;
1245 unsigned BlobLen;
1246 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1247 default:
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001248 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor258ae542009-04-27 06:38:32 +00001249 return Failure;
1250
Sebastian Redl539c5062010-08-18 23:57:32 +00001251 case SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001252 std::string Filename(BlobStart, BlobStart + BlobLen);
1253 MaybeAddSystemRootToFilename(Filename);
Chris Lattner5159f612010-11-23 08:35:12 +00001254 const FileEntry *File = FileMgr.getFile(Filename);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001255 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1256 OriginalDir != CurrentDir) {
1257 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1258 OriginalDir,
1259 CurrentDir);
1260 if (!resolved.empty())
1261 File = FileMgr.getFile(resolved);
1262 }
Axel Naumann63fbaed2011-01-27 10:55:51 +00001263 if (File == 0)
1264 File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1265 (time_t)Record[5]);
Chris Lattnerd20dc872009-06-15 04:35:16 +00001266 if (File == 0) {
1267 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001268 ErrorStr += Filename;
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001269 ErrorStr += "' referenced by AST file";
Chris Lattnerd20dc872009-06-15 04:35:16 +00001270 Error(ErrorStr.c_str());
1271 return Failure;
1272 }
Mike Stump11289f42009-09-09 15:08:12 +00001273
Douglas Gregor09b69892011-02-10 17:09:37 +00001274 if (Record.size() < 6) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001275 Error("source location entry is incorrect");
1276 return Failure;
1277 }
1278
Douglas Gregorce3a8292010-07-27 00:27:13 +00001279 if (!DisableValidation &&
1280 ((off_t)Record[4] != File->getSize()
Douglas Gregor08288f22010-04-09 15:54:22 +00001281#if !defined(LLVM_ON_WIN32)
1282 // In our regression testing, the Windows file system seems to
1283 // have inconsistent modification times that sometimes
1284 // erroneously trigger this error-handling path.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001285 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor08288f22010-04-09 15:54:22 +00001286#endif
Douglas Gregorce3a8292010-07-27 00:27:13 +00001287 )) {
Argyrios Kyrtzidisdaa41f52011-04-25 22:23:56 +00001288 Error(diag::err_fe_pch_file_modified, Filename);
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001289 return Failure;
1290 }
1291
Douglas Gregor925296b2011-07-19 16:10:42 +00001292 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Douglas Gregora6895d82011-07-22 16:00:58 +00001293 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
Douglas Gregor925296b2011-07-19 16:10:42 +00001294 // This is the module's main file.
1295 IncludeLoc = getImportLocation(F);
1296 }
1297 FileID FID = SourceMgr.createFileID(File, IncludeLoc,
Chris Lattner26b5c192010-11-23 09:19:42 +00001298 (SrcMgr::CharacteristicKind)Record[2],
Douglas Gregor925296b2011-07-19 16:10:42 +00001299 ID, BaseOffset + Record[0]);
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001300 SrcMgr::FileInfo &FileInfo =
1301 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1302 FileInfo.NumCreatedFIDs = Record[6];
Douglas Gregor258ae542009-04-27 06:38:32 +00001303 if (Record[3])
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001304 FileInfo.setHasLineDirectives();
Douglas Gregor09b69892011-02-10 17:09:37 +00001305
Douglas Gregor258ae542009-04-27 06:38:32 +00001306 break;
1307 }
1308
Sebastian Redl539c5062010-08-18 23:57:32 +00001309 case SM_SLOC_BUFFER_ENTRY: {
Douglas Gregor258ae542009-04-27 06:38:32 +00001310 const char *Name = BlobStart;
1311 unsigned Offset = Record[0];
1312 unsigned Code = SLocEntryCursor.ReadCode();
1313 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001314 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001315 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001316
Sebastian Redl539c5062010-08-18 23:57:32 +00001317 if (RecCode != SM_SLOC_BUFFER_BLOB) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001318 Error("AST record has invalid code");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001319 return Failure;
1320 }
1321
Douglas Gregor258ae542009-04-27 06:38:32 +00001322 llvm::MemoryBuffer *Buffer
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001323 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
Chris Lattner58c79342010-04-05 22:42:27 +00001324 Name);
Douglas Gregor925296b2011-07-19 16:10:42 +00001325 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1326 BaseOffset + Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregore6648fb2009-04-28 20:33:11 +00001328 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001329 PCHPredefinesBlock Block = {
1330 BufferID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001331 StringRef(BlobStart, BlobLen - 1)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001332 };
1333 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001334 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001335
1336 break;
1337 }
1338
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001339 case SM_SLOC_EXPANSION_ENTRY: {
Sebastian Redl2c373b92010-10-05 15:59:54 +00001340 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
Chandler Carruth115b0772011-07-26 03:03:05 +00001341 SourceMgr.createExpansionLoc(SpellingLoc,
Sebastian Redl2c373b92010-10-05 15:59:54 +00001342 ReadSourceLocation(*F, Record[2]),
1343 ReadSourceLocation(*F, Record[3]),
Douglas Gregor258ae542009-04-27 06:38:32 +00001344 Record[4],
1345 ID,
Douglas Gregor925296b2011-07-19 16:10:42 +00001346 BaseOffset + Record[0]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001347 break;
Mike Stump11289f42009-09-09 15:08:12 +00001348 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001349 }
1350
1351 return Success;
1352}
1353
Douglas Gregor925296b2011-07-19 16:10:42 +00001354/// \brief Find the location where the module F is imported.
Douglas Gregora6895d82011-07-22 16:00:58 +00001355SourceLocation ASTReader::getImportLocation(Module *F) {
Douglas Gregor925296b2011-07-19 16:10:42 +00001356 if (F->ImportLoc.isValid())
1357 return F->ImportLoc;
Jonathan D. Turner10d52012011-07-29 18:09:09 +00001358
Douglas Gregor925296b2011-07-19 16:10:42 +00001359 // Otherwise we have a PCH. It's considered to be "imported" at the first
1360 // location of its includer.
Jonathan D. Turner10d52012011-07-29 18:09:09 +00001361 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Douglas Gregor925296b2011-07-19 16:10:42 +00001362 // Main file is the importer. We assume that it is the first entry in the
1363 // entry table. We can't ask the manager, because at the time of PCH loading
1364 // the main file entry doesn't exist yet.
1365 // The very first entry is the invalid instantiation loc, which takes up
1366 // offsets 0 and 1.
1367 return SourceLocation::getFromRawEncoding(2U);
1368 }
Jonathan D. Turner10d52012011-07-29 18:09:09 +00001369 //return F->Loaders[0]->FirstLoc;
1370 return F->ImportedBy[0]->FirstLoc;
Douglas Gregor925296b2011-07-19 16:10:42 +00001371}
1372
Chris Lattnere78a6be2009-04-27 01:05:14 +00001373/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1374/// specified cursor. Read the abbreviations that are at the top of the block
1375/// and then leave the cursor pointing into the block.
Sebastian Redl2c499f62010-08-18 23:56:43 +00001376bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
Chris Lattnere78a6be2009-04-27 01:05:14 +00001377 unsigned BlockID) {
1378 if (Cursor.EnterSubBlock(BlockID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001379 Error("malformed block record in AST file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001380 return Failure;
1381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
Chris Lattnere78a6be2009-04-27 01:05:14 +00001383 while (true) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001384 uint64_t Offset = Cursor.GetCurrentBitNo();
Chris Lattnere78a6be2009-04-27 01:05:14 +00001385 unsigned Code = Cursor.ReadCode();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001386
Chris Lattnere78a6be2009-04-27 01:05:14 +00001387 // We expect all abbrevs to be at the start of the block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001388 if (Code != llvm::bitc::DEFINE_ABBREV) {
1389 Cursor.JumpToBit(Offset);
Chris Lattnere78a6be2009-04-27 01:05:14 +00001390 return false;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001391 }
Chris Lattnere78a6be2009-04-27 01:05:14 +00001392 Cursor.ReadAbbrevRecord();
1393 }
1394}
1395
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001396void ASTReader::ReadMacroRecord(Module &F, uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001397 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor796d76a2010-10-20 22:00:55 +00001398 llvm::BitstreamCursor &Stream = F.MacroCursor;
Mike Stump11289f42009-09-09 15:08:12 +00001399
Douglas Gregorc3366a52009-04-21 23:56:24 +00001400 // Keep track of where we are in the stream, then jump back there
1401 // after reading this macro.
1402 SavedStreamPosition SavedPosition(Stream);
1403
1404 Stream.JumpToBit(Offset);
1405 RecordData Record;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001406 SmallVector<IdentifierInfo*, 16> MacroArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001407 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregorc3366a52009-04-21 23:56:24 +00001409 while (true) {
1410 unsigned Code = Stream.ReadCode();
1411 switch (Code) {
1412 case llvm::bitc::END_BLOCK:
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001413 return;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001414
1415 case llvm::bitc::ENTER_SUBBLOCK:
1416 // No known subblocks, always skip them.
1417 Stream.ReadSubBlockID();
1418 if (Stream.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001419 Error("malformed block record in AST file");
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001420 return;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001421 }
1422 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregorc3366a52009-04-21 23:56:24 +00001424 case llvm::bitc::DEFINE_ABBREV:
1425 Stream.ReadAbbrevRecord();
1426 continue;
1427 default: break;
1428 }
1429
1430 // Read a record.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001431 const char *BlobStart = 0;
1432 unsigned BlobLen = 0;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001433 Record.clear();
Sebastian Redl539c5062010-08-18 23:57:32 +00001434 PreprocessorRecordTypes RecType =
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001435 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001436 BlobLen);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001437 switch (RecType) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001438 case PP_MACRO_OBJECT_LIKE:
1439 case PP_MACRO_FUNCTION_LIKE: {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001440 // If we already have a macro, that means that we've hit the end
1441 // of the definition of the macro we were looking for. We're
1442 // done.
1443 if (Macro)
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001444 return;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001445
Douglas Gregora3e41532011-07-28 20:55:49 +00001446 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001447 if (II == 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001448 Error("macro must have a name in AST file");
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001449 return;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001450 }
Sebastian Redl2c373b92010-10-05 15:59:54 +00001451 SourceLocation Loc = ReadSourceLocation(F, Record[1]);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001452 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001453
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001454 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001455 MI->setIsUsed(isUsed);
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001456 MI->setIsFromAST();
Mike Stump11289f42009-09-09 15:08:12 +00001457
Douglas Gregoraae92242010-03-19 21:51:54 +00001458 unsigned NextIndex = 3;
Sebastian Redl539c5062010-08-18 23:57:32 +00001459 if (RecType == PP_MACRO_FUNCTION_LIKE) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001460 // Decode function-like macro info.
1461 bool isC99VarArgs = Record[3];
1462 bool isGNUVarArgs = Record[4];
1463 MacroArgs.clear();
1464 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001465 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001466 for (unsigned i = 0; i != NumArgs; ++i)
Douglas Gregora3e41532011-07-28 20:55:49 +00001467 MacroArgs.push_back(getLocalIdentifier(F, Record[6+i]));
Douglas Gregorc3366a52009-04-21 23:56:24 +00001468
1469 // Install function-like macro info.
1470 MI->setIsFunctionLike();
1471 if (isC99VarArgs) MI->setIsC99Varargs();
1472 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001473 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001474 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001475 }
1476
1477 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001478 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001479
1480 // Remember that we saw this macro last so that we add the tokens that
1481 // form its body to it.
1482 Macro = MI;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001483
Douglas Gregoraae92242010-03-19 21:51:54 +00001484 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1485 // We have a macro definition. Load it now.
1486 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
Douglas Gregor035611e2011-07-28 22:16:57 +00001487 getLocalMacroDefinition(F, Record[NextIndex]));
Douglas Gregoraae92242010-03-19 21:51:54 +00001488 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001489
Douglas Gregorc3366a52009-04-21 23:56:24 +00001490 ++NumMacrosRead;
1491 break;
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Sebastian Redl539c5062010-08-18 23:57:32 +00001494 case PP_TOKEN: {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001495 // If we see a TOKEN before a PP_MACRO_*, then the file is
1496 // erroneous, just pretend we didn't see this.
1497 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001498
Douglas Gregorc3366a52009-04-21 23:56:24 +00001499 Token Tok;
1500 Tok.startToken();
Sebastian Redl2c373b92010-10-05 15:59:54 +00001501 Tok.setLocation(ReadSourceLocation(F, Record[0]));
Douglas Gregorc3366a52009-04-21 23:56:24 +00001502 Tok.setLength(Record[1]);
Douglas Gregora3e41532011-07-28 20:55:49 +00001503 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
Douglas Gregorc3366a52009-04-21 23:56:24 +00001504 Tok.setIdentifierInfo(II);
1505 Tok.setKind((tok::TokenKind)Record[3]);
1506 Tok.setFlag((Token::TokenFlags)Record[4]);
1507 Macro->AddTokenToBody(Tok);
1508 break;
1509 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00001510 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001511 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001512
Douglas Gregor7cb0d012011-08-04 18:09:14 +00001513 return;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001514}
1515
Douglas Gregora6895d82011-07-22 16:00:58 +00001516PreprocessedEntity *ASTReader::LoadPreprocessedEntity(Module &F) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00001517 assert(PP && "Forgot to set Preprocessor ?");
1518 unsigned Code = F.PreprocessorDetailCursor.ReadCode();
1519 switch (Code) {
1520 case llvm::bitc::END_BLOCK:
1521 return 0;
1522
1523 case llvm::bitc::ENTER_SUBBLOCK:
1524 Error("unexpected subblock record in preprocessor detail block");
1525 return 0;
1526
1527 case llvm::bitc::DEFINE_ABBREV:
1528 Error("unexpected abbrevation record in preprocessor detail block");
1529 return 0;
1530
1531 default:
1532 break;
1533 }
1534
1535 if (!PP->getPreprocessingRecord()) {
1536 Error("no preprocessing record");
1537 return 0;
1538 }
1539
1540 // Read the record.
1541 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1542 const char *BlobStart = 0;
1543 unsigned BlobLen = 0;
1544 RecordData Record;
1545 PreprocessorDetailRecordTypes RecType =
1546 (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord(
1547 Code, Record, BlobStart, BlobLen);
1548 switch (RecType) {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001549 case PPD_MACRO_EXPANSION: {
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001550 PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001551 if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
Douglas Gregor92a96f52011-02-08 21:58:10 +00001552 return PE;
1553
Chandler Carrutha88a22182011-07-14 08:20:46 +00001554 MacroExpansion *ME =
Douglas Gregora3e41532011-07-28 20:55:49 +00001555 new (PPRec) MacroExpansion(getLocalIdentifier(F, Record[3]),
Douglas Gregor92a96f52011-02-08 21:58:10 +00001556 SourceRange(ReadSourceLocation(F, Record[1]),
1557 ReadSourceLocation(F, Record[2])),
Douglas Gregor035611e2011-07-28 22:16:57 +00001558 getLocalMacroDefinition(F, Record[4]));
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001559 PPRec.setLoadedPreallocatedEntity(GlobalID - 1, ME);
Chandler Carrutha88a22182011-07-14 08:20:46 +00001560 return ME;
Douglas Gregor92a96f52011-02-08 21:58:10 +00001561 }
1562
1563 case PPD_MACRO_DEFINITION: {
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001564 PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001565 if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
Douglas Gregor92a96f52011-02-08 21:58:10 +00001566 return PE;
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001567
1568 unsigned MacroDefID = getGlobalMacroDefinitionID(F, Record[1]);
1569 if (MacroDefID > MacroDefinitionsLoaded.size()) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00001570 Error("out-of-bounds macro definition record");
1571 return 0;
1572 }
1573
1574 // Decode the identifier info and then check again; if the macro is
1575 // still defined and associated with the identifier,
Douglas Gregora3e41532011-07-28 20:55:49 +00001576 IdentifierInfo *II = getLocalIdentifier(F, Record[4]);
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001577 if (!MacroDefinitionsLoaded[MacroDefID - 1]) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00001578 MacroDefinition *MD
1579 = new (PPRec) MacroDefinition(II,
1580 ReadSourceLocation(F, Record[5]),
1581 SourceRange(
1582 ReadSourceLocation(F, Record[2]),
1583 ReadSourceLocation(F, Record[3])));
1584
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001585 PPRec.setLoadedPreallocatedEntity(GlobalID - 1, MD);
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001586 MacroDefinitionsLoaded[MacroDefID - 1] = MD;
Douglas Gregor92a96f52011-02-08 21:58:10 +00001587
1588 if (DeserializationListener)
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001589 DeserializationListener->MacroDefinitionRead(MacroDefID, MD);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001590 }
1591
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001592 return MacroDefinitionsLoaded[MacroDefID - 1];
Douglas Gregor92a96f52011-02-08 21:58:10 +00001593 }
1594
1595 case PPD_INCLUSION_DIRECTIVE: {
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001596 PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001597 if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
Douglas Gregor92a96f52011-02-08 21:58:10 +00001598 return PE;
1599
1600 const char *FullFileNameStart = BlobStart + Record[3];
1601 const FileEntry *File
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001602 = PP->getFileManager().getFile(StringRef(FullFileNameStart,
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001603 BlobLen - Record[3]));
Douglas Gregor92a96f52011-02-08 21:58:10 +00001604
1605 // FIXME: Stable encoding
1606 InclusionDirective::InclusionKind Kind
1607 = static_cast<InclusionDirective::InclusionKind>(Record[5]);
1608 InclusionDirective *ID
1609 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001610 StringRef(BlobStart, Record[3]),
Douglas Gregor92a96f52011-02-08 21:58:10 +00001611 Record[4],
1612 File,
1613 SourceRange(ReadSourceLocation(F, Record[1]),
1614 ReadSourceLocation(F, Record[2])));
Douglas Gregor0d4b4312011-08-04 17:06:18 +00001615 PPRec.setLoadedPreallocatedEntity(GlobalID - 1, ID);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001616 return ID;
1617 }
1618 }
1619
1620 Error("invalid offset in preprocessor detail block");
1621 return 0;
1622}
1623
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001624PreprocessedEntityID
1625ASTReader::getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) {
Douglas Gregor2f555fc2011-08-04 18:56:47 +00001626 ContinuousRangeMap<uint32_t, int, 2>::iterator
1627 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1628 assert(I != M.PreprocessedEntityRemap.end()
1629 && "Invalid index into preprocessed entity index remap");
1630
1631 return LocalID + I->second;
Douglas Gregorcaed7c62011-07-28 22:39:26 +00001632}
1633
Douglas Gregor09b69892011-02-10 17:09:37 +00001634namespace {
1635 /// \brief Trait class used to search the on-disk hash table containing all of
1636 /// the header search information.
1637 ///
1638 /// The on-disk hash table contains a mapping from each header path to
1639 /// information about that header (how many times it has been included, its
1640 /// controlling macro, etc.). Note that we actually hash based on the
1641 /// filename, and support "deep" comparisons of file names based on current
1642 /// inode numbers, so that the search can cope with non-normalized path names
1643 /// and symlinks.
1644 class HeaderFileInfoTrait {
Douglas Gregora3e41532011-07-28 20:55:49 +00001645 ASTReader &Reader;
1646 Module &M;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001647 HeaderSearch *HS;
1648 const char *FrameworkStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001649 const char *SearchPath;
1650 struct stat SearchPathStatBuf;
1651 llvm::Optional<int> SearchPathStatResult;
1652
1653 int StatSimpleCache(const char *Path, struct stat *StatBuf) {
1654 if (Path == SearchPath) {
1655 if (!SearchPathStatResult)
1656 SearchPathStatResult = stat(Path, &SearchPathStatBuf);
1657
1658 *StatBuf = SearchPathStatBuf;
1659 return *SearchPathStatResult;
1660 }
1661
1662 return stat(Path, StatBuf);
1663 }
1664
1665 public:
1666 typedef const char *external_key_type;
1667 typedef const char *internal_key_type;
1668
1669 typedef HeaderFileInfo data_type;
1670
Douglas Gregora3e41532011-07-28 20:55:49 +00001671 HeaderFileInfoTrait(ASTReader &Reader, Module &M, HeaderSearch *HS,
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001672 const char *FrameworkStrings,
1673 const char *SearchPath = 0)
Douglas Gregora3e41532011-07-28 20:55:49 +00001674 : Reader(Reader), M(M), HS(HS), FrameworkStrings(FrameworkStrings),
1675 SearchPath(SearchPath) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001676
1677 static unsigned ComputeHash(const char *path) {
1678 return llvm::HashString(llvm::sys::path::filename(path));
1679 }
1680
1681 static internal_key_type GetInternalKey(const char *path) { return path; }
1682
1683 bool EqualKey(internal_key_type a, internal_key_type b) {
1684 if (strcmp(a, b) == 0)
1685 return true;
1686
1687 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1688 return false;
1689
1690 // The file names match, but the path names don't. stat() the files to
1691 // see if they are the same.
1692 struct stat StatBufA, StatBufB;
1693 if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1694 return false;
1695
1696 return StatBufA.st_ino == StatBufB.st_ino;
1697 }
1698
1699 static std::pair<unsigned, unsigned>
1700 ReadKeyDataLength(const unsigned char*& d) {
1701 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1702 unsigned DataLen = (unsigned) *d++;
1703 return std::make_pair(KeyLen + 1, DataLen);
1704 }
1705
1706 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1707 return (const char *)d;
1708 }
1709
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001710 data_type ReadData(const internal_key_type, const unsigned char *d,
1711 unsigned DataLen) {
Douglas Gregor09b69892011-02-10 17:09:37 +00001712 const unsigned char *End = d + DataLen;
1713 using namespace clang::io;
1714 HeaderFileInfo HFI;
1715 unsigned Flags = *d++;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001716 HFI.isImport = (Flags >> 5) & 0x01;
1717 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1718 HFI.DirInfo = (Flags >> 2) & 0x03;
1719 HFI.Resolved = (Flags >> 1) & 0x01;
1720 HFI.IndexHeaderMapHeader = Flags & 0x01;
Douglas Gregor09b69892011-02-10 17:09:37 +00001721 HFI.NumIncludes = ReadUnalignedLE16(d);
Douglas Gregora3e41532011-07-28 20:55:49 +00001722 HFI.ControllingMacroID = Reader.getGlobalDeclID(M, ReadUnalignedLE32(d));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001723 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1724 // The framework offset is 1 greater than the actual offset,
1725 // since 0 is used as an indicator for "no framework name".
1726 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1727 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1728 }
1729
Douglas Gregor09b69892011-02-10 17:09:37 +00001730 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1731 (void)End;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001732
Douglas Gregor09b69892011-02-10 17:09:37 +00001733 // This HeaderFileInfo was externally loaded.
1734 HFI.External = true;
1735 return HFI;
1736 }
1737 };
1738}
1739
1740/// \brief The on-disk hash table used for the global method pool.
1741typedef OnDiskChainedHashTable<HeaderFileInfoTrait>
1742 HeaderFileInfoLookupTable;
1743
Douglas Gregora6895d82011-07-22 16:00:58 +00001744void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
Douglas Gregor074fdc52011-07-28 21:16:51 +00001745 uint64_t LocalOffset) {
Douglas Gregor5ef9e332010-10-30 00:23:06 +00001746 // Note that this identifier has a macro definition.
1747 II->setHasMacroDefinition(true);
1748
Douglas Gregord32f0352011-07-22 06:10:01 +00001749 // Adjust the offset to a global offset.
Douglas Gregor074fdc52011-07-28 21:16:51 +00001750 UnreadMacroRecordOffsets[II] = F.GlobalBitOffset + LocalOffset;
Douglas Gregor5ef9e332010-10-30 00:23:06 +00001751}
1752
Sebastian Redl2c499f62010-08-18 23:56:43 +00001753void ASTReader::ReadDefinedMacros() {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00001754 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1755 E = ModuleMgr.rend(); I != E; ++I) {
1756 llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001757
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001758 // If there was no preprocessor block, skip this file.
1759 if (!MacroCursor.getBitStreamReader())
1760 continue;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001761
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001762 llvm::BitstreamCursor Cursor = MacroCursor;
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00001763 Cursor.JumpToBit((*I)->MacroStartOffset);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00001764
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001765 RecordData Record;
1766 while (true) {
1767 unsigned Code = Cursor.ReadCode();
Douglas Gregor796d76a2010-10-20 22:00:55 +00001768 if (Code == llvm::bitc::END_BLOCK)
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001769 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001770
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001771 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1772 // No known subblocks, always skip them.
1773 Cursor.ReadSubBlockID();
1774 if (Cursor.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001775 Error("malformed block record in AST file");
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001776 return;
1777 }
1778 continue;
1779 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001780
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001781 if (Code == llvm::bitc::DEFINE_ABBREV) {
1782 Cursor.ReadAbbrevRecord();
1783 continue;
1784 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001785
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001786 // Read a record.
1787 const char *BlobStart;
1788 unsigned BlobLen;
1789 Record.clear();
1790 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1791 default: // Default behavior: ignore.
1792 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001793
Sebastian Redl539c5062010-08-18 23:57:32 +00001794 case PP_MACRO_OBJECT_LIKE:
1795 case PP_MACRO_FUNCTION_LIKE:
Douglas Gregora3e41532011-07-28 20:55:49 +00001796 getLocalIdentifier(**I, Record[0]);
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001797 break;
1798
Sebastian Redl539c5062010-08-18 23:57:32 +00001799 case PP_TOKEN:
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001800 // Ignore tokens.
1801 break;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001802 }
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001803 }
1804 }
Douglas Gregor5ef9e332010-10-30 00:23:06 +00001805
1806 // Drain the unread macro-record offsets map.
1807 while (!UnreadMacroRecordOffsets.empty())
1808 LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1809}
1810
1811void ASTReader::LoadMacroDefinition(
1812 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1813 assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
Douglas Gregor5ef9e332010-10-30 00:23:06 +00001814 uint64_t Offset = Pos->second;
1815 UnreadMacroRecordOffsets.erase(Pos);
1816
Douglas Gregord32f0352011-07-22 06:10:01 +00001817 RecordLocation Loc = getLocalBitOffset(Offset);
1818 ReadMacroRecord(*Loc.F, Loc.Offset);
Douglas Gregor5ef9e332010-10-30 00:23:06 +00001819}
1820
1821void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1822 llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1823 = UnreadMacroRecordOffsets.find(II);
1824 LoadMacroDefinition(Pos);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001825}
1826
Sebastian Redl50e26582010-09-15 19:54:06 +00001827MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
Douglas Gregor91096292010-10-02 19:29:26 +00001828 if (ID == 0 || ID > MacroDefinitionsLoaded.size())
Douglas Gregoraae92242010-03-19 21:51:54 +00001829 return 0;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001830
Douglas Gregor91096292010-10-02 19:29:26 +00001831 if (!MacroDefinitionsLoaded[ID - 1]) {
Douglas Gregor270e0142011-07-20 01:29:15 +00001832 GlobalMacroDefinitionMapType::iterator I =GlobalMacroDefinitionMap.find(ID);
1833 assert(I != GlobalMacroDefinitionMap.end() &&
1834 "Corrupted global macro definition map");
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00001835 Module &M = *I->second;
1836 unsigned Index = ID - 1 - M.BaseMacroDefinitionID;
1837 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
1838 M.PreprocessorDetailCursor.JumpToBit(M.MacroDefinitionOffsets[Index]);
1839 LoadPreprocessedEntity(M);
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001840 }
1841
Douglas Gregor91096292010-10-02 19:29:26 +00001842 return MacroDefinitionsLoaded[ID - 1];
Douglas Gregoraae92242010-03-19 21:51:54 +00001843}
1844
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001845const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00001846 std::string Filename = filenameStrRef;
1847 MaybeAddSystemRootToFilename(Filename);
1848 const FileEntry *File = FileMgr.getFile(Filename);
1849 if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1850 OriginalDir != CurrentDir) {
1851 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1852 OriginalDir,
1853 CurrentDir);
1854 if (!resolved.empty())
1855 File = FileMgr.getFile(resolved);
1856 }
1857
1858 return File;
1859}
1860
Douglas Gregor035611e2011-07-28 22:16:57 +00001861MacroID ASTReader::getGlobalMacroDefinitionID(Module &M, unsigned LocalID) {
Douglas Gregora863b4b2011-08-04 16:36:56 +00001862 if (LocalID < NUM_PREDEF_MACRO_IDS)
1863 return LocalID;
1864
1865 ContinuousRangeMap<uint32_t, int, 2>::iterator I
1866 = M.MacroDefinitionRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
1867 assert(I != M.MacroDefinitionRemap.end() &&
1868 "Invalid index into macro definition ID remap");
1869
1870 return LocalID + I->second;
Douglas Gregor035611e2011-07-28 22:16:57 +00001871}
1872
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001873/// \brief If we are loading a relocatable PCH file, and the filename is
1874/// not an absolute path, add the system root to the beginning of the file
1875/// name.
Sebastian Redl2c499f62010-08-18 23:56:43 +00001876void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001877 // If this is not a relocatable PCH file, there's nothing to do.
1878 if (!RelocatablePCH)
1879 return;
Mike Stump11289f42009-09-09 15:08:12 +00001880
Michael J. Spencerf28df4c2010-12-17 21:22:22 +00001881 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001882 return;
1883
Douglas Gregorc567ba22011-07-22 16:35:34 +00001884 if (isysroot.empty()) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001885 // If no system root was given, default to '/'
1886 Filename.insert(Filename.begin(), '/');
1887 return;
1888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Douglas Gregorc567ba22011-07-22 16:35:34 +00001890 unsigned Length = isysroot.size();
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001891 if (isysroot[Length - 1] != '/')
1892 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001893
Douglas Gregorc567ba22011-07-22 16:35:34 +00001894 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001895}
1896
Sebastian Redl2c499f62010-08-18 23:56:43 +00001897ASTReader::ASTReadResult
Douglas Gregora6895d82011-07-22 16:00:58 +00001898ASTReader::ReadASTBlock(Module &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001899 llvm::BitstreamCursor &Stream = F.Stream;
1900
Sebastian Redl539c5062010-08-18 23:57:32 +00001901 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001902 Error("malformed block record in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001903 return Failure;
1904 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001905
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001906 // Read all of the records and blocks for the ASt file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001907 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001908 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001909 while (!Stream.AtEndOfStream()) {
1910 unsigned Code = Stream.ReadCode();
1911 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001912 if (Stream.ReadBlockEnd()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001913 Error("error at end of module block in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001914 return Failure;
1915 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001916
Douglas Gregor55abb232009-04-10 20:39:37 +00001917 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001918 }
1919
1920 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1921 switch (Stream.ReadSubBlockID()) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001922 case DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001923 // We lazily load the decls block, but we want to set up the
1924 // DeclsCursor cursor to point into it. Clone our current bitcode
1925 // cursor to it, enter the block and read the abbrevs in that block.
1926 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001927 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001928 if (Stream.SkipBlock() || // Skip with the main cursor.
1929 // Read the abbrevs.
Sebastian Redl539c5062010-08-18 23:57:32 +00001930 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001931 Error("malformed block record in AST file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001932 return Failure;
1933 }
1934 break;
Mike Stump11289f42009-09-09 15:08:12 +00001935
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00001936 case DECL_UPDATES_BLOCK_ID:
1937 if (Stream.SkipBlock()) {
1938 Error("malformed block record in AST file");
1939 return Failure;
1940 }
1941 break;
1942
Sebastian Redl539c5062010-08-18 23:57:32 +00001943 case PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001944 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001945 if (PP)
1946 PP->setExternalSource(this);
1947
Douglas Gregor796d76a2010-10-20 22:00:55 +00001948 if (Stream.SkipBlock() ||
1949 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001950 Error("malformed block record in AST file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001951 return Failure;
1952 }
Douglas Gregor796d76a2010-10-20 22:00:55 +00001953 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001954 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001955
Douglas Gregor92a96f52011-02-08 21:58:10 +00001956 case PREPROCESSOR_DETAIL_BLOCK_ID:
1957 F.PreprocessorDetailCursor = Stream;
1958 if (Stream.SkipBlock() ||
1959 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1960 PREPROCESSOR_DETAIL_BLOCK_ID)) {
1961 Error("malformed preprocessor detail record in AST file");
1962 return Failure;
1963 }
1964 F.PreprocessorDetailStartOffset
1965 = F.PreprocessorDetailCursor.GetCurrentBitNo();
1966 break;
1967
Sebastian Redl539c5062010-08-18 23:57:32 +00001968 case SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001969 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001970 case Success:
1971 break;
1972
1973 case Failure:
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001974 Error("malformed source manager block in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001975 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001976
1977 case IgnorePCH:
1978 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001979 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001980 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001981 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001982 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001983 continue;
1984 }
1985
1986 if (Code == llvm::bitc::DEFINE_ABBREV) {
1987 Stream.ReadAbbrevRecord();
1988 continue;
1989 }
1990
1991 // Read and process a record.
1992 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001993 const char *BlobStart = 0;
1994 unsigned BlobLen = 0;
Sebastian Redl539c5062010-08-18 23:57:32 +00001995 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
Sebastian Redl2c373b92010-10-05 15:59:54 +00001996 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001997 default: // Default behavior: ignore.
1998 break;
1999
Sebastian Redl539c5062010-08-18 23:57:32 +00002000 case METADATA: {
2001 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2002 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002003 : diag::warn_pch_version_too_new);
2004 return IgnorePCH;
2005 }
2006
2007 RelocatablePCH = Record[4];
2008 if (Listener) {
2009 std::string TargetTriple(BlobStart, BlobLen);
2010 if (Listener->ReadTargetTriple(TargetTriple))
2011 return IgnorePCH;
2012 }
2013 break;
2014 }
2015
Douglas Gregor29cc6422011-08-17 21:07:30 +00002016 case IMPORTS: {
2017 // Load each of the imported PCH files.
2018 unsigned Idx = 0, N = Record.size();
2019 while (Idx < N) {
2020 // Read information about the AST file.
2021 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2022 unsigned Length = Record[Idx++];
2023 llvm::SmallString<128> ImportedFile(Record.begin() + Idx,
2024 Record.begin() + Idx + Length);
2025 Idx += Length;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002026
Douglas Gregor29cc6422011-08-17 21:07:30 +00002027 // Load the AST file.
Douglas Gregordf0c1512011-08-18 04:12:04 +00002028 switch(ReadASTCore(ImportedFile, ImportedKind, &F)) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00002029 case Failure: return Failure;
2030 // If we have to ignore the dependency, we'll have to ignore this too.
2031 case IgnorePCH: return IgnorePCH;
2032 case Success: break;
2033 }
2034 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002035 break;
2036 }
2037
Douglas Gregor5204bde2011-08-02 16:26:37 +00002038 case TYPE_OFFSET: {
Sebastian Redl9e687992010-07-19 22:06:55 +00002039 if (F.LocalNumTypes != 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002040 Error("duplicate TYPE_OFFSET record in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00002041 return Failure;
2042 }
Sebastian Redl9e687992010-07-19 22:06:55 +00002043 F.TypeOffsets = (const uint32_t *)BlobStart;
2044 F.LocalNumTypes = Record[0];
Douglas Gregor3b65ed02011-08-02 18:32:54 +00002045 unsigned LocalBaseTypeIndex = Record[1];
2046 F.BaseTypeIndex = getTotalNumTypes();
Douglas Gregor8ab4ea82011-07-29 00:21:44 +00002047
Douglas Gregor5204bde2011-08-02 16:26:37 +00002048 if (F.LocalNumTypes > 0) {
2049 // Introduce the global -> local mapping for types within this module.
2050 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2051
2052 // Introduce the local -> global mapping for types within this module.
Douglas Gregor3b65ed02011-08-02 18:32:54 +00002053 F.TypeRemap.insert(std::make_pair(LocalBaseTypeIndex,
2054 F.BaseTypeIndex - LocalBaseTypeIndex));
Douglas Gregor5204bde2011-08-02 16:26:37 +00002055
2056 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2057 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002058 break;
Douglas Gregor5204bde2011-08-02 16:26:37 +00002059 }
2060
Douglas Gregorf7180622011-08-03 15:48:04 +00002061 case DECL_OFFSET: {
Sebastian Redl9e687992010-07-19 22:06:55 +00002062 if (F.LocalNumDecls != 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002063 Error("duplicate DECL_OFFSET record in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00002064 return Failure;
2065 }
Sebastian Redl9e687992010-07-19 22:06:55 +00002066 F.DeclOffsets = (const uint32_t *)BlobStart;
2067 F.LocalNumDecls = Record[0];
Douglas Gregorf7180622011-08-03 15:48:04 +00002068 unsigned LocalBaseDeclID = Record[1];
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00002069 F.BaseDeclID = getTotalNumDecls();
Douglas Gregor047d2ef2011-07-20 00:27:43 +00002070
Douglas Gregorf7180622011-08-03 15:48:04 +00002071 if (F.LocalNumDecls > 0) {
2072 // Introduce the global -> local mapping for declarations within this
2073 // module.
Douglas Gregordab42432011-08-12 00:15:20 +00002074 GlobalDeclMap.insert(
2075 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
Douglas Gregorf7180622011-08-03 15:48:04 +00002076
2077 // Introduce the local -> global mapping for declarations within this
2078 // module.
2079 F.DeclRemap.insert(std::make_pair(LocalBaseDeclID,
2080 F.BaseDeclID - LocalBaseDeclID));
2081
2082 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2083 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002084 break;
Douglas Gregorf7180622011-08-03 15:48:04 +00002085 }
2086
Sebastian Redl539c5062010-08-18 23:57:32 +00002087 case TU_UPDATE_LEXICAL: {
Douglas Gregordab42432011-08-12 00:15:20 +00002088 DeclContext *TU = Context ? Context->getTranslationUnitDecl() : 0;
Douglas Gregor94619c82011-08-24 19:03:07 +00002089 DeclContextInfo &Info = F.DeclContextInfos[TU];
2090 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
2091 Info.NumLexicalDecls
2092 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
Douglas Gregordab42432011-08-12 00:15:20 +00002093 if (TU)
2094 TU->setHasExternalLexicalStorage(true);
2095
Sebastian Redl4b1f4902010-07-27 18:24:41 +00002096 break;
2097 }
2098
Sebastian Redld7dce0a2010-08-24 00:50:04 +00002099 case UPDATE_VISIBLE: {
Douglas Gregorf7180622011-08-03 15:48:04 +00002100 unsigned Idx = 0;
2101 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Sebastian Redld7dce0a2010-08-24 00:50:04 +00002102 void *Table = ASTDeclContextNameLookupTable::Create(
Douglas Gregorf7180622011-08-03 15:48:04 +00002103 (const unsigned char *)BlobStart + Record[Idx++],
Sebastian Redld7dce0a2010-08-24 00:50:04 +00002104 (const unsigned char *)BlobStart,
Douglas Gregor903b7e92011-07-22 00:38:23 +00002105 ASTDeclContextNameLookupTrait(*this, F));
Douglas Gregordab42432011-08-12 00:15:20 +00002106 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID && Context) { // Is it the TU?
Douglas Gregordab42432011-08-12 00:15:20 +00002107 DeclContext *TU = Context->getTranslationUnitDecl();
Douglas Gregor94619c82011-08-24 19:03:07 +00002108 F.DeclContextInfos[TU].NameLookupTableData = Table;
Douglas Gregordab42432011-08-12 00:15:20 +00002109 TU->setHasExternalVisibleStorage(true);
Sebastian Redld7dce0a2010-08-24 00:50:04 +00002110 } else
Douglas Gregorf7180622011-08-03 15:48:04 +00002111 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
Sebastian Redld7dce0a2010-08-24 00:50:04 +00002112 break;
2113 }
2114
Sebastian Redl539c5062010-08-18 23:57:32 +00002115 case REDECLS_UPDATE_LATEST: {
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002116 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
Douglas Gregorf7180622011-08-03 15:48:04 +00002117 for (unsigned i = 0, e = Record.size(); i < e; /* in loop */) {
2118 DeclID First = ReadDeclID(F, Record, i);
2119 DeclID Latest = ReadDeclID(F, Record, i);
Argyrios Kyrtzidis839bbac2010-08-03 17:30:10 +00002120 FirstLatestDeclIDs[First] = Latest;
2121 }
2122 break;
2123 }
2124
Sebastian Redl539c5062010-08-18 23:57:32 +00002125 case LANGUAGE_OPTIONS:
Douglas Gregorce3a8292010-07-27 00:27:13 +00002126 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor55abb232009-04-10 20:39:37 +00002127 return IgnorePCH;
2128 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00002129
Sebastian Redl539c5062010-08-18 23:57:32 +00002130 case IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00002131 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00002132 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00002133 F.IdentifierLookupTable
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002134 = ASTIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00002135 (const unsigned char *)F.IdentifierTableData + Record[0],
2136 (const unsigned char *)F.IdentifierTableData,
Sebastian Redl2c373b92010-10-05 15:59:54 +00002137 ASTIdentifierLookupTrait(*this, F));
Douglas Gregor49bf76b2011-07-21 18:46:38 +00002138 if (PP) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002139 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor49bf76b2011-07-21 18:46:38 +00002140 PP->getHeaderSearchInfo().SetExternalLookup(this);
2141 }
Douglas Gregor0e149972009-04-25 19:10:14 +00002142 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002143 break;
2144
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002145 case IDENTIFIER_OFFSET: {
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00002146 if (F.LocalNumIdentifiers != 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002147 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002148 return Failure;
2149 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00002150 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2151 F.LocalNumIdentifiers = Record[0];
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002152 unsigned LocalBaseIdentifierID = Record[1];
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00002153 F.BaseIdentifierID = getTotalNumIdentifiers();
Douglas Gregor19d26352011-07-20 00:59:32 +00002154
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002155 if (F.LocalNumIdentifiers > 0) {
2156 // Introduce the global -> local mapping for identifiers within this
2157 // module.
2158 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2159 &F));
2160
2161 // Introduce the local -> global mapping for identifiers within this
2162 // module.
2163 F.IdentifierRemap.insert(
2164 std::make_pair(LocalBaseIdentifierID,
2165 F.BaseIdentifierID - LocalBaseIdentifierID));
2166
2167 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2168 + F.LocalNumIdentifiers);
2169 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002170 break;
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002171 }
2172
Sebastian Redl539c5062010-08-18 23:57:32 +00002173 case EXTERNAL_DEFINITIONS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002174 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2175 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002176 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00002177
Sebastian Redl539c5062010-08-18 23:57:32 +00002178 case SPECIAL_TYPES:
Douglas Gregor903b7e92011-07-22 00:38:23 +00002179 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2180 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
Douglas Gregor652d82a2009-04-18 05:55:16 +00002181 break;
2182
Sebastian Redl539c5062010-08-18 23:57:32 +00002183 case STATISTICS:
Sebastian Redlb293a452010-07-20 21:20:32 +00002184 TotalNumStatements += Record[0];
2185 TotalNumMacros += Record[1];
2186 TotalLexicalDeclContexts += Record[2];
2187 TotalVisibleDeclContexts += Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00002188 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00002189
Sebastian Redl539c5062010-08-18 23:57:32 +00002190 case UNUSED_FILESCOPED_DECLS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002191 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2192 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
Tanya Lattner90073802010-02-12 00:07:30 +00002193 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002194
Alexis Hunt27a761d2011-05-04 23:29:54 +00002195 case DELEGATING_CTORS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002196 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2197 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
Alexis Hunt27a761d2011-05-04 23:29:54 +00002198 break;
2199
Sebastian Redl539c5062010-08-18 23:57:32 +00002200 case WEAK_UNDECLARED_IDENTIFIERS:
Douglas Gregor1c4bfe52011-07-28 18:09:57 +00002201 if (Record.size() % 4 != 0) {
2202 Error("invalid weak identifiers record");
2203 return Failure;
2204 }
2205
2206 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2207 // files. This isn't the way to do it :)
2208 WeakUndeclaredIdentifiers.clear();
2209
2210 // Translate the weak, undeclared identifiers into global IDs.
2211 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2212 WeakUndeclaredIdentifiers.push_back(
2213 getGlobalIdentifierID(F, Record[I++]));
2214 WeakUndeclaredIdentifiers.push_back(
2215 getGlobalIdentifierID(F, Record[I++]));
2216 WeakUndeclaredIdentifiers.push_back(
2217 ReadSourceLocation(F, Record, I).getRawEncoding());
2218 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2219 }
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00002220 break;
2221
Sebastian Redl539c5062010-08-18 23:57:32 +00002222 case LOCALLY_SCOPED_EXTERNAL_DECLS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002223 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2224 LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002225 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002226
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002227 case SELECTOR_OFFSETS: {
Sebastian Redla19a67f2010-08-03 21:58:15 +00002228 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redlada023c2010-08-04 20:40:17 +00002229 F.LocalNumSelectors = Record[0];
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002230 unsigned LocalBaseSelectorID = Record[1];
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00002231 F.BaseSelectorID = getTotalNumSelectors();
Douglas Gregor2262d282011-07-20 01:10:58 +00002232
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002233 if (F.LocalNumSelectors > 0) {
2234 // Introduce the global -> local mapping for selectors within this
2235 // module.
2236 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2237
2238 // Introduce the local -> global mapping for selectors within this
2239 // module.
2240 F.SelectorRemap.insert(std::make_pair(LocalBaseSelectorID,
2241 F.BaseSelectorID - LocalBaseSelectorID));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002242
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002243 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2244 }
2245 break;
2246 }
2247
Sebastian Redl539c5062010-08-18 23:57:32 +00002248 case METHOD_POOL:
Sebastian Redlada023c2010-08-04 20:40:17 +00002249 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002250 if (Record[0])
Sebastian Redlada023c2010-08-04 20:40:17 +00002251 F.SelectorLookupTable
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002252 = ASTSelectorLookupTable::Create(
Sebastian Redlada023c2010-08-04 20:40:17 +00002253 F.SelectorLookupTableData + Record[0],
2254 F.SelectorLookupTableData,
Douglas Gregor7fb09192011-07-21 22:35:25 +00002255 ASTSelectorLookupTrait(*this, F));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00002256 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00002257 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00002258
Sebastian Redl96371b42010-09-22 00:42:30 +00002259 case REFERENCED_SELECTOR_POOL:
Douglas Gregor3f8f04f2011-07-28 14:41:43 +00002260 if (!Record.empty()) {
2261 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2262 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2263 Record[Idx++]));
2264 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2265 getRawEncoding());
2266 }
2267 }
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00002268 break;
2269
Sebastian Redl539c5062010-08-18 23:57:32 +00002270 case PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002271 if (!Record.empty() && Listener)
2272 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002273 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00002274
Douglas Gregor925296b2011-07-19 16:10:42 +00002275 case SOURCE_LOCATION_OFFSETS: {
2276 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
Sebastian Redlb293a452010-07-20 21:20:32 +00002277 F.LocalNumSLocEntries = Record[0];
Douglas Gregor925296b2011-07-19 16:10:42 +00002278 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2279 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, Record[1]);
2280 // Make our entry in the range map. BaseID is negative and growing, so
2281 // we invert it. Because we invert it, though, we need the other end of
2282 // the range.
2283 unsigned RangeStart =
2284 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2285 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2286 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2287
2288 // Initialize the remapping table.
2289 // Invalid stays invalid.
2290 F.SLocRemap.insert(std::make_pair(0U, 0));
2291 // This module. Base was 2 when being compiled.
2292 F.SLocRemap.insert(std::make_pair(2U,
2293 static_cast<int>(F.SLocEntryBaseOffset - 2)));
Douglas Gregor49bf76b2011-07-21 18:46:38 +00002294
2295 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor925296b2011-07-19 16:10:42 +00002296 break;
2297 }
2298
Douglas Gregor5a1797c2011-08-01 16:01:55 +00002299 case MODULE_OFFSET_MAP: {
Douglas Gregor925296b2011-07-19 16:10:42 +00002300 // Additional remapping information.
2301 const unsigned char *Data = (const unsigned char*)BlobStart;
2302 const unsigned char *DataEnd = Data + BlobLen;
Douglas Gregor00659902011-08-02 10:56:51 +00002303
2304 // Continuous range maps we may be updating in our module.
2305 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002306 ContinuousRangeMap<uint32_t, int, 2>::Builder
2307 IdentifierRemap(F.IdentifierRemap);
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002308 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002309 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2310 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregora863b4b2011-08-04 16:36:56 +00002311 MacroDefinitionRemap(F.MacroDefinitionRemap);
2312 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002313 SelectorRemap(F.SelectorRemap);
Douglas Gregorf7180622011-08-03 15:48:04 +00002314 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
Douglas Gregor5204bde2011-08-02 16:26:37 +00002315 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2316
Douglas Gregor925296b2011-07-19 16:10:42 +00002317 while(Data < DataEnd) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002318 uint16_t Len = io::ReadUnalignedLE16(Data);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319 StringRef Name = StringRef((const char*)Data, Len);
Douglas Gregor00659902011-08-02 10:56:51 +00002320 Data += Len;
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002321 Module *OM = ModuleMgr.lookup(Name);
Douglas Gregor925296b2011-07-19 16:10:42 +00002322 if (!OM) {
2323 Error("SourceLocation remap refers to unknown module");
2324 return Failure;
2325 }
Douglas Gregor00659902011-08-02 10:56:51 +00002326
2327 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2328 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2329 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2330 uint32_t MacroDefinitionIDOffset = io::ReadUnalignedLE32(Data);
2331 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2332 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregor5204bde2011-08-02 16:26:37 +00002333 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
Douglas Gregor00659902011-08-02 10:56:51 +00002334
2335 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2336 SLocRemap.insert(std::make_pair(SLocOffset,
2337 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
Douglas Gregor1ab036c2011-08-03 21:49:18 +00002338 IdentifierRemap.insert(
2339 std::make_pair(IdentifierIDOffset,
2340 OM->BaseIdentifierID - IdentifierIDOffset));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002341 PreprocessedEntityRemap.insert(
2342 std::make_pair(PreprocessedEntityIDOffset,
2343 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
Douglas Gregora863b4b2011-08-04 16:36:56 +00002344 MacroDefinitionRemap.insert(
2345 std::make_pair(MacroDefinitionIDOffset,
2346 OM->BaseMacroDefinitionID - MacroDefinitionIDOffset));
Douglas Gregor8f364fb2011-08-03 23:28:44 +00002347 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2348 OM->BaseSelectorID - SelectorIDOffset));
Douglas Gregorf7180622011-08-03 15:48:04 +00002349 DeclRemap.insert(std::make_pair(DeclIDOffset,
2350 OM->BaseDeclID - DeclIDOffset));
2351
Douglas Gregor5204bde2011-08-02 16:26:37 +00002352 TypeRemap.insert(std::make_pair(TypeIndexOffset,
Douglas Gregor3b65ed02011-08-02 18:32:54 +00002353 OM->BaseTypeIndex - TypeIndexOffset));
Douglas Gregor925296b2011-07-19 16:10:42 +00002354 }
2355 break;
2356 }
2357
Douglas Gregor925296b2011-07-19 16:10:42 +00002358 case SOURCE_MANAGER_LINE_TABLE:
2359 if (ParseLineTable(F, Record))
2360 return Failure;
Douglas Gregor258ae542009-04-27 06:38:32 +00002361 break;
2362
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00002363 case FILE_SOURCE_LOCATION_OFFSETS:
2364 F.SLocFileOffsets = (const uint32_t *)BlobStart;
2365 F.LocalNumSLocFileEntries = Record[0];
2366 break;
2367
Douglas Gregor925296b2011-07-19 16:10:42 +00002368 case SOURCE_LOCATION_PRELOADS: {
2369 // Need to transform from the local view (1-based IDs) to the global view,
2370 // which is based off F.SLocEntryBaseID.
2371 PreloadSLocEntries.reserve(PreloadSLocEntries.size() + Record.size());
2372 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2373 PreloadSLocEntries.push_back(int(Record[I] - 1) + F.SLocEntryBaseID);
Douglas Gregor258ae542009-04-27 06:38:32 +00002374 break;
Douglas Gregor925296b2011-07-19 16:10:42 +00002375 }
Douglas Gregorc5046832009-04-27 18:38:38 +00002376
Sebastian Redl539c5062010-08-18 23:57:32 +00002377 case STAT_CACHE: {
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002378 if (!DisableStatCache) {
2379 ASTStatCache *MyStatCache =
2380 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2381 (const unsigned char *)BlobStart,
2382 NumStatHits, NumStatMisses);
2383 FileMgr.addStatCache(MyStatCache);
2384 F.StatCache = MyStatCache;
2385 }
Douglas Gregorc5046832009-04-27 18:38:38 +00002386 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00002387 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00002388
Sebastian Redl539c5062010-08-18 23:57:32 +00002389 case EXT_VECTOR_DECLS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002390 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2391 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002392 break;
2393
Sebastian Redl539c5062010-08-18 23:57:32 +00002394 case VTABLE_USES:
Douglas Gregor4daf6a32011-07-28 19:11:31 +00002395 if (Record.size() % 3 != 0) {
2396 Error("Invalid VTABLE_USES record");
2397 return Failure;
2398 }
2399
Sebastian Redl08aca90252010-08-05 18:21:25 +00002400 // Later tables overwrite earlier ones.
Douglas Gregor4daf6a32011-07-28 19:11:31 +00002401 // FIXME: Modules will have some trouble with this. This is clearly not
2402 // the right way to do this.
Douglas Gregor7fb09192011-07-21 22:35:25 +00002403 VTableUses.clear();
Douglas Gregor4daf6a32011-07-28 19:11:31 +00002404
2405 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2406 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2407 VTableUses.push_back(
2408 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2409 VTableUses.push_back(Record[Idx++]);
2410 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00002411 break;
2412
Sebastian Redl539c5062010-08-18 23:57:32 +00002413 case DYNAMIC_CLASSES:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002414 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2415 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00002416 break;
2417
Sebastian Redl539c5062010-08-18 23:57:32 +00002418 case PENDING_IMPLICIT_INSTANTIATIONS:
Douglas Gregorbbbc3672011-07-28 19:26:52 +00002419 if (PendingInstantiations.size() % 2 != 0) {
2420 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2421 return Failure;
2422 }
2423
2424 // Later lists of pending instantiations overwrite earlier ones.
2425 // FIXME: This is most certainly wrong for modules.
2426 PendingInstantiations.clear();
2427 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2428 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2429 PendingInstantiations.push_back(
2430 ReadSourceLocation(F, Record, I).getRawEncoding());
2431 }
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00002432 break;
2433
Sebastian Redl539c5062010-08-18 23:57:32 +00002434 case SEMA_DECL_REFS:
Sebastian Redl08aca90252010-08-05 18:21:25 +00002435 // Later tables overwrite earlier ones.
Douglas Gregor7fb09192011-07-21 22:35:25 +00002436 // FIXME: Modules will have some trouble with this.
2437 SemaDeclRefs.clear();
2438 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2439 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002440 break;
2441
Sebastian Redl539c5062010-08-18 23:57:32 +00002442 case ORIGINAL_FILE_NAME:
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002443 // The primary AST will be the last to get here, so it will be the one
Sebastian Redlb293a452010-07-20 21:20:32 +00002444 // that's used.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00002445 ActualOriginalFileName.assign(BlobStart, BlobLen);
2446 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00002447 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00002448 break;
Mike Stump11289f42009-09-09 15:08:12 +00002449
Douglas Gregora3b20262011-05-06 21:43:30 +00002450 case ORIGINAL_FILE_ID:
2451 OriginalFileID = FileID::get(Record[0]);
2452 break;
2453
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002454 case ORIGINAL_PCH_DIR:
2455 // The primary AST will be the last to get here, so it will be the one
2456 // that's used.
2457 OriginalDir.assign(BlobStart, BlobLen);
2458 break;
2459
Sebastian Redl539c5062010-08-18 23:57:32 +00002460 case VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00002461 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002462 StringRef ASTBranch(BlobStart, BlobLen);
2463 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002464 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
Douglas Gregord54f3a12009-10-05 21:07:28 +00002465 return IgnorePCH;
2466 }
2467 break;
2468 }
Sebastian Redlfa061442010-07-21 20:07:32 +00002469
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002470 case MACRO_DEFINITION_OFFSETS: {
Sebastian Redlfa061442010-07-21 20:07:32 +00002471 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
2472 F.NumPreallocatedPreprocessingEntities = Record[0];
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002473 unsigned LocalBasePreprocessedEntityID = Record[1];
2474 F.LocalNumMacroDefinitions = Record[2];
2475 unsigned LocalBaseMacroID = Record[3];
Douglas Gregora863b4b2011-08-04 16:36:56 +00002476
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002477 unsigned StartingID;
2478 if (PP) {
2479 if (!PP->getPreprocessingRecord())
2480 PP->createPreprocessingRecord(true);
2481 if (!PP->getPreprocessingRecord()->getExternalSource())
2482 PP->getPreprocessingRecord()->SetExternalSource(*this);
2483 StartingID
2484 = PP->getPreprocessingRecord()
2485 ->allocateLoadedEntities(F.NumPreallocatedPreprocessingEntities);
2486 } else {
2487 // FIXME: We'll eventually want to kill this path, since it assumes
2488 // a particular allocation strategy in the preprocessing record.
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002489 StartingID = getTotalNumPreprocessedEntities()
2490 - F.NumPreallocatedPreprocessingEntities;
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002491 }
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00002492 F.BaseMacroDefinitionID = getTotalNumMacroDefinitions();
2493 F.BasePreprocessedEntityID = StartingID;
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002494
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002495 if (F.NumPreallocatedPreprocessingEntities > 0) {
2496 // Introduce the global -> local mapping for preprocessed entities in
2497 // this module.
2498 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2499
2500 // Introduce the local -> global mapping for preprocessed entities in
2501 // this module.
2502 F.PreprocessedEntityRemap.insert(
2503 std::make_pair(LocalBasePreprocessedEntityID,
2504 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2505 }
2506
2507
Douglas Gregora863b4b2011-08-04 16:36:56 +00002508 if (F.LocalNumMacroDefinitions > 0) {
2509 // Introduce the global -> local mapping for macro definitions within
2510 // this module.
2511 GlobalMacroDefinitionMap.insert(
2512 std::make_pair(getTotalNumMacroDefinitions() + 1, &F));
2513
2514 // Introduce the local -> global mapping for macro definitions within
2515 // this module.
2516 F.MacroDefinitionRemap.insert(
2517 std::make_pair(LocalBaseMacroID,
2518 F.BaseMacroDefinitionID - LocalBaseMacroID));
2519
2520 MacroDefinitionsLoaded.resize(
Douglas Gregor270e0142011-07-20 01:29:15 +00002521 MacroDefinitionsLoaded.size() + F.LocalNumMacroDefinitions);
Douglas Gregora863b4b2011-08-04 16:36:56 +00002522 }
2523
Douglas Gregoraae92242010-03-19 21:51:54 +00002524 break;
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002525 }
2526
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00002527 case DECL_UPDATE_OFFSETS: {
2528 if (Record.size() % 2 != 0) {
2529 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2530 return Failure;
2531 }
2532 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
Douglas Gregorf7180622011-08-03 15:48:04 +00002533 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2534 .push_back(std::make_pair(&F, Record[I+1]));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00002535 break;
2536 }
2537
Sebastian Redl539c5062010-08-18 23:57:32 +00002538 case DECL_REPLACEMENTS: {
Sebastian Redle7c1fe62010-08-13 00:28:03 +00002539 if (Record.size() % 2 != 0) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002540 Error("invalid DECL_REPLACEMENTS block in AST file");
Sebastian Redle7c1fe62010-08-13 00:28:03 +00002541 return Failure;
2542 }
2543 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
Douglas Gregorf7180622011-08-03 15:48:04 +00002544 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2545 = std::make_pair(&F, Record[I+1]);
Sebastian Redle7c1fe62010-08-13 00:28:03 +00002546 break;
2547 }
Douglas Gregord4c5ed02010-10-29 22:39:52 +00002548
2549 case CXX_BASE_SPECIFIER_OFFSETS: {
2550 if (F.LocalNumCXXBaseSpecifiers != 0) {
2551 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2552 return Failure;
2553 }
2554
2555 F.LocalNumCXXBaseSpecifiers = Record[0];
2556 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
Jonathan D. Turner3766fdb2011-07-21 21:15:19 +00002557 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00002558 break;
2559 }
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002560
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002561 case DIAG_PRAGMA_MAPPINGS:
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002562 if (Record.size() % 2 != 0) {
2563 Error("invalid DIAG_USER_MAPPINGS block in AST file");
2564 return Failure;
2565 }
Douglas Gregor925296b2011-07-19 16:10:42 +00002566
2567 if (F.PragmaDiagMappings.empty())
2568 F.PragmaDiagMappings.swap(Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002569 else
Douglas Gregor925296b2011-07-19 16:10:42 +00002570 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2571 Record.begin(), Record.end());
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002572 break;
Douglas Gregor09b69892011-02-10 17:09:37 +00002573
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00002574 case CUDA_SPECIAL_DECL_REFS:
2575 // Later tables overwrite earlier ones.
Douglas Gregor7fb09192011-07-21 22:35:25 +00002576 // FIXME: Modules will have trouble with this.
2577 CUDASpecialDeclRefs.clear();
2578 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2579 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00002580 break;
Douglas Gregor09b69892011-02-10 17:09:37 +00002581
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002582 case HEADER_SEARCH_TABLE: {
Douglas Gregor09b69892011-02-10 17:09:37 +00002583 F.HeaderFileInfoTableData = BlobStart;
2584 F.LocalNumHeaderFileInfos = Record[1];
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002585 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
Douglas Gregor09b69892011-02-10 17:09:37 +00002586 if (Record[0]) {
2587 F.HeaderFileInfoTable
2588 = HeaderFileInfoLookupTable::Create(
2589 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002590 (const unsigned char *)F.HeaderFileInfoTableData,
Douglas Gregora3e41532011-07-28 20:55:49 +00002591 HeaderFileInfoTrait(*this, F,
2592 PP? &PP->getHeaderSearchInfo() : 0,
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002593 BlobStart + Record[2]));
Douglas Gregor09b69892011-02-10 17:09:37 +00002594 if (PP)
2595 PP->getHeaderSearchInfo().SetExternalSource(this);
2596 }
2597 break;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002598 }
2599
Peter Collingbourne5df20e02011-02-15 19:46:30 +00002600 case FP_PRAGMA_OPTIONS:
2601 // Later tables overwrite earlier ones.
2602 FPPragmaOptions.swap(Record);
2603 break;
2604
2605 case OPENCL_EXTENSIONS:
2606 // Later tables overwrite earlier ones.
2607 OpenCLExtensions.swap(Record);
2608 break;
Alexis Hunt27a761d2011-05-04 23:29:54 +00002609
2610 case TENTATIVE_DEFINITIONS:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002611 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2612 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Alexis Hunt27a761d2011-05-04 23:29:54 +00002613 break;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002614
2615 case KNOWN_NAMESPACES:
Douglas Gregor7fb09192011-07-21 22:35:25 +00002616 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2617 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002618 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002619 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00002620 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002621 }
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002622 Error("premature end of bitstream in AST file");
Douglas Gregor55abb232009-04-10 20:39:37 +00002623 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002624}
2625
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002626ASTReader::ASTReadResult ASTReader::validateFileEntries() {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00002627 for (ModuleIterator I = ModuleMgr.begin(),
2628 E = ModuleMgr.end(); I != E; ++I) {
2629 Module *F = *I;
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002630 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
2631
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00002632 for (unsigned i = 0, e = F->LocalNumSLocFileEntries; i != e; ++i) {
2633 SLocEntryCursor.JumpToBit(F->SLocFileOffsets[i]);
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002634 unsigned Code = SLocEntryCursor.ReadCode();
2635 if (Code == llvm::bitc::END_BLOCK ||
2636 Code == llvm::bitc::ENTER_SUBBLOCK ||
2637 Code == llvm::bitc::DEFINE_ABBREV) {
2638 Error("incorrectly-formatted source location entry in AST file");
2639 return Failure;
2640 }
2641
2642 RecordData Record;
2643 const char *BlobStart;
2644 unsigned BlobLen;
2645 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
2646 default:
2647 Error("incorrectly-formatted source location entry in AST file");
2648 return Failure;
2649
2650 case SM_SLOC_FILE_ENTRY: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002651 StringRef Filename(BlobStart, BlobLen);
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002652 const FileEntry *File = getFileEntry(Filename);
2653
2654 if (File == 0) {
2655 std::string ErrorStr = "could not find file '";
2656 ErrorStr += Filename;
2657 ErrorStr += "' referenced by AST file";
2658 Error(ErrorStr.c_str());
2659 return IgnorePCH;
2660 }
2661
2662 if (Record.size() < 6) {
2663 Error("source location entry is incorrect");
2664 return Failure;
2665 }
2666
2667 // The stat info from the FileEntry came from the cached stat
2668 // info of the PCH, so we cannot trust it.
2669 struct stat StatBuf;
2670 if (::stat(File->getName(), &StatBuf) != 0) {
2671 StatBuf.st_size = File->getSize();
2672 StatBuf.st_mtime = File->getModificationTime();
2673 }
2674
2675 if (((off_t)Record[4] != StatBuf.st_size
2676#if !defined(LLVM_ON_WIN32)
2677 // In our regression testing, the Windows file system seems to
2678 // have inconsistent modification times that sometimes
2679 // erroneously trigger this error-handling path.
2680 || (time_t)Record[5] != StatBuf.st_mtime
2681#endif
2682 )) {
2683 Error(diag::err_fe_pch_file_modified, Filename);
2684 return IgnorePCH;
2685 }
2686
2687 break;
2688 }
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002689 }
2690 }
2691 }
2692
2693 return Success;
2694}
2695
Sebastian Redl009e7f22010-10-05 16:15:19 +00002696ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
Douglas Gregora6895d82011-07-22 16:00:58 +00002697 ModuleKind Type) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00002698 switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00002699 case Failure: return Failure;
2700 case IgnorePCH: return IgnorePCH;
2701 case Success: break;
2702 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002703
2704 // Here comes stuff that we only do once the entire chain is loaded.
2705
Argyrios Kyrtzidis460132d2011-06-01 05:43:53 +00002706 if (!DisableValidation) {
2707 switch(validateFileEntries()) {
2708 case Failure: return Failure;
2709 case IgnorePCH: return IgnorePCH;
2710 case Success: break;
2711 }
2712 }
2713
Sebastian Redl96371b42010-09-22 00:42:30 +00002714 // Preload SLocEntries.
2715 for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) {
2716 ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]);
2717 if (Result != Success)
Douglas Gregor925296b2011-07-19 16:10:42 +00002718 return Failure;
Sebastian Redl96371b42010-09-22 00:42:30 +00002719 }
Douglas Gregor49bf76b2011-07-21 18:46:38 +00002720 PreloadSLocEntries.clear();
2721
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002722 // Check the predefines buffers.
Douglas Gregor9125bd62011-07-27 16:30:06 +00002723 if (!DisableValidation && Type != MK_Module && CheckPredefinesBuffers())
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002724 return IgnorePCH;
2725
2726 if (PP) {
2727 // Initialization of keywords and pragmas occurs before the
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002728 // AST file is read, so there may be some identifiers that were
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002729 // loaded into the IdentifierTable before we intercepted the
2730 // creation of identifiers. Iterate through the list of known
2731 // identifiers and determine whether we have to establish
2732 // preprocessor definitions or top-level identifier declaration
2733 // chains for those identifiers.
2734 //
2735 // We copy the IdentifierInfo pointers to a small vector first,
2736 // since de-serializing declarations or macro definitions can add
2737 // new entries into the identifier table, invalidating the
2738 // iterators.
Douglas Gregor9125bd62011-07-27 16:30:06 +00002739 //
2740 // FIXME: We need a lazier way to load this information, e.g., by marking
2741 // the identifier data as 'dirty', so that it will be looked up in the
2742 // AST file(s) if it is uttered in the source. This could save us some
2743 // module load time.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002744 SmallVector<IdentifierInfo *, 128> Identifiers;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002745 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
2746 IdEnd = PP->getIdentifierTable().end();
2747 Id != IdEnd; ++Id)
2748 Identifiers.push_back(Id->second);
Sebastian Redlfa061442010-07-21 20:07:32 +00002749 // We need to search the tables in all files.
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00002750 for (ModuleIterator J = ModuleMgr.begin(),
2751 M = ModuleMgr.end(); J != M; ++J) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002752 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00002753 = (ASTIdentifierLookupTable *)(*J)->IdentifierLookupTable;
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002754 // Not all AST files necessarily have identifier tables, only the useful
Sebastian Redl5c415f32010-07-22 17:01:13 +00002755 // ones.
2756 if (!IdTable)
2757 continue;
Sebastian Redlfa061442010-07-21 20:07:32 +00002758 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2759 IdentifierInfo *II = Identifiers[I];
2760 // Look in the on-disk hash tables for an entry for this identifier
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00002761 ASTIdentifierLookupTrait Info(*this, *(*J), II);
Sebastian Redlfa061442010-07-21 20:07:32 +00002762 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002763 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
Sebastian Redlb293a452010-07-20 21:20:32 +00002764 if (Pos == IdTable->end())
2765 continue;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002766
Sebastian Redlb293a452010-07-20 21:20:32 +00002767 // Dereferencing the iterator has the effect of populating the
2768 // IdentifierInfo node with the various declarations it needs.
2769 (void)*Pos;
2770 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002771 }
2772 }
2773
2774 if (Context)
2775 InitializeContext(*Context);
2776
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00002777 if (DeserializationListener)
2778 DeserializationListener->ReaderInitialized(this);
2779
Douglas Gregor936a5b42010-11-30 05:23:00 +00002780 // If this AST file is a precompiled preamble, then set the main file ID of
2781 // the source manager to the file source file from which the preamble was
2782 // built. This is the only valid way to use a precompiled preamble.
Douglas Gregora6895d82011-07-22 16:00:58 +00002783 if (Type == MK_Preamble) {
Douglas Gregora3b20262011-05-06 21:43:30 +00002784 if (OriginalFileID.isInvalid()) {
2785 SourceLocation Loc
2786 = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1);
2787 if (Loc.isValid())
2788 OriginalFileID = SourceMgr.getDecomposedLoc(Loc).first;
Douglas Gregor936a5b42010-11-30 05:23:00 +00002789 }
Douglas Gregor925296b2011-07-19 16:10:42 +00002790 else {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00002791 OriginalFileID = FileID::get(ModuleMgr.getPrimaryModule().SLocEntryBaseID
Douglas Gregor925296b2011-07-19 16:10:42 +00002792 + OriginalFileID.getOpaqueValue() - 1);
2793 }
2794
Douglas Gregora3b20262011-05-06 21:43:30 +00002795 if (!OriginalFileID.isInvalid())
2796 SourceMgr.SetPreambleFileID(OriginalFileID);
Douglas Gregor936a5b42010-11-30 05:23:00 +00002797 }
2798
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002799 return Success;
2800}
2801
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002802ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
Douglas Gregordf0c1512011-08-18 04:12:04 +00002803 ModuleKind Type,
2804 Module *ImportedBy) {
Douglas Gregor4dd3e942011-08-19 02:29:29 +00002805 Module *M;
2806 bool NewModule;
2807 std::string ErrorStr;
2808 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
2809 ErrorStr);
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002810
Douglas Gregor4dd3e942011-08-19 02:29:29 +00002811 if (!M) {
2812 // We couldn't load the module.
2813 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2814 + ErrorStr;
2815 Error(Msg);
2816 return Failure;
2817 }
2818
2819 if (!NewModule) {
2820 // We've already loaded this module.
2821 return Success;
2822 }
2823
2824 // FIXME: This seems rather a hack. Should CurrentDir be part of the
2825 // module?
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002826 if (FileName != "-") {
2827 CurrentDir = llvm::sys::path::parent_path(FileName);
2828 if (CurrentDir.empty()) CurrentDir = ".";
2829 }
2830
Douglas Gregor4dd3e942011-08-19 02:29:29 +00002831 Module &F = *M;
Sebastian Redl34522812010-07-16 17:50:48 +00002832 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002833 Stream.init(F.StreamFile);
Sebastian Redlfa061442010-07-21 20:07:32 +00002834 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Douglas Gregord32f0352011-07-22 06:10:01 +00002835
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00002836 // Sniff for the signature.
2837 if (Stream.Read(8) != 'C' ||
2838 Stream.Read(8) != 'P' ||
2839 Stream.Read(8) != 'C' ||
2840 Stream.Read(8) != 'H') {
2841 Diag(diag::err_not_a_pch_file) << FileName;
2842 return Failure;
2843 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002844
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002845 while (!Stream.AtEndOfStream()) {
2846 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00002847
Douglas Gregor92863e42009-04-10 23:10:45 +00002848 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002849 Error("invalid record at top-level of AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00002850 return Failure;
2851 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002852
2853 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002854
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002855 // We only know the AST subblock ID.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002856 switch (BlockID) {
2857 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00002858 if (Stream.ReadBlockInfoBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002859 Error("malformed BlockInfoBlock in AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00002860 return Failure;
2861 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002862 break;
Sebastian Redl539c5062010-08-18 23:57:32 +00002863 case AST_BLOCK_ID:
Sebastian Redl3e31c722010-08-18 23:56:56 +00002864 switch (ReadASTBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00002865 case Success:
2866 break;
2867
2868 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00002869 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00002870
2871 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00002872 // FIXME: We could consider reading through to the end of this
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002873 // AST block, skipping subblocks, to see if there are other
2874 // AST blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00002875
Douglas Gregor925296b2011-07-19 16:10:42 +00002876 // FIXME: We can't clear loaded slocentries anymore.
2877 //SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00002878
2879 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00002880 if (F.StatCache)
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002881 FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00002882
Douglas Gregor92863e42009-04-10 23:10:45 +00002883 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00002884 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002885 break;
2886 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00002887 if (Stream.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00002888 Error("malformed block record in AST file");
Douglas Gregor92863e42009-04-10 23:10:45 +00002889 return Failure;
2890 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002891 break;
2892 }
Mike Stump11289f42009-09-09 15:08:12 +00002893 }
Douglas Gregord32f0352011-07-22 06:10:01 +00002894
Douglas Gregora6895d82011-07-22 16:00:58 +00002895 // Once read, set the Module bit base offset and update the size in
Douglas Gregord32f0352011-07-22 06:10:01 +00002896 // bits of all files we've seen.
2897 F.GlobalBitOffset = TotalModulesSizeInBits;
2898 TotalModulesSizeInBits += F.SizeInBits;
2899 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Sebastian Redl2abc0382010-07-16 20:41:52 +00002900 return Success;
2901}
2902
Sebastian Redl2c499f62010-08-18 23:56:43 +00002903void ASTReader::setPreprocessor(Preprocessor &pp) {
Douglas Gregoraae92242010-03-19 21:51:54 +00002904 PP = &pp;
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002905
2906 if (unsigned N = getTotalNumPreprocessedEntities()) {
Douglas Gregoraae92242010-03-19 21:51:54 +00002907 if (!PP->getPreprocessingRecord())
Douglas Gregor998caea2011-05-06 16:33:08 +00002908 PP->createPreprocessingRecord(true);
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002909 PP->getPreprocessingRecord()->SetExternalSource(*this);
2910 PP->getPreprocessingRecord()->allocateLoadedEntities(N);
Douglas Gregoraae92242010-03-19 21:51:54 +00002911 }
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00002912
2913 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor49bf76b2011-07-21 18:46:38 +00002914 PP->getHeaderSearchInfo().SetExternalSource(this);
Douglas Gregoraae92242010-03-19 21:51:54 +00002915}
2916
Sebastian Redl2c499f62010-08-18 23:56:43 +00002917void ASTReader::InitializeContext(ASTContext &Ctx) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002918 Context = &Ctx;
2919 assert(Context && "Passed null context!");
2920
2921 assert(PP && "Forgot to set Preprocessor ?");
2922 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00002923 PP->setExternalSource(this);
Douglas Gregor09b69892011-02-10 17:09:37 +00002924
Douglas Gregor94619c82011-08-24 19:03:07 +00002925 // If we have any update blocks for the TU waiting, we have to add
2926 // them before we deserialize anything.
Douglas Gregordab42432011-08-12 00:15:20 +00002927 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Douglas Gregor94619c82011-08-24 19:03:07 +00002928 for (ModuleIterator M = ModuleMgr.begin(), MEnd = ModuleMgr.end();
2929 M != MEnd; ++M) {
2930 Module::DeclContextInfosMap::iterator DCU
2931 = (*M)->DeclContextInfos.find(0);
2932 if (DCU != (*M)->DeclContextInfos.end()) {
2933 // Insertion could invalidate map, so grab value first.
2934 DeclContextInfo Info = DCU->second;
2935 (*M)->DeclContextInfos.erase(DCU);
2936 (*M)->DeclContextInfos[TU] = Info;
2937 }
Douglas Gregoraa433012010-10-01 01:18:02 +00002938 }
Douglas Gregordab42432011-08-12 00:15:20 +00002939
2940 // If there's a listener, notify them that we "read" the translation unit.
2941 if (DeserializationListener)
2942 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, TU);
Douglas Gregoraa433012010-10-01 01:18:02 +00002943
Douglas Gregordab42432011-08-12 00:15:20 +00002944 // Make sure we load the declaration update records for the translation unit,
2945 // if there are any.
2946 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID, TU);
2947
2948 // Note that the translation unit has external lexical and visible storage.
2949 TU->setHasExternalLexicalStorage(true);
2950 TU->setHasExternalVisibleStorage(true);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002951
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002952 // FIXME: Find a better way to deal with collisions between these
2953 // built-in types. Right now, we just ignore the problem.
2954
2955 // Load the special types.
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00002956 if (Context->getBuiltinVaListType().isNull()) {
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00002957 Context->setBuiltinVaListType(
2958 GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002959 }
2960
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002961 if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) {
2962 if (Context->ObjCProtoType.isNull())
Douglas Gregor09c4aa82011-08-11 22:04:35 +00002963 Context->ObjCProtoType = GetType(Proto);
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002964 }
2965
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002966 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2967 if (!Context->CFConstantStringTypeDecl)
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00002968 Context->setCFConstantStringType(GetType(String));
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002969 }
2970
2971 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2972 QualType FileType = GetType(File);
2973 if (FileType.isNull()) {
2974 Error("FILE type is NULL");
2975 return;
2976 }
2977
2978 if (!Context->FILEDecl) {
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00002979 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2980 Context->setFILEDecl(Typedef->getDecl());
2981 else {
2982 const TagType *Tag = FileType->getAs<TagType>();
2983 if (!Tag) {
2984 Error("Invalid FILE type in AST file");
2985 return;
2986 }
2987 Context->setFILEDecl(Tag->getDecl());
2988 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002989 }
Douglas Gregoraa8a8272011-08-11 22:18:49 +00002990 }
2991
2992 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2993 QualType Jmp_bufType = GetType(Jmp_buf);
2994 if (Jmp_bufType.isNull()) {
2995 Error("jmp_buf type is NULL");
2996 return;
2997 }
2998
2999 if (!Context->jmp_bufDecl) {
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00003000 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3001 Context->setjmp_bufDecl(Typedef->getDecl());
3002 else {
3003 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3004 if (!Tag) {
3005 Error("Invalid jmp_buf type in AST file");
3006 return;
3007 }
3008 Context->setjmp_bufDecl(Tag->getDecl());
3009 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00003010 }
Douglas Gregoraa8a8272011-08-11 22:18:49 +00003011 }
3012
3013 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
3014 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3015 if (Sigjmp_bufType.isNull()) {
3016 Error("sigjmp_buf type is NULL");
3017 return;
3018 }
3019
3020 if (!Context->sigjmp_bufDecl) {
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00003021 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3022 Context->setsigjmp_bufDecl(Typedef->getDecl());
3023 else {
3024 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3025 assert(Tag && "Invalid sigjmp_buf type in AST file");
3026 Context->setsigjmp_bufDecl(Tag->getDecl());
3027 }
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003028 }
Jonathan D. Turnerf07f1312011-08-05 23:07:10 +00003029 }
Richard Smith02e85f32011-04-14 22:09:26 +00003030
Douglas Gregoraa8a8272011-08-11 22:18:49 +00003031 if (unsigned ObjCIdRedef
3032 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3033 if (Context->ObjCIdRedefinitionType.isNull())
3034 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3035 }
3036
3037 if (unsigned ObjCClassRedef
3038 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3039 if (Context->ObjCClassRedefinitionType.isNull())
3040 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3041 }
3042
3043 if (unsigned ObjCSelRedef
3044 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3045 if (Context->ObjCSelRedefinitionType.isNull())
3046 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3047 }
3048
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003049 ReadPragmaDiagnosticMappings(Context->getDiagnostics());
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00003050
3051 // If there were any CUDA special declarations, deserialize them.
3052 if (!CUDASpecialDeclRefs.empty()) {
3053 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3054 Context->setcudaConfigureCallDecl(
3055 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3056 }
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003057}
3058
Douglas Gregor45fe0362009-05-12 01:31:05 +00003059/// \brief Retrieve the name of the original source file name
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003060/// directly from the AST file, without actually loading the AST
Douglas Gregor45fe0362009-05-12 01:31:05 +00003061/// file.
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003062std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00003063 FileManager &FileMgr,
Daniel Dunbar3b951482009-12-03 09:13:06 +00003064 Diagnostic &Diags) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003065 // Open the AST file.
Douglas Gregor45fe0362009-05-12 01:31:05 +00003066 std::string ErrStr;
3067 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
Chris Lattner5159f612010-11-23 08:35:12 +00003068 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
Douglas Gregor45fe0362009-05-12 01:31:05 +00003069 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00003070 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00003071 return std::string();
3072 }
3073
3074 // Initialize the stream
3075 llvm::BitstreamReader StreamFile;
3076 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00003077 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00003078 (const unsigned char *)Buffer->getBufferEnd());
3079 Stream.init(StreamFile);
3080
3081 // Sniff for the signature.
3082 if (Stream.Read(8) != 'C' ||
3083 Stream.Read(8) != 'P' ||
3084 Stream.Read(8) != 'C' ||
3085 Stream.Read(8) != 'H') {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003086 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00003087 return std::string();
3088 }
3089
3090 RecordData Record;
3091 while (!Stream.AtEndOfStream()) {
3092 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00003093
Douglas Gregor45fe0362009-05-12 01:31:05 +00003094 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3095 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00003096
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003097 // We only know the AST subblock ID.
Douglas Gregor45fe0362009-05-12 01:31:05 +00003098 switch (BlockID) {
Sebastian Redl539c5062010-08-18 23:57:32 +00003099 case AST_BLOCK_ID:
3100 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003101 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00003102 return std::string();
3103 }
3104 break;
Mike Stump11289f42009-09-09 15:08:12 +00003105
Douglas Gregor45fe0362009-05-12 01:31:05 +00003106 default:
3107 if (Stream.SkipBlock()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003108 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00003109 return std::string();
3110 }
3111 break;
3112 }
3113 continue;
3114 }
3115
3116 if (Code == llvm::bitc::END_BLOCK) {
3117 if (Stream.ReadBlockEnd()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003118 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00003119 return std::string();
3120 }
3121 continue;
3122 }
3123
3124 if (Code == llvm::bitc::DEFINE_ABBREV) {
3125 Stream.ReadAbbrevRecord();
3126 continue;
3127 }
3128
3129 Record.clear();
3130 const char *BlobStart = 0;
3131 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003132 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Sebastian Redl539c5062010-08-18 23:57:32 +00003133 == ORIGINAL_FILE_NAME)
Douglas Gregor45fe0362009-05-12 01:31:05 +00003134 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00003135 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00003136
3137 return std::string();
3138}
3139
Douglas Gregor55abb232009-04-10 20:39:37 +00003140/// \brief Parse the record that corresponds to a LangOptions data
3141/// structure.
3142///
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003143/// This routine parses the language options from the AST file and then gives
3144/// them to the AST listener if one is set.
Douglas Gregor55abb232009-04-10 20:39:37 +00003145///
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003146/// \returns true if the listener deems the file unacceptable, false otherwise.
Sebastian Redl2c499f62010-08-18 23:56:43 +00003147bool ASTReader::ParseLanguageOptions(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003148 const SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003149 if (Listener) {
3150 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00003151
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003152 #define PARSE_LANGOPT(Option) \
3153 LangOpts.Option = Record[Idx]; \
3154 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00003155
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003156 unsigned Idx = 0;
3157 PARSE_LANGOPT(Trigraphs);
3158 PARSE_LANGOPT(BCPLComment);
3159 PARSE_LANGOPT(DollarIdents);
3160 PARSE_LANGOPT(AsmPreprocessor);
3161 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00003162 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003163 PARSE_LANGOPT(ImplicitInt);
3164 PARSE_LANGOPT(Digraphs);
3165 PARSE_LANGOPT(HexFloats);
3166 PARSE_LANGOPT(C99);
Peter Collingbournea686b5f2011-04-15 00:35:23 +00003167 PARSE_LANGOPT(C1X);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003168 PARSE_LANGOPT(Microsoft);
3169 PARSE_LANGOPT(CPlusPlus);
3170 PARSE_LANGOPT(CPlusPlus0x);
3171 PARSE_LANGOPT(CXXOperatorNames);
3172 PARSE_LANGOPT(ObjC1);
3173 PARSE_LANGOPT(ObjC2);
3174 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00003175 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian13f3b2f2011-01-07 18:59:25 +00003176 PARSE_LANGOPT(AppleKext);
Ted Kremenek1d56c9e2010-12-23 21:35:43 +00003177 PARSE_LANGOPT(ObjCDefaultSynthProperties);
Douglas Gregora860e6a2011-06-14 23:20:43 +00003178 PARSE_LANGOPT(ObjCInferRelatedResultType);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00003179 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003180 PARSE_LANGOPT(PascalStrings);
3181 PARSE_LANGOPT(WritableStrings);
3182 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00003183 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003184 PARSE_LANGOPT(Exceptions);
Anders Carlssonce8dd3a2011-02-19 23:53:54 +00003185 PARSE_LANGOPT(ObjCExceptions);
Anders Carlsson6bbd2682011-02-23 03:04:54 +00003186 PARSE_LANGOPT(CXXExceptions);
3187 PARSE_LANGOPT(SjLjExceptions);
Douglas Gregordbe39272011-02-01 15:15:22 +00003188 PARSE_LANGOPT(MSBitfields);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003189 PARSE_LANGOPT(NeXTRuntime);
3190 PARSE_LANGOPT(Freestanding);
3191 PARSE_LANGOPT(NoBuiltin);
3192 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00003193 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003194 PARSE_LANGOPT(Blocks);
3195 PARSE_LANGOPT(EmitAllDecls);
3196 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00003197 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
3198 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003199 PARSE_LANGOPT(HeinousExtensions);
3200 PARSE_LANGOPT(Optimize);
3201 PARSE_LANGOPT(OptimizeSize);
3202 PARSE_LANGOPT(Static);
3203 PARSE_LANGOPT(PICLevel);
3204 PARSE_LANGOPT(GNUInline);
3205 PARSE_LANGOPT(NoInline);
Chandler Carruth7ffce732011-04-23 20:05:38 +00003206 PARSE_LANGOPT(Deprecated);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003207 PARSE_LANGOPT(AccessControl);
3208 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00003209 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidisa88942a2011-01-15 02:56:16 +00003210 PARSE_LANGOPT(ShortEnums);
Chris Lattner51924e512010-06-26 21:25:03 +00003211 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
John McCall457a04e2010-10-22 21:05:15 +00003212 LangOpts.setVisibilityMode((Visibility)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00003213 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00003214 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003215 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00003216 PARSE_LANGOPT(OpenCL);
Peter Collingbourne546d0792010-12-01 19:14:57 +00003217 PARSE_LANGOPT(CUDA);
Mike Stumpd9546382009-12-12 01:27:46 +00003218 PARSE_LANGOPT(CatchUndefined);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003219 PARSE_LANGOPT(DefaultFPContract);
Roman Divackydc1f68d2011-03-01 17:36:40 +00003220 PARSE_LANGOPT(ElideConstructors);
3221 PARSE_LANGOPT(SpellChecking);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003222 PARSE_LANGOPT(MRTD);
John McCall31168b02011-06-15 23:02:42 +00003223 PARSE_LANGOPT(ObjCAutoRefCount);
Douglas Gregor49b236a2011-08-04 15:46:00 +00003224 PARSE_LANGOPT(ObjCInferRelatedReturnType);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003225 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00003226
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003227 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00003228 }
Douglas Gregor55abb232009-04-10 20:39:37 +00003229
3230 return false;
3231}
3232
Sebastian Redl2c499f62010-08-18 23:56:43 +00003233void ASTReader::ReadPreprocessedEntities() {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00003234 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3235 Module &F = *(*I);
Douglas Gregor92a96f52011-02-08 21:58:10 +00003236 if (!F.PreprocessorDetailCursor.getBitStreamReader())
3237 continue;
3238
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00003239 SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
Douglas Gregor92a96f52011-02-08 21:58:10 +00003240 F.PreprocessorDetailCursor.JumpToBit(F.PreprocessorDetailStartOffset);
3241 while (LoadPreprocessedEntity(F)) { }
3242 }
Douglas Gregoraae92242010-03-19 21:51:54 +00003243}
3244
Douglas Gregor46c50012011-02-11 19:46:30 +00003245PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) {
Douglas Gregord32f0352011-07-22 06:10:01 +00003246 RecordLocation Loc = getLocalBitOffset(Offset);
Douglas Gregorf88e35b2010-11-30 06:16:57 +00003247
Douglas Gregor92a96f52011-02-08 21:58:10 +00003248 // Keep track of where we are in the stream, then jump back there
3249 // after reading this entity.
Douglas Gregord32f0352011-07-22 06:10:01 +00003250 SavedStreamPosition SavedPosition(Loc.F->PreprocessorDetailCursor);
3251 Loc.F->PreprocessorDetailCursor.JumpToBit(Loc.Offset);
3252 return LoadPreprocessedEntity(*Loc.F);
Douglas Gregorf88e35b2010-11-30 06:16:57 +00003253}
3254
Douglas Gregor09b69892011-02-10 17:09:37 +00003255HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00003256 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3257 Module &F = *(*I);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00003258
Douglas Gregora3e41532011-07-28 20:55:49 +00003259 HeaderFileInfoTrait Trait(*this, F, &PP->getHeaderSearchInfo(),
Douglas Gregor4b123cb2011-07-28 04:50:02 +00003260 F.HeaderFileFrameworkStrings,
3261 FE->getName());
3262
Douglas Gregor09b69892011-02-10 17:09:37 +00003263 HeaderFileInfoLookupTable *Table
3264 = static_cast<HeaderFileInfoLookupTable *>(F.HeaderFileInfoTable);
3265 if (!Table)
3266 continue;
3267
3268 // Look in the on-disk hash table for an entry for this file name.
3269 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE->getName(),
3270 &Trait);
3271 if (Pos == Table->end())
3272 continue;
3273
3274 HeaderFileInfo HFI = *Pos;
3275 if (Listener)
3276 Listener->ReadHeaderFileInfo(HFI, FE->getUID());
3277
3278 return HFI;
3279 }
3280
3281 return HeaderFileInfo();
3282}
3283
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003284void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00003285 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3286 Module &F = *(*I);
Douglas Gregor925296b2011-07-19 16:10:42 +00003287 unsigned Idx = 0;
3288 while (Idx < F.PragmaDiagMappings.size()) {
3289 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
3290 while (1) {
3291 assert(Idx < F.PragmaDiagMappings.size() &&
3292 "Invalid data, didn't find '-1' marking end of diag/map pairs");
3293 if (Idx >= F.PragmaDiagMappings.size()) {
3294 break; // Something is messed up but at least avoid infinite loop in
3295 // release build.
3296 }
3297 unsigned DiagID = F.PragmaDiagMappings[Idx++];
3298 if (DiagID == (unsigned)-1) {
3299 break; // no more diag/map pairs for this location.
3300 }
3301 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
3302 Diag.setDiagnosticMapping(DiagID, Map, Loc);
3303 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003304 }
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003305 }
3306}
3307
Sebastian Redl837a6cb2010-07-20 22:37:49 +00003308/// \brief Get the correct cursor and offset for loading a type.
Sebastian Redl2c499f62010-08-18 23:56:43 +00003309ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
Douglas Gregor5204bde2011-08-02 16:26:37 +00003310 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
Jonathan D. Turner35005682011-07-20 21:31:32 +00003311 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
Douglas Gregor8ab4ea82011-07-29 00:21:44 +00003312 Module *M = I->second;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003313 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
Sebastian Redl837a6cb2010-07-20 22:37:49 +00003314}
3315
3316/// \brief Read and return the type with the given index..
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003317///
Sebastian Redl837a6cb2010-07-20 22:37:49 +00003318/// The index is the type ID, shifted and minus the number of predefs. This
3319/// routine actually reads the record corresponding to the type at the given
3320/// location. It is a helper routine for GetType, which deals with reading type
3321/// IDs.
Douglas Gregor903b7e92011-07-22 00:38:23 +00003322QualType ASTReader::readTypeRecord(unsigned Index) {
Sebastian Redl837a6cb2010-07-20 22:37:49 +00003323 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl2c373b92010-10-05 15:59:54 +00003324 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00003325
Douglas Gregorfeb84b02009-04-14 21:18:50 +00003326 // Keep track of where we are in the stream, then jump back there
3327 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00003328 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00003329
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00003330 ReadingKindTracker ReadingKind(Read_Type, *this);
Sebastian Redleaa4ade2010-08-11 18:52:41 +00003331
Douglas Gregor1342e842009-07-06 18:54:52 +00003332 // Note that we are loading a type record.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003333 Deserializing AType(this);
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregor903b7e92011-07-22 00:38:23 +00003335 unsigned Idx = 0;
Sebastian Redl2c373b92010-10-05 15:59:54 +00003336 DeclsCursor.JumpToBit(Loc.Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003337 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00003338 unsigned Code = DeclsCursor.ReadCode();
Sebastian Redl539c5062010-08-18 23:57:32 +00003339 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
3340 case TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003341 if (Record.size() != 2) {
3342 Error("Incorrect encoding of extended qualifier type");
3343 return QualType();
3344 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003345 QualType Base = readType(*Loc.F, Record, Idx);
3346 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
John McCall8ccfcb52009-09-24 19:53:00 +00003347 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00003348 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003349
Sebastian Redl539c5062010-08-18 23:57:32 +00003350 case TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003351 if (Record.size() != 1) {
3352 Error("Incorrect encoding of complex type");
3353 return QualType();
3354 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003355 QualType ElemType = readType(*Loc.F, Record, Idx);
Chris Lattner8575daa2009-04-27 21:45:14 +00003356 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003357 }
3358
Sebastian Redl539c5062010-08-18 23:57:32 +00003359 case TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003360 if (Record.size() != 1) {
3361 Error("Incorrect encoding of pointer type");
3362 return QualType();
3363 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003364 QualType PointeeType = readType(*Loc.F, Record, Idx);
Chris Lattner8575daa2009-04-27 21:45:14 +00003365 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003366 }
3367
Sebastian Redl539c5062010-08-18 23:57:32 +00003368 case TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003369 if (Record.size() != 1) {
3370 Error("Incorrect encoding of block pointer type");
3371 return QualType();
3372 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003373 QualType PointeeType = readType(*Loc.F, Record, Idx);
Chris Lattner8575daa2009-04-27 21:45:14 +00003374 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003375 }
3376
Sebastian Redl539c5062010-08-18 23:57:32 +00003377 case TYPE_LVALUE_REFERENCE: {
Richard Smith0f538462011-04-12 10:38:03 +00003378 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003379 Error("Incorrect encoding of lvalue reference type");
3380 return QualType();
3381 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003382 QualType PointeeType = readType(*Loc.F, Record, Idx);
Richard Smith0f538462011-04-12 10:38:03 +00003383 return Context->getLValueReferenceType(PointeeType, Record[1]);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003384 }
3385
Sebastian Redl539c5062010-08-18 23:57:32 +00003386 case TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003387 if (Record.size() != 1) {
3388 Error("Incorrect encoding of rvalue reference type");
3389 return QualType();
3390 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003391 QualType PointeeType = readType(*Loc.F, Record, Idx);
Chris Lattner8575daa2009-04-27 21:45:14 +00003392 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003393 }
3394
Sebastian Redl539c5062010-08-18 23:57:32 +00003395 case TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00003396 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003397 Error("Incorrect encoding of member pointer type");
3398 return QualType();
3399 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003400 QualType PointeeType = readType(*Loc.F, Record, Idx);
3401 QualType ClassType = readType(*Loc.F, Record, Idx);
Douglas Gregor0cdc8322010-12-10 17:03:06 +00003402 if (PointeeType.isNull() || ClassType.isNull())
3403 return QualType();
3404
Chris Lattner8575daa2009-04-27 21:45:14 +00003405 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003406 }
3407
Sebastian Redl539c5062010-08-18 23:57:32 +00003408 case TYPE_CONSTANT_ARRAY: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003409 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003410 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3411 unsigned IndexTypeQuals = Record[2];
3412 unsigned Idx = 3;
3413 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00003414 return Context->getConstantArrayType(ElementType, Size,
3415 ASM, IndexTypeQuals);
3416 }
3417
Sebastian Redl539c5062010-08-18 23:57:32 +00003418 case TYPE_INCOMPLETE_ARRAY: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003419 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003420 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3421 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00003422 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003423 }
3424
Sebastian Redl539c5062010-08-18 23:57:32 +00003425 case TYPE_VARIABLE_ARRAY: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003426 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00003427 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3428 unsigned IndexTypeQuals = Record[2];
Sebastian Redl2c373b92010-10-05 15:59:54 +00003429 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3430 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3431 return Context->getVariableArrayType(ElementType, ReadExpr(*Loc.F),
Douglas Gregor04318252009-07-06 15:59:29 +00003432 ASM, IndexTypeQuals,
3433 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003434 }
3435
Sebastian Redl539c5062010-08-18 23:57:32 +00003436 case TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00003437 if (Record.size() != 3) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003438 Error("incorrect encoding of vector type in AST file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003439 return QualType();
3440 }
3441
Douglas Gregor903b7e92011-07-22 00:38:23 +00003442 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003443 unsigned NumElements = Record[1];
Bob Wilsonaeb56442010-11-10 21:56:12 +00003444 unsigned VecKind = Record[2];
Chris Lattner37141f42010-06-23 06:00:24 +00003445 return Context->getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003446 (VectorType::VectorKind)VecKind);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003447 }
3448
Sebastian Redl539c5062010-08-18 23:57:32 +00003449 case TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00003450 if (Record.size() != 3) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003451 Error("incorrect encoding of extended vector type in AST file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003452 return QualType();
3453 }
3454
Douglas Gregor903b7e92011-07-22 00:38:23 +00003455 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003456 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00003457 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003458 }
3459
Sebastian Redl539c5062010-08-18 23:57:32 +00003460 case TYPE_FUNCTION_NO_PROTO: {
John McCall31168b02011-06-15 23:02:42 +00003461 if (Record.size() != 6) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003462 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003463 return QualType();
3464 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003465 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCall31168b02011-06-15 23:02:42 +00003466 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
3467 (CallingConv)Record[4], Record[5]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003468 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003469 }
3470
Sebastian Redl539c5062010-08-18 23:57:32 +00003471 case TYPE_FUNCTION_PROTO: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003472 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCalldb40c7f2010-12-14 08:05:40 +00003473
3474 FunctionProtoType::ExtProtoInfo EPI;
3475 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
Eli Friedmanc5b20b52011-04-09 08:18:08 +00003476 /*hasregparm*/ Record[2],
3477 /*regparm*/ Record[3],
John McCall31168b02011-06-15 23:02:42 +00003478 static_cast<CallingConv>(Record[4]),
3479 /*produces*/ Record[5]);
John McCalldb40c7f2010-12-14 08:05:40 +00003480
John McCall31168b02011-06-15 23:02:42 +00003481 unsigned Idx = 6;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003482 unsigned NumParams = Record[Idx++];
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003483 SmallVector<QualType, 16> ParamTypes;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003484 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor903b7e92011-07-22 00:38:23 +00003485 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
John McCalldb40c7f2010-12-14 08:05:40 +00003486
3487 EPI.Variadic = Record[Idx++];
3488 EPI.TypeQuals = Record[Idx++];
Douglas Gregordb9d6642011-01-26 05:01:58 +00003489 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003490 ExceptionSpecificationType EST =
3491 static_cast<ExceptionSpecificationType>(Record[Idx++]);
3492 EPI.ExceptionSpecType = EST;
3493 if (EST == EST_Dynamic) {
3494 EPI.NumExceptions = Record[Idx++];
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003495 SmallVector<QualType, 2> Exceptions;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003496 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
Douglas Gregor903b7e92011-07-22 00:38:23 +00003497 Exceptions.push_back(readType(*Loc.F, Record, Idx));
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003498 EPI.Exceptions = Exceptions.data();
3499 } else if (EST == EST_ComputedNoexcept) {
3500 EPI.NoexceptExpr = ReadExpr(*Loc.F);
3501 }
Jay Foad7d0479f2009-05-21 09:52:38 +00003502 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
John McCalldb40c7f2010-12-14 08:05:40 +00003503 EPI);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003504 }
3505
Douglas Gregor7fb09192011-07-21 22:35:25 +00003506 case TYPE_UNRESOLVED_USING: {
3507 unsigned Idx = 0;
John McCallb96ec562009-12-04 22:46:56 +00003508 return Context->getTypeDeclType(
Douglas Gregor7fb09192011-07-21 22:35:25 +00003509 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
3510 }
3511
Sebastian Redl539c5062010-08-18 23:57:32 +00003512 case TYPE_TYPEDEF: {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003513 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003514 Error("incorrect encoding of typedef type");
3515 return QualType();
3516 }
Douglas Gregor7fb09192011-07-21 22:35:25 +00003517 unsigned Idx = 0;
3518 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00003519 QualType Canonical = readType(*Loc.F, Record, Idx);
Douglas Gregorf86c9392010-10-26 00:51:02 +00003520 if (!Canonical.isNull())
3521 Canonical = Context->getCanonicalType(Canonical);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003522 return Context->getTypedefType(Decl, Canonical);
3523 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003524
Sebastian Redl539c5062010-08-18 23:57:32 +00003525 case TYPE_TYPEOF_EXPR:
Sebastian Redl2c373b92010-10-05 15:59:54 +00003526 return Context->getTypeOfExprType(ReadExpr(*Loc.F));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003527
Sebastian Redl539c5062010-08-18 23:57:32 +00003528 case TYPE_TYPEOF: {
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003529 if (Record.size() != 1) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003530 Error("incorrect encoding of typeof(type) in AST file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003531 return QualType();
3532 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003533 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Chris Lattner8575daa2009-04-27 21:45:14 +00003534 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003535 }
Mike Stump11289f42009-09-09 15:08:12 +00003536
Sebastian Redl539c5062010-08-18 23:57:32 +00003537 case TYPE_DECLTYPE:
Sebastian Redl2c373b92010-10-05 15:59:54 +00003538 return Context->getDecltypeType(ReadExpr(*Loc.F));
Anders Carlsson81df7b82009-06-24 19:06:50 +00003539
Alexis Hunte852b102011-05-24 22:41:36 +00003540 case TYPE_UNARY_TRANSFORM: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003541 QualType BaseType = readType(*Loc.F, Record, Idx);
3542 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Alexis Hunte852b102011-05-24 22:41:36 +00003543 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
3544 return Context->getUnaryTransformType(BaseType, UnderlyingType, UKind);
3545 }
3546
Richard Smith30482bc2011-02-20 03:19:35 +00003547 case TYPE_AUTO:
Douglas Gregor903b7e92011-07-22 00:38:23 +00003548 return Context->getAutoType(readType(*Loc.F, Record, Idx));
Richard Smith30482bc2011-02-20 03:19:35 +00003549
Sebastian Redl539c5062010-08-18 23:57:32 +00003550 case TYPE_RECORD: {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003551 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003552 Error("incorrect encoding of record type");
3553 return QualType();
3554 }
Douglas Gregor7fb09192011-07-21 22:35:25 +00003555 unsigned Idx = 0;
3556 bool IsDependent = Record[Idx++];
3557 QualType T
3558 = Context->getRecordType(ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx));
John McCall424cec92011-01-19 06:33:43 +00003559 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003560 return T;
3561 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003562
Sebastian Redl539c5062010-08-18 23:57:32 +00003563 case TYPE_ENUM: {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003564 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00003565 Error("incorrect encoding of enum type");
3566 return QualType();
3567 }
Douglas Gregor7fb09192011-07-21 22:35:25 +00003568 unsigned Idx = 0;
3569 bool IsDependent = Record[Idx++];
3570 QualType T
3571 = Context->getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
John McCall424cec92011-01-19 06:33:43 +00003572 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003573 return T;
3574 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00003575
John McCall81904512011-01-06 01:58:22 +00003576 case TYPE_ATTRIBUTED: {
3577 if (Record.size() != 3) {
3578 Error("incorrect encoding of attributed type");
3579 return QualType();
3580 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003581 QualType modifiedType = readType(*Loc.F, Record, Idx);
3582 QualType equivalentType = readType(*Loc.F, Record, Idx);
John McCall81904512011-01-06 01:58:22 +00003583 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3584 return Context->getAttributedType(kind, modifiedType, equivalentType);
3585 }
3586
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003587 case TYPE_PAREN: {
3588 if (Record.size() != 1) {
3589 Error("incorrect encoding of paren type");
3590 return QualType();
3591 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003592 QualType InnerType = readType(*Loc.F, Record, Idx);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003593 return Context->getParenType(InnerType);
3594 }
3595
Douglas Gregord2fa7662010-12-20 02:24:11 +00003596 case TYPE_PACK_EXPANSION: {
Douglas Gregor17328502011-02-01 15:24:58 +00003597 if (Record.size() != 2) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003598 Error("incorrect encoding of pack expansion type");
3599 return QualType();
3600 }
Douglas Gregor903b7e92011-07-22 00:38:23 +00003601 QualType Pattern = readType(*Loc.F, Record, Idx);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003602 if (Pattern.isNull())
3603 return QualType();
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003604 llvm::Optional<unsigned> NumExpansions;
3605 if (Record[1])
3606 NumExpansions = Record[1] - 1;
3607 return Context->getPackExpansionType(Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003608 }
3609
Sebastian Redl539c5062010-08-18 23:57:32 +00003610 case TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003611 unsigned Idx = 0;
3612 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor7fb09192011-07-21 22:35:25 +00003613 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00003614 QualType NamedType = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003615 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00003616 }
3617
Sebastian Redl539c5062010-08-18 23:57:32 +00003618 case TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00003619 unsigned Idx = 0;
Douglas Gregor7fb09192011-07-21 22:35:25 +00003620 ObjCInterfaceDecl *ItfD
3621 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
John McCall8b07ec22010-05-15 11:32:37 +00003622 return Context->getObjCInterfaceType(ItfD);
3623 }
3624
Sebastian Redl539c5062010-08-18 23:57:32 +00003625 case TYPE_OBJC_OBJECT: {
John McCall8b07ec22010-05-15 11:32:37 +00003626 unsigned Idx = 0;
Douglas Gregor903b7e92011-07-22 00:38:23 +00003627 QualType Base = readType(*Loc.F, Record, Idx);
Chris Lattner587cbe12009-04-22 06:45:28 +00003628 unsigned NumProtos = Record[Idx++];
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003629 SmallVector<ObjCProtocolDecl*, 4> Protos;
Chris Lattner587cbe12009-04-22 06:45:28 +00003630 for (unsigned I = 0; I != NumProtos; ++I)
Douglas Gregor7fb09192011-07-21 22:35:25 +00003631 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003632 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00003633 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00003634
Sebastian Redl539c5062010-08-18 23:57:32 +00003635 case TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00003636 unsigned Idx = 0;
Douglas Gregor903b7e92011-07-22 00:38:23 +00003637 QualType Pointee = readType(*Loc.F, Record, Idx);
John McCall8b07ec22010-05-15 11:32:37 +00003638 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00003639 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00003640
Sebastian Redl539c5062010-08-18 23:57:32 +00003641 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
John McCallcebee162009-10-18 09:09:24 +00003642 unsigned Idx = 0;
Douglas Gregor903b7e92011-07-22 00:38:23 +00003643 QualType Parm = readType(*Loc.F, Record, Idx);
3644 QualType Replacement = readType(*Loc.F, Record, Idx);
John McCallcebee162009-10-18 09:09:24 +00003645 return
3646 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3647 Replacement);
3648 }
John McCalle78aac42010-03-10 03:28:59 +00003649
Douglas Gregorada4b792011-01-14 02:55:32 +00003650 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3651 unsigned Idx = 0;
Douglas Gregor903b7e92011-07-22 00:38:23 +00003652 QualType Parm = readType(*Loc.F, Record, Idx);
Douglas Gregorada4b792011-01-14 02:55:32 +00003653 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3654 return Context->getSubstTemplateTypeParmPackType(
3655 cast<TemplateTypeParmType>(Parm),
3656 ArgPack);
3657 }
3658
Sebastian Redl539c5062010-08-18 23:57:32 +00003659 case TYPE_INJECTED_CLASS_NAME: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00003660 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00003661 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00003662 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
Sebastian Redld44cd6a2010-08-18 23:57:06 +00003663 // for AST reading, too much interdependencies.
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00003664 return
3665 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00003666 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003667
Sebastian Redl539c5062010-08-18 23:57:32 +00003668 case TYPE_TEMPLATE_TYPE_PARM: {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003669 unsigned Idx = 0;
3670 unsigned Depth = Record[Idx++];
3671 unsigned Index = Record[Idx++];
3672 bool Pack = Record[Idx++];
Douglas Gregor7fb09192011-07-21 22:35:25 +00003673 TemplateTypeParmDecl *D
3674 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Chandler Carruth08836322011-05-01 00:51:33 +00003675 return Context->getTemplateTypeParmType(Depth, Index, Pack, D);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003676 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003677
Sebastian Redl539c5062010-08-18 23:57:32 +00003678 case TYPE_DEPENDENT_NAME: {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00003679 unsigned Idx = 0;
3680 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor7fb09192011-07-21 22:35:25 +00003681 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregora3e41532011-07-28 20:55:49 +00003682 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00003683 QualType Canon = readType(*Loc.F, Record, Idx);
Douglas Gregorf86c9392010-10-26 00:51:02 +00003684 if (!Canon.isNull())
3685 Canon = Context->getCanonicalType(Canon);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00003686 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00003687 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003688
Sebastian Redl539c5062010-08-18 23:57:32 +00003689 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003690 unsigned Idx = 0;
3691 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor7fb09192011-07-21 22:35:25 +00003692 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregora3e41532011-07-28 20:55:49 +00003693 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003694 unsigned NumArgs = Record[Idx++];
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003695 SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003696 Args.reserve(NumArgs);
3697 while (NumArgs--)
Sebastian Redl2c373b92010-10-05 15:59:54 +00003698 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00003699 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
3700 Args.size(), Args.data());
3701 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00003702
Sebastian Redl539c5062010-08-18 23:57:32 +00003703 case TYPE_DEPENDENT_SIZED_ARRAY: {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00003704 unsigned Idx = 0;
3705
3706 // ArrayType
Douglas Gregor903b7e92011-07-22 00:38:23 +00003707 QualType ElementType = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00003708 ArrayType::ArraySizeModifier ASM
3709 = (ArrayType::ArraySizeModifier)Record[Idx++];
3710 unsigned IndexTypeQuals = Record[Idx++];
3711
3712 // DependentSizedArrayType
Sebastian Redl2c373b92010-10-05 15:59:54 +00003713 Expr *NumElts = ReadExpr(*Loc.F);
3714 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00003715
3716 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
3717 IndexTypeQuals, Brackets);
3718 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00003719
Sebastian Redl539c5062010-08-18 23:57:32 +00003720 case TYPE_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003721 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003722 bool IsDependent = Record[Idx++];
Douglas Gregor5590be02011-01-15 06:45:20 +00003723 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003724 SmallVector<TemplateArgument, 8> Args;
Sebastian Redl2c373b92010-10-05 15:59:54 +00003725 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00003726 QualType Underlying = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003727 QualType T;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003728 if (Underlying.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003729 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
3730 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003731 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003732 T = Context->getTemplateSpecializationType(Name, Args.data(),
Richard Smith3f1b5d02011-05-05 21:57:07 +00003733 Args.size(), Underlying);
John McCall424cec92011-01-19 06:33:43 +00003734 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00003735 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003736 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003737 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003738 // Suppress a GCC warning
3739 return QualType();
3740}
3741
Sebastian Redl2c373b92010-10-05 15:59:54 +00003742class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
Sebastian Redl2c499f62010-08-18 23:56:43 +00003743 ASTReader &Reader;
Douglas Gregora6895d82011-07-22 16:00:58 +00003744 Module &F;
Sebastian Redlc67764e2010-07-22 22:43:28 +00003745 llvm::BitstreamCursor &DeclsCursor;
Sebastian Redl2c499f62010-08-18 23:56:43 +00003746 const ASTReader::RecordData &Record;
John McCall8f115c62009-10-16 21:56:05 +00003747 unsigned &Idx;
3748
Sebastian Redl2c373b92010-10-05 15:59:54 +00003749 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3750 unsigned &I) {
3751 return Reader.ReadSourceLocation(F, R, I);
3752 }
3753
Douglas Gregor7fb09192011-07-21 22:35:25 +00003754 template<typename T>
3755 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
3756 return Reader.ReadDeclAs<T>(F, Record, Idx);
3757 }
3758
John McCall8f115c62009-10-16 21:56:05 +00003759public:
Douglas Gregora6895d82011-07-22 16:00:58 +00003760 TypeLocReader(ASTReader &Reader, Module &F,
Sebastian Redl2c499f62010-08-18 23:56:43 +00003761 const ASTReader::RecordData &Record, unsigned &Idx)
Sebastian Redl2c373b92010-10-05 15:59:54 +00003762 : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3763 { }
John McCall8f115c62009-10-16 21:56:05 +00003764
John McCall17001972009-10-18 01:05:36 +00003765 // We want compile-time assurance that we've enumerated all of
3766 // these, so unfortunately we have to declare them first, then
3767 // define them out-of-line.
3768#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00003769#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00003770 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00003771#include "clang/AST/TypeLocNodes.def"
3772
John McCall17001972009-10-18 01:05:36 +00003773 void VisitFunctionTypeLoc(FunctionTypeLoc);
3774 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00003775};
3776
John McCall17001972009-10-18 01:05:36 +00003777void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00003778 // nothing to do
3779}
John McCall17001972009-10-18 01:05:36 +00003780void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003781 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
Douglas Gregorc9b7a592010-01-18 18:04:31 +00003782 if (TL.needsExtraLocalData()) {
3783 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3784 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3785 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3786 TL.setModeAttr(Record[Idx++]);
3787 }
John McCall8f115c62009-10-16 21:56:05 +00003788}
John McCall17001972009-10-18 01:05:36 +00003789void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003790 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003791}
John McCall17001972009-10-18 01:05:36 +00003792void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003793 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003794}
John McCall17001972009-10-18 01:05:36 +00003795void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003796 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003797}
John McCall17001972009-10-18 01:05:36 +00003798void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003799 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003800}
John McCall17001972009-10-18 01:05:36 +00003801void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003802 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003803}
John McCall17001972009-10-18 01:05:36 +00003804void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003805 TL.setStarLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnara509357842011-03-05 14:42:21 +00003806 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003807}
John McCall17001972009-10-18 01:05:36 +00003808void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003809 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3810 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003811 if (Record[Idx++])
Sebastian Redl2c373b92010-10-05 15:59:54 +00003812 TL.setSizeExpr(Reader.ReadExpr(F));
Douglas Gregor12bfa382009-10-17 00:13:19 +00003813 else
John McCall17001972009-10-18 01:05:36 +00003814 TL.setSizeExpr(0);
3815}
3816void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3817 VisitArrayTypeLoc(TL);
3818}
3819void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3820 VisitArrayTypeLoc(TL);
3821}
3822void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3823 VisitArrayTypeLoc(TL);
3824}
3825void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3826 DependentSizedArrayTypeLoc TL) {
3827 VisitArrayTypeLoc(TL);
3828}
3829void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3830 DependentSizedExtVectorTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003831 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003832}
3833void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003834 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003835}
3836void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003837 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003838}
3839void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00003840 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
3841 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Douglas Gregor7fb25412010-10-01 18:44:50 +00003842 TL.setTrailingReturn(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00003843 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
Douglas Gregor7fb09192011-07-21 22:35:25 +00003844 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003845 }
3846}
3847void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3848 VisitFunctionTypeLoc(TL);
3849}
3850void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3851 VisitFunctionTypeLoc(TL);
3852}
John McCallb96ec562009-12-04 22:46:56 +00003853void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003854 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCallb96ec562009-12-04 22:46:56 +00003855}
John McCall17001972009-10-18 01:05:36 +00003856void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003857 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003858}
3859void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003860 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3861 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3862 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003863}
3864void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003865 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3866 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3867 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3868 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003869}
3870void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003871 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003872}
Alexis Hunte852b102011-05-24 22:41:36 +00003873void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3874 TL.setKWLoc(ReadSourceLocation(Record, Idx));
3875 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3876 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3877 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3878}
Richard Smith30482bc2011-02-20 03:19:35 +00003879void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3880 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3881}
John McCall17001972009-10-18 01:05:36 +00003882void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003883 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003884}
3885void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003886 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003887}
John McCall81904512011-01-06 01:58:22 +00003888void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3889 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3890 if (TL.hasAttrOperand()) {
3891 SourceRange range;
3892 range.setBegin(ReadSourceLocation(Record, Idx));
3893 range.setEnd(ReadSourceLocation(Record, Idx));
3894 TL.setAttrOperandParensRange(range);
3895 }
3896 if (TL.hasAttrExprOperand()) {
3897 if (Record[Idx++])
3898 TL.setAttrExprOperand(Reader.ReadExpr(F));
3899 else
3900 TL.setAttrExprOperand(0);
3901 } else if (TL.hasAttrEnumOperand())
3902 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3903}
John McCall17001972009-10-18 01:05:36 +00003904void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003905 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003906}
John McCallcebee162009-10-18 09:09:24 +00003907void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3908 SubstTemplateTypeParmTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003909 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCallcebee162009-10-18 09:09:24 +00003910}
Douglas Gregorada4b792011-01-14 02:55:32 +00003911void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3912 SubstTemplateTypeParmPackTypeLoc TL) {
3913 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3914}
John McCall17001972009-10-18 01:05:36 +00003915void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3916 TemplateSpecializationTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003917 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3918 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3919 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall0ad16662009-10-29 08:12:44 +00003920 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3921 TL.setArgLocInfo(i,
Sebastian Redl2c373b92010-10-05 15:59:54 +00003922 Reader.GetTemplateArgumentLocInfo(F,
3923 TL.getTypePtr()->getArg(i).getKind(),
3924 Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003925}
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003926void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3927 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3928 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3929}
Abramo Bagnara6150c882010-05-11 21:36:43 +00003930void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003931 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor844cb502011-03-01 18:12:44 +00003932 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003933}
John McCalle78aac42010-03-10 03:28:59 +00003934void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003935 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCalle78aac42010-03-10 03:28:59 +00003936}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003937void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003938 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00003939 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Sebastian Redl2c373b92010-10-05 15:59:54 +00003940 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003941}
John McCallc392f372010-06-11 00:33:02 +00003942void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3943 DependentTemplateSpecializationTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003944 TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregora7a795b2011-03-01 20:11:18 +00003945 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Sebastian Redl2c373b92010-10-05 15:59:54 +00003946 TL.setNameLoc(ReadSourceLocation(Record, Idx));
3947 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3948 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00003949 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3950 TL.setArgLocInfo(I,
Sebastian Redl2c373b92010-10-05 15:59:54 +00003951 Reader.GetTemplateArgumentLocInfo(F,
3952 TL.getTypePtr()->getArg(I).getKind(),
3953 Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00003954}
Douglas Gregord2fa7662010-12-20 02:24:11 +00003955void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3956 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3957}
John McCall17001972009-10-18 01:05:36 +00003958void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003959 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall8b07ec22010-05-15 11:32:37 +00003960}
3961void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3962 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Sebastian Redl2c373b92010-10-05 15:59:54 +00003963 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3964 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00003965 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Sebastian Redl2c373b92010-10-05 15:59:54 +00003966 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
John McCall8f115c62009-10-16 21:56:05 +00003967}
John McCallfc93cf92009-10-22 22:37:11 +00003968void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00003969 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCallfc93cf92009-10-22 22:37:11 +00003970}
John McCall8f115c62009-10-16 21:56:05 +00003971
Douglas Gregora6895d82011-07-22 16:00:58 +00003972TypeSourceInfo *ASTReader::GetTypeSourceInfo(Module &F,
Sebastian Redlc67764e2010-07-22 22:43:28 +00003973 const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00003974 unsigned &Idx) {
Douglas Gregor903b7e92011-07-22 00:38:23 +00003975 QualType InfoTy = readType(F, Record, Idx);
John McCall8f115c62009-10-16 21:56:05 +00003976 if (InfoTy.isNull())
3977 return 0;
3978
John McCallbcd03502009-12-07 02:54:59 +00003979 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl2c373b92010-10-05 15:59:54 +00003980 TypeLocReader TLR(*this, F, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00003981 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00003982 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00003983 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00003984}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003985
Sebastian Redl539c5062010-08-18 23:57:32 +00003986QualType ASTReader::GetType(TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00003987 unsigned FastQuals = ID & Qualifiers::FastMask;
3988 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003989
Sebastian Redl539c5062010-08-18 23:57:32 +00003990 if (Index < NUM_PREDEF_TYPE_IDS) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003991 QualType T;
Sebastian Redl539c5062010-08-18 23:57:32 +00003992 switch ((PredefinedTypeIDs)Index) {
3993 case PREDEF_TYPE_NULL_ID: return QualType();
3994 case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
3995 case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003996
Sebastian Redl539c5062010-08-18 23:57:32 +00003997 case PREDEF_TYPE_CHAR_U_ID:
3998 case PREDEF_TYPE_CHAR_S_ID:
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003999 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00004000 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004001 break;
4002
Sebastian Redl539c5062010-08-18 23:57:32 +00004003 case PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
4004 case PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
4005 case PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
4006 case PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
4007 case PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
4008 case PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
4009 case PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
4010 case PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
4011 case PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
4012 case PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
4013 case PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
4014 case PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
4015 case PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
4016 case PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
4017 case PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
4018 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
4019 case PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
John McCall0009fcc2011-04-26 20:42:42 +00004020 case PREDEF_TYPE_BOUND_MEMBER: T = Context->BoundMemberTy; break;
Sebastian Redl539c5062010-08-18 23:57:32 +00004021 case PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
John McCall31996342011-04-07 08:22:57 +00004022 case PREDEF_TYPE_UNKNOWN_ANY: T = Context->UnknownAnyTy; break;
Sebastian Redl539c5062010-08-18 23:57:32 +00004023 case PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
4024 case PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
4025 case PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
4026 case PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
4027 case PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
4028 case PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoreda8e122011-08-09 15:13:55 +00004029 case PREDEF_TYPE_AUTO_DEDUCT: T = Context->getAutoDeductType(); break;
4030
4031 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
4032 T = Context->getAutoRRefDeductType();
4033 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004034 }
4035
4036 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00004037 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004038 }
4039
Sebastian Redl539c5062010-08-18 23:57:32 +00004040 Index -= NUM_PREDEF_TYPE_IDS;
Sebastian Redl837a6cb2010-07-20 22:37:49 +00004041 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00004042 if (TypesLoaded[Index].isNull()) {
Douglas Gregor903b7e92011-07-22 00:38:23 +00004043 TypesLoaded[Index] = readTypeRecord(Index);
Douglas Gregor9b3932c2010-10-05 18:37:06 +00004044 if (TypesLoaded[Index].isNull())
4045 return QualType();
4046
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004047 TypesLoaded[Index]->setFromAST();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00004048 if (DeserializationListener)
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00004049 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
Sebastian Redl1ea025b2010-07-16 16:36:56 +00004050 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00004051 }
Mike Stump11289f42009-09-09 15:08:12 +00004052
John McCall8ccfcb52009-09-24 19:53:00 +00004053 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004054}
4055
Douglas Gregora6895d82011-07-22 16:00:58 +00004056QualType ASTReader::getLocalType(Module &F, unsigned LocalID) {
Douglas Gregor903b7e92011-07-22 00:38:23 +00004057 return GetType(getGlobalTypeID(F, LocalID));
4058}
4059
4060serialization::TypeID
Douglas Gregora6895d82011-07-22 16:00:58 +00004061ASTReader::getGlobalTypeID(Module &F, unsigned LocalID) const {
Douglas Gregor5204bde2011-08-02 16:26:37 +00004062 unsigned FastQuals = LocalID & Qualifiers::FastMask;
4063 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
4064
4065 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
4066 return LocalID;
4067
4068 ContinuousRangeMap<uint32_t, int, 2>::iterator I
4069 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
4070 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
4071
4072 unsigned GlobalIndex = LocalIndex + I->second;
4073 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
4074}
4075
John McCall0ad16662009-10-29 08:12:44 +00004076TemplateArgumentLocInfo
Douglas Gregora6895d82011-07-22 16:00:58 +00004077ASTReader::GetTemplateArgumentLocInfo(Module &F,
Sebastian Redl2c373b92010-10-05 15:59:54 +00004078 TemplateArgument::ArgKind Kind,
John McCall0ad16662009-10-29 08:12:44 +00004079 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00004080 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00004081 switch (Kind) {
4082 case TemplateArgument::Expression:
Sebastian Redl2c373b92010-10-05 15:59:54 +00004083 return ReadExpr(F);
John McCall0ad16662009-10-29 08:12:44 +00004084 case TemplateArgument::Type:
Sebastian Redl2c373b92010-10-05 15:59:54 +00004085 return GetTypeSourceInfo(F, Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004086 case TemplateArgument::Template: {
Douglas Gregor9d802122011-03-02 17:09:35 +00004087 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4088 Index);
Sebastian Redl2c373b92010-10-05 15:59:54 +00004089 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregor9d802122011-03-02 17:09:35 +00004090 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004091 SourceLocation());
4092 }
4093 case TemplateArgument::TemplateExpansion: {
Douglas Gregor9d802122011-03-02 17:09:35 +00004094 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
4095 Index);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004096 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregoreb29d182011-01-05 17:40:24 +00004097 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregor9d802122011-03-02 17:09:35 +00004098 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregoreb29d182011-01-05 17:40:24 +00004099 EllipsisLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004100 }
John McCall0ad16662009-10-29 08:12:44 +00004101 case TemplateArgument::Null:
4102 case TemplateArgument::Integral:
4103 case TemplateArgument::Declaration:
4104 case TemplateArgument::Pack:
4105 return TemplateArgumentLocInfo();
4106 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004107 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00004108 return TemplateArgumentLocInfo();
4109}
4110
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004111TemplateArgumentLoc
Douglas Gregora6895d82011-07-22 16:00:58 +00004112ASTReader::ReadTemplateArgumentLoc(Module &F,
Sebastian Redlc67764e2010-07-22 22:43:28 +00004113 const RecordData &Record, unsigned &Index) {
Sebastian Redl2c373b92010-10-05 15:59:54 +00004114 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004115
4116 if (Arg.getKind() == TemplateArgument::Expression) {
4117 if (Record[Index++]) // bool InfoHasSameExpr.
4118 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
4119 }
Sebastian Redl2c373b92010-10-05 15:59:54 +00004120 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00004121 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004122}
4123
Sebastian Redl2c499f62010-08-18 23:56:43 +00004124Decl *ASTReader::GetExternalDecl(uint32_t ID) {
John McCall75b960e2010-06-01 09:23:16 +00004125 return GetDecl(ID);
4126}
4127
Douglas Gregorc27b2872011-08-04 00:01:48 +00004128uint64_t ASTReader::readCXXBaseSpecifiers(Module &M, const RecordData &Record,
4129 unsigned &Idx){
4130 if (Idx >= Record.size())
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004131 return 0;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004132
Douglas Gregorc27b2872011-08-04 00:01:48 +00004133 unsigned LocalID = Record[Idx++];
4134 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004135}
4136
4137CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Douglas Gregord32f0352011-07-22 06:10:01 +00004138 RecordLocation Loc = getLocalBitOffset(Offset);
4139 llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004140 SavedStreamPosition SavedPosition(Cursor);
Douglas Gregord32f0352011-07-22 06:10:01 +00004141 Cursor.JumpToBit(Loc.Offset);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004142 ReadingKindTracker ReadingKind(Read_Decl, *this);
4143 RecordData Record;
4144 unsigned Code = Cursor.ReadCode();
4145 unsigned RecCode = Cursor.ReadRecord(Code, Record);
4146 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
4147 Error("Malformed AST file: missing C++ base specifiers");
4148 return 0;
4149 }
4150
4151 unsigned Idx = 0;
4152 unsigned NumBases = Record[Idx++];
4153 void *Mem = Context->Allocate(sizeof(CXXBaseSpecifier) * NumBases);
4154 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
4155 for (unsigned I = 0; I != NumBases; ++I)
Douglas Gregord32f0352011-07-22 06:10:01 +00004156 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004157 return Bases;
4158}
4159
Douglas Gregor7fb09192011-07-21 22:35:25 +00004160serialization::DeclID
Douglas Gregora6895d82011-07-22 16:00:58 +00004161ASTReader::getGlobalDeclID(Module &F, unsigned LocalID) const {
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004162 if (LocalID < NUM_PREDEF_DECL_IDS)
Douglas Gregorf7180622011-08-03 15:48:04 +00004163 return LocalID;
4164
4165 ContinuousRangeMap<uint32_t, int, 2>::iterator I
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004166 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
Douglas Gregorf7180622011-08-03 15:48:04 +00004167 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
4168
4169 return LocalID + I->second;
Douglas Gregor7fb09192011-07-21 22:35:25 +00004170}
4171
Sebastian Redl539c5062010-08-18 23:57:32 +00004172Decl *ASTReader::GetDecl(DeclID ID) {
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004173 if (ID < NUM_PREDEF_DECL_IDS) {
4174 switch ((PredefinedDeclIDs)ID) {
Douglas Gregordab42432011-08-12 00:15:20 +00004175 case PREDEF_DECL_NULL_ID:
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004176 return 0;
Douglas Gregordab42432011-08-12 00:15:20 +00004177
4178 case PREDEF_DECL_TRANSLATION_UNIT_ID:
4179 assert(Context && "No context available?");
4180 return Context->getTranslationUnitDecl();
Douglas Gregor3ea72692011-08-12 05:46:01 +00004181
4182 case PREDEF_DECL_OBJC_ID_ID:
4183 assert(Context && "No context available?");
4184 return Context->getObjCIdDecl();
Douglas Gregor0a586182011-08-12 05:59:41 +00004185
Douglas Gregor52e02802011-08-12 06:17:30 +00004186 case PREDEF_DECL_OBJC_SEL_ID:
4187 assert(Context && "No context available?");
4188 return Context->getObjCSelDecl();
4189
Douglas Gregor0a586182011-08-12 05:59:41 +00004190 case PREDEF_DECL_OBJC_CLASS_ID:
4191 assert(Context && "No context available?");
4192 return Context->getObjCClassDecl();
Douglas Gregor801c99d2011-08-12 06:49:56 +00004193
4194 case PREDEF_DECL_INT_128_ID:
4195 assert(Context && "No context available?");
4196 return Context->getInt128Decl();
4197
4198 case PREDEF_DECL_UNSIGNED_INT_128_ID:
4199 assert(Context && "No context available?");
4200 return Context->getUInt128Decl();
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004201 }
4202
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004203 return 0;
Douglas Gregor6f8912e2011-08-03 16:05:40 +00004204 }
4205
Douglas Gregordab42432011-08-12 00:15:20 +00004206 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
4207
4208 if (Index > DeclsLoaded.size()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004209 Error("declaration ID out-of-range for AST file");
Douglas Gregor745ed142009-04-25 18:35:21 +00004210 return 0;
4211 }
Douglas Gregordab42432011-08-12 00:15:20 +00004212
4213if (!DeclsLoaded[Index]) {
Douglas Gregorf7180622011-08-03 15:48:04 +00004214 ReadDeclRecord(ID);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00004215 if (DeserializationListener)
4216 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
4217 }
Douglas Gregor745ed142009-04-25 18:35:21 +00004218
4219 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004220}
4221
Douglas Gregora6895d82011-07-22 16:00:58 +00004222serialization::DeclID ASTReader::ReadDeclID(Module &F,
Douglas Gregor7fb09192011-07-21 22:35:25 +00004223 const RecordData &Record,
4224 unsigned &Idx) {
4225 if (Idx >= Record.size()) {
4226 Error("Corrupted AST file");
4227 return 0;
4228 }
4229
4230 return getGlobalDeclID(F, Record[Idx++]);
4231}
4232
Chris Lattner9c28af02009-04-27 05:46:25 +00004233/// \brief Resolve the offset of a statement into a statement.
4234///
4235/// This operation will read a new statement from the external
4236/// source each time it is called, and is meant to be used via a
4237/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
Sebastian Redl2c499f62010-08-18 23:56:43 +00004238Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
Argyrios Kyrtzidisd9f526f2010-10-28 09:29:32 +00004239 // Switch case IDs are per Decl.
4240 ClearSwitchCaseIDs();
4241
Sebastian Redl5c415f32010-07-22 17:01:13 +00004242 // Offset here is a global offset across the entire chain.
Douglas Gregord32f0352011-07-22 06:10:01 +00004243 RecordLocation Loc = getLocalBitOffset(Offset);
4244 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
4245 return ReadStmtFromStream(*Loc.F);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00004246}
4247
Douglas Gregor1257f972011-08-24 21:27:34 +00004248namespace {
4249 class FindExternalLexicalDeclsVisitor {
4250 ASTReader &Reader;
4251 const DeclContext *DC;
4252 bool (*isKindWeWant)(Decl::Kind);
4253 SmallVectorImpl<Decl*> &Decls;
4254 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
4255
4256 public:
4257 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
4258 bool (*isKindWeWant)(Decl::Kind),
4259 SmallVectorImpl<Decl*> &Decls)
4260 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
4261 {
4262 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
4263 PredefsVisited[I] = false;
4264 }
4265
4266 static bool visit(Module &M, bool Preorder, void *UserData) {
4267 if (Preorder)
4268 return false;
4269
4270 FindExternalLexicalDeclsVisitor *This
4271 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
4272
4273 Module::DeclContextInfosMap::iterator Info
4274 = M.DeclContextInfos.find(This->DC);
4275 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
4276 return false;
4277
4278 // Load all of the declaration IDs
4279 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
4280 *IDE = ID + Info->second.NumLexicalDecls;
4281 ID != IDE; ++ID) {
4282 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
4283 continue;
4284
4285 // Don't add predefined declarations to the lexical context more
4286 // than once.
4287 if (ID->second < NUM_PREDEF_DECL_IDS) {
4288 if (This->PredefsVisited[ID->second])
4289 continue;
4290
4291 This->PredefsVisited[ID->second] = true;
4292 }
4293
4294 Decl *D = This->Reader.GetLocalDecl(M, ID->second);
4295 assert(D && "Null decl in lexical decls");
4296 This->Decls.push_back(D);
4297 }
4298
4299 return false;
4300 }
4301 };
4302}
4303
Douglas Gregor3d0adb32011-07-15 21:46:17 +00004304ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004305 bool (*isKindWeWant)(Decl::Kind),
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004306 SmallVectorImpl<Decl*> &Decls) {
Douglas Gregor94619c82011-08-24 19:03:07 +00004307 // There might be lexical decls in multiple modules, for the TU at
Douglas Gregor1257f972011-08-24 21:27:34 +00004308 // least. Walk all of the modules in the order they were loaded.
4309 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
4310 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
Douglas Gregora57c3ab2009-04-22 22:34:57 +00004311 ++NumLexicalDeclContextsRead;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00004312 return ELR_Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004313}
4314
Douglas Gregor94619c82011-08-24 19:03:07 +00004315namespace {
4316 /// \brief Module visitor used to perform name lookup into a
4317 /// declaration context.
4318 class DeclContextNameLookupVisitor {
4319 ASTReader &Reader;
4320 const DeclContext *DC;
4321 DeclarationName Name;
4322 SmallVectorImpl<NamedDecl *> &Decls;
4323
4324 public:
4325 DeclContextNameLookupVisitor(ASTReader &Reader,
4326 const DeclContext *DC, DeclarationName Name,
4327 SmallVectorImpl<NamedDecl *> &Decls)
4328 : Reader(Reader), DC(DC), Name(Name), Decls(Decls) { }
4329
4330 static bool visit(Module &M, void *UserData) {
4331 DeclContextNameLookupVisitor *This
4332 = static_cast<DeclContextNameLookupVisitor *>(UserData);
4333
4334 // Check whether we have any visible declaration information for
4335 // this context in this module.
4336 Module::DeclContextInfosMap::iterator Info
4337 = M.DeclContextInfos.find(This->DC);
4338 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
4339 return false;
4340
4341 // Look for this name within this module.
4342 ASTDeclContextNameLookupTable *LookupTable =
4343 (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
4344 ASTDeclContextNameLookupTable::iterator Pos
4345 = LookupTable->find(This->Name);
4346 if (Pos == LookupTable->end())
4347 return false;
4348
4349 bool FoundAnything = false;
4350 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
4351 for (; Data.first != Data.second; ++Data.first) {
4352 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
4353 if (!ND)
4354 continue;
4355
4356 if (ND->getDeclName() != This->Name) {
4357 assert(!This->Name.getCXXNameType().isNull() &&
4358 "Name mismatch without a type");
4359 continue;
4360 }
4361
4362 // Record this declaration.
4363 FoundAnything = true;
4364 This->Decls.push_back(ND);
4365 }
4366
4367 return FoundAnything;
4368 }
4369 };
4370}
4371
John McCall75b960e2010-06-01 09:23:16 +00004372DeclContext::lookup_result
Sebastian Redl2c499f62010-08-18 23:56:43 +00004373ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00004374 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004375 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004376 "DeclContext has no visible decls in storage");
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004377 if (!Name)
4378 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
4379 DeclContext::lookup_iterator(0));
Ted Kremenek1ff615c2010-03-18 00:56:54 +00004380
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004381 SmallVector<NamedDecl *, 64> Decls;
Douglas Gregor94619c82011-08-24 19:03:07 +00004382 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls);
4383 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
Douglas Gregora57c3ab2009-04-22 22:34:57 +00004384 ++NumVisibleDeclContextsRead;
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004385 SetExternalVisibleDeclsForName(DC, Name, Decls);
John McCall75b960e2010-06-01 09:23:16 +00004386 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004387}
4388
Sebastian Redl2c499f62010-08-18 23:56:43 +00004389void ASTReader::PassInterestingDeclsToConsumer() {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00004390 assert(Consumer);
4391 while (!InterestingDecls.empty()) {
4392 DeclGroupRef DG(InterestingDecls.front());
4393 InterestingDecls.pop_front();
Sebastian Redleaa4ade2010-08-11 18:52:41 +00004394 Consumer->HandleInterestingDecl(DG);
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00004395 }
4396}
4397
Sebastian Redl2c499f62010-08-18 23:56:43 +00004398void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00004399 this->Consumer = Consumer;
4400
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00004401 if (!Consumer)
4402 return;
4403
4404 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00004405 // Force deserialization of this decl, which will cause it to be queued for
4406 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00004407 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00004408 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00004409
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00004410 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00004411}
4412
Sebastian Redl2c499f62010-08-18 23:56:43 +00004413void ASTReader::PrintStats() {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004414 std::fprintf(stderr, "*** AST File Statistics:\n");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004415
Mike Stump11289f42009-09-09 15:08:12 +00004416 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00004417 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00004418 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00004419 unsigned NumDeclsLoaded
4420 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
4421 (Decl *)0);
4422 unsigned NumIdentifiersLoaded
4423 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
4424 IdentifiersLoaded.end(),
4425 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00004426 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00004427 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
4428 SelectorsLoaded.end(),
4429 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00004430
Douglas Gregorc5046832009-04-27 18:38:38 +00004431 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
4432 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor49bf76b2011-07-21 18:46:38 +00004433 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
Douglas Gregor258ae542009-04-27 06:38:32 +00004434 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
4435 NumSLocEntriesRead, TotalNumSLocEntries,
4436 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00004437 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00004438 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00004439 NumTypesLoaded, (unsigned)TypesLoaded.size(),
4440 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
4441 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00004442 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00004443 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
4444 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00004445 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00004446 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00004447 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
4448 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redlada023c2010-08-04 20:40:17 +00004449 if (!SelectorsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00004450 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redlada023c2010-08-04 20:40:17 +00004451 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
4452 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00004453 if (TotalNumStatements)
4454 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
4455 NumStatementsRead, TotalNumStatements,
4456 ((float)NumStatementsRead/TotalNumStatements * 100));
4457 if (TotalNumMacros)
4458 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
4459 NumMacrosRead, TotalNumMacros,
4460 ((float)NumMacrosRead/TotalNumMacros * 100));
4461 if (TotalLexicalDeclContexts)
4462 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
4463 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4464 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4465 * 100));
4466 if (TotalVisibleDeclContexts)
4467 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
4468 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4469 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4470 * 100));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00004471 if (TotalNumMethodPoolEntries) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004472 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00004473 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4474 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor95c13f52009-04-25 17:48:32 +00004475 * 100));
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00004476 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor95c13f52009-04-25 17:48:32 +00004477 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004478 std::fprintf(stderr, "\n");
Douglas Gregor204b8712011-07-21 19:50:14 +00004479 dump();
4480 std::fprintf(stderr, "\n");
4481}
4482
Douglas Gregora6895d82011-07-22 16:00:58 +00004483template<typename Key, typename Module, unsigned InitialCapacity>
Douglas Gregor204b8712011-07-21 19:50:14 +00004484static void
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004485dumpModuleIDMap(StringRef Name,
Douglas Gregora6895d82011-07-22 16:00:58 +00004486 const ContinuousRangeMap<Key, Module *,
Douglas Gregor204b8712011-07-21 19:50:14 +00004487 InitialCapacity> &Map) {
4488 if (Map.begin() == Map.end())
4489 return;
4490
Douglas Gregora6895d82011-07-22 16:00:58 +00004491 typedef ContinuousRangeMap<Key, Module *, InitialCapacity> MapType;
Douglas Gregor204b8712011-07-21 19:50:14 +00004492 llvm::errs() << Name << ":\n";
4493 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
4494 I != IEnd; ++I) {
4495 llvm::errs() << " " << I->first << " -> " << I->second->FileName
4496 << "\n";
4497 }
4498}
4499
Douglas Gregor204b8712011-07-21 19:50:14 +00004500void ASTReader::dump() {
Douglas Gregor1cc9c062011-08-02 11:12:41 +00004501 llvm::errs() << "*** PCH/Module Remappings:\n";
Douglas Gregord32f0352011-07-22 06:10:01 +00004502 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
Douglas Gregor204b8712011-07-21 19:50:14 +00004503 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
Douglas Gregor8ab4ea82011-07-29 00:21:44 +00004504 dumpModuleIDMap("Global type map", GlobalTypeMap);
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00004505 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00004506 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
4507 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
4508 dumpModuleIDMap("Global macro definition map", GlobalMacroDefinitionMap);
4509 dumpModuleIDMap("Global preprocessed entity map",
4510 GlobalPreprocessedEntityMap);
Douglas Gregor1cc9c062011-08-02 11:12:41 +00004511
4512 llvm::errs() << "\n*** PCH/Modules Loaded:";
4513 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
4514 MEnd = ModuleMgr.end();
4515 M != MEnd; ++M)
4516 (*M)->dump();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004517}
4518
Ted Kremenek5e1ed7b2011-04-28 23:46:20 +00004519/// Return the amount of memory used by memory buffers, breaking down
4520/// by heap-backed versus mmap'ed memory.
4521void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00004522 for (ModuleConstIterator I = ModuleMgr.begin(),
4523 E = ModuleMgr.end(); I != E; ++I) {
4524 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
Ted Kremenek5e1ed7b2011-04-28 23:46:20 +00004525 size_t bytes = buf->getBufferSize();
4526 switch (buf->getBufferKind()) {
4527 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
4528 sizes.malloc_bytes += bytes;
4529 break;
4530 case llvm::MemoryBuffer::MemoryBuffer_MMap:
4531 sizes.mmap_bytes += bytes;
4532 break;
4533 }
4534 }
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00004535 }
Ted Kremenek5e1ed7b2011-04-28 23:46:20 +00004536}
4537
Sebastian Redl2c499f62010-08-18 23:56:43 +00004538void ASTReader::InitializeSema(Sema &S) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00004539 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00004540 S.ExternalSource = this;
4541
Douglas Gregor7cd60f72009-04-22 21:15:06 +00004542 // Makes sure any declarations that were deserialized "too early"
4543 // still get added to the identifier's declaration chains.
Douglas Gregor2fb99df2010-09-24 23:29:12 +00004544 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4545 if (SemaObj->TUScope)
John McCall48871652010-08-21 09:40:31 +00004546 SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
Douglas Gregor2fb99df2010-09-24 23:29:12 +00004547
4548 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00004549 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00004550 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00004551
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004552 // Load the offsets of the declarations that Sema references.
4553 // They will be lazily deserialized when needed.
4554 if (!SemaDeclRefs.empty()) {
4555 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
Douglas Gregorb0f3ae62011-07-28 00:57:24 +00004556 if (!SemaObj->StdNamespace)
4557 SemaObj->StdNamespace = SemaDeclRefs[0];
4558 if (!SemaObj->StdBadAlloc)
4559 SemaObj->StdBadAlloc = SemaDeclRefs[1];
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004560 }
4561
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004562 if (!FPPragmaOptions.empty()) {
4563 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4564 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4565 }
4566
4567 if (!OpenCLExtensions.empty()) {
4568 unsigned I = 0;
4569#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4570#include "clang/Basic/OpenCLExtensions.def"
4571
4572 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4573 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00004574}
4575
Douglas Gregorab443b92011-08-20 04:39:52 +00004576namespace {
4577 /// \brief Visitor class used to look up identifirs in
4578 class IdentifierLookupVisitor {
4579 StringRef Name;
4580 IdentifierInfo *Found;
4581 public:
4582 explicit IdentifierLookupVisitor(StringRef Name) : Name(Name), Found() { }
Douglas Gregora868bbd2009-04-21 22:25:48 +00004583
Douglas Gregorab443b92011-08-20 04:39:52 +00004584 static bool visit(Module &M, void *UserData) {
4585 IdentifierLookupVisitor *This
4586 = static_cast<IdentifierLookupVisitor *>(UserData);
4587
4588 ASTIdentifierLookupTable *IdTable
4589 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
4590 if (!IdTable)
4591 return false;
4592
4593 std::pair<const char*, unsigned> Key(This->Name.begin(),
4594 This->Name.size());
4595 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
4596 if (Pos == IdTable->end())
4597 return false;
4598
4599 // Dereferencing the iterator has the effect of building the
4600 // IdentifierInfo node and populating it with the various
4601 // declarations it needs.
4602 This->Found = *Pos;
4603 return true;
4604 }
4605
4606 // \brief Retrieve the identifier info found within the module
4607 // files.
4608 IdentifierInfo *getIdentifierInfo() const { return Found; }
4609 };
4610}
4611
4612IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
Douglas Gregorab443b92011-08-20 04:39:52 +00004613 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart));
4614 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
4615 return Visitor.getIdentifierInfo();
Douglas Gregora868bbd2009-04-21 22:25:48 +00004616}
4617
Douglas Gregor57756ea2010-10-14 22:11:03 +00004618namespace clang {
4619 /// \brief An identifier-lookup iterator that enumerates all of the
4620 /// identifiers stored within a set of AST files.
4621 class ASTIdentifierIterator : public IdentifierIterator {
4622 /// \brief The AST reader whose identifiers are being enumerated.
4623 const ASTReader &Reader;
4624
4625 /// \brief The current index into the chain of AST files stored in
4626 /// the AST reader.
4627 unsigned Index;
4628
4629 /// \brief The current position within the identifier lookup table
4630 /// of the current AST file.
4631 ASTIdentifierLookupTable::key_iterator Current;
4632
4633 /// \brief The end position within the identifier lookup table of
4634 /// the current AST file.
4635 ASTIdentifierLookupTable::key_iterator End;
4636
4637 public:
4638 explicit ASTIdentifierIterator(const ASTReader &Reader);
4639
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004640 virtual StringRef Next();
Douglas Gregor57756ea2010-10-14 22:11:03 +00004641 };
4642}
4643
4644ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00004645 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
Douglas Gregor57756ea2010-10-14 22:11:03 +00004646 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00004647 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004648 Current = IdTable->key_begin();
4649 End = IdTable->key_end();
4650}
4651
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004652StringRef ASTIdentifierIterator::Next() {
Douglas Gregor57756ea2010-10-14 22:11:03 +00004653 while (Current == End) {
4654 // If we have exhausted all of our AST files, we're done.
4655 if (Index == 0)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004656 return StringRef();
Douglas Gregor57756ea2010-10-14 22:11:03 +00004657
4658 --Index;
4659 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner16f57d32011-07-25 20:32:21 +00004660 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
4661 IdentifierLookupTable;
Douglas Gregor57756ea2010-10-14 22:11:03 +00004662 Current = IdTable->key_begin();
4663 End = IdTable->key_end();
4664 }
4665
4666 // We have any identifiers remaining in the current AST file; return
4667 // the next one.
4668 std::pair<const char*, unsigned> Key = *Current;
4669 ++Current;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004670 return StringRef(Key.first, Key.second);
Douglas Gregor57756ea2010-10-14 22:11:03 +00004671}
4672
4673IdentifierIterator *ASTReader::getIdentifiers() const {
4674 return new ASTIdentifierIterator(*this);
4675}
4676
Douglas Gregorc10edd62011-08-25 14:51:20 +00004677namespace clang { namespace serialization {
4678 class ReadMethodPoolVisitor {
4679 ASTReader &Reader;
4680 Selector Sel;
4681 llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
4682 llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Douglas Gregorc78d3462009-04-24 21:10:55 +00004683
Douglas Gregorc10edd62011-08-25 14:51:20 +00004684 /// \brief Build an ObjCMethodList from a vector of Objective-C method
4685 /// declarations.
4686 ObjCMethodList
4687 buildObjCMethodList(const SmallVectorImpl<ObjCMethodDecl *> &Vec) const
4688 {
4689 ObjCMethodList List;
4690 ObjCMethodList *Prev = 0;
4691 for (unsigned I = 0, N = Vec.size(); I != N; ++I) {
4692 if (!List.Method) {
4693 // This is the first method, which is the easy case.
4694 List.Method = Vec[I];
4695 Prev = &List;
4696 continue;
4697 }
4698
4699 ObjCMethodList *Mem =
4700 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
4701 Prev->Next = new (Mem) ObjCMethodList(Vec[I], 0);
4702 Prev = Prev->Next;
4703 }
4704
4705 return List;
4706 }
4707
4708 public:
4709 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel)
4710 : Reader(Reader), Sel(Sel) { }
4711
4712 static bool visit(Module &M, void *UserData) {
4713 ReadMethodPoolVisitor *This
4714 = static_cast<ReadMethodPoolVisitor *>(UserData);
4715
4716 if (!M.SelectorLookupTable)
4717 return false;
4718
4719 ASTSelectorLookupTable *PoolTable
4720 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
4721 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
4722 if (Pos == PoolTable->end())
4723 return false;
4724
4725 ++This->Reader.NumSelectorsRead;
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00004726 // FIXME: Not quite happy with the statistics here. We probably should
4727 // disable this tracking when called via LoadSelector.
4728 // Also, should entries without methods count as misses?
Douglas Gregorc10edd62011-08-25 14:51:20 +00004729 ++This->Reader.NumMethodPoolEntriesRead;
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004730 ASTSelectorLookupTrait::data_type Data = *Pos;
Douglas Gregorc10edd62011-08-25 14:51:20 +00004731 if (This->Reader.DeserializationListener)
4732 This->Reader.DeserializationListener->SelectorRead(Data.ID,
4733 This->Sel);
4734
4735 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
4736 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
4737 return true;
Sebastian Redlada023c2010-08-04 20:40:17 +00004738 }
Douglas Gregorc10edd62011-08-25 14:51:20 +00004739
4740 /// \brief Retrieve the instance methods found by this visitor.
4741 ObjCMethodList getInstanceMethods() const {
4742 return buildObjCMethodList(InstanceMethods);
4743 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00004744
Douglas Gregorc10edd62011-08-25 14:51:20 +00004745 /// \brief Retrieve the instance methods found by this visitor.
4746 ObjCMethodList getFactoryMethods() const {
4747 return buildObjCMethodList(FactoryMethods);
4748 }
4749 };
4750} } // end namespace clang::serialization
4751
4752std::pair<ObjCMethodList, ObjCMethodList>
4753ASTReader::ReadMethodPool(Selector Sel) {
4754 ReadMethodPoolVisitor Visitor(*this, Sel);
4755 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
4756 std::pair<ObjCMethodList, ObjCMethodList> Result;
4757 Result.first = Visitor.getInstanceMethods();
4758 Result.second = Visitor.getFactoryMethods();
4759
4760 if (!Result.first.Method && !Result.second.Method)
4761 ++NumMethodPoolMisses;
4762 return Result;
Douglas Gregorc78d3462009-04-24 21:10:55 +00004763}
4764
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004765void ASTReader::ReadKnownNamespaces(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004766 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004767 Namespaces.clear();
4768
4769 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
4770 if (NamespaceDecl *Namespace
4771 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
4772 Namespaces.push_back(Namespace);
4773 }
4774}
4775
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004776void ASTReader::ReadTentativeDefinitions(
4777 SmallVectorImpl<VarDecl *> &TentativeDefs) {
4778 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4779 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
4780 if (Var)
4781 TentativeDefs.push_back(Var);
4782 }
4783 TentativeDefinitions.clear();
4784}
4785
Douglas Gregora94a1542011-07-27 21:45:57 +00004786void ASTReader::ReadUnusedFileScopedDecls(
4787 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
4788 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4789 DeclaratorDecl *D
4790 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4791 if (D)
4792 Decls.push_back(D);
4793 }
4794 UnusedFileScopedDecls.clear();
4795}
4796
Douglas Gregorbae31202011-07-27 21:57:17 +00004797void ASTReader::ReadDelegatingConstructors(
4798 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
4799 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
4800 CXXConstructorDecl *D
4801 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
4802 if (D)
4803 Decls.push_back(D);
4804 }
4805 DelegatingCtorDecls.clear();
4806}
4807
Douglas Gregorb7098a32011-07-28 00:39:29 +00004808void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
4809 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
4810 TypedefNameDecl *D
4811 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
4812 if (D)
4813 Decls.push_back(D);
4814 }
4815 ExtVectorDecls.clear();
4816}
4817
Douglas Gregor32002192011-07-28 00:53:40 +00004818void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
4819 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
4820 CXXRecordDecl *D
4821 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
4822 if (D)
4823 Decls.push_back(D);
4824 }
4825 DynamicClasses.clear();
4826}
4827
Douglas Gregordc5c9582011-07-28 14:20:37 +00004828void
4829ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
4830 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4831 NamedDecl *D
4832 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4833 if (D)
4834 Decls.push_back(D);
4835 }
4836 LocallyScopedExternalDecls.clear();
4837}
4838
Douglas Gregor72e357f2011-07-28 14:54:22 +00004839void ASTReader::ReadReferencedSelectors(
4840 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
4841 if (ReferencedSelectorsData.empty())
4842 return;
4843
4844 // If there are @selector references added them to its pool. This is for
4845 // implementation of -Wselector.
4846 unsigned int DataSize = ReferencedSelectorsData.size()-1;
4847 unsigned I = 0;
4848 while (I < DataSize) {
4849 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
4850 SourceLocation SelLoc
4851 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
4852 Sels.push_back(std::make_pair(Sel, SelLoc));
4853 }
4854 ReferencedSelectorsData.clear();
4855}
4856
Douglas Gregor1c4bfe52011-07-28 18:09:57 +00004857void ASTReader::ReadWeakUndeclaredIdentifiers(
4858 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
4859 if (WeakUndeclaredIdentifiers.empty())
4860 return;
4861
4862 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
4863 IdentifierInfo *WeakId
4864 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4865 IdentifierInfo *AliasId
4866 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4867 SourceLocation Loc
4868 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
4869 bool Used = WeakUndeclaredIdentifiers[I++];
4870 WeakInfo WI(AliasId, Loc);
4871 WI.setUsed(Used);
4872 WeakIDs.push_back(std::make_pair(WeakId, WI));
4873 }
4874 WeakUndeclaredIdentifiers.clear();
4875}
4876
Douglas Gregor4daf6a32011-07-28 19:11:31 +00004877void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
4878 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
4879 ExternalVTableUse VT;
4880 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4881 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
4882 VT.DefinitionRequired = VTableUses[Idx++];
4883 VTables.push_back(VT);
4884 }
4885
4886 VTableUses.clear();
4887}
4888
Douglas Gregore39f97c2011-07-28 19:49:54 +00004889void ASTReader::ReadPendingInstantiations(
4890 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
4891 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
4892 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
4893 SourceLocation Loc
4894 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
4895 Pending.push_back(std::make_pair(D, Loc));
4896 }
4897 PendingInstantiations.clear();
4898}
4899
Sebastian Redl2c499f62010-08-18 23:56:43 +00004900void ASTReader::LoadSelector(Selector Sel) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004901 // It would be complicated to avoid reading the methods anyway. So don't.
4902 ReadMethodPool(Sel);
4903}
4904
Douglas Gregora3e41532011-07-28 20:55:49 +00004905void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00004906 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00004907 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00004908 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlff4a2952010-07-23 23:49:55 +00004909 if (DeserializationListener)
4910 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregora868bbd2009-04-21 22:25:48 +00004911}
4912
Douglas Gregor1342e842009-07-06 18:54:52 +00004913/// \brief Set the globally-visible declarations associated with the given
4914/// identifier.
4915///
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004916/// If the AST reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00004917/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00004918/// them.
4919///
4920/// \param II an IdentifierInfo that refers to one or more globally-visible
4921/// declarations.
4922///
4923/// \param DeclIDs the set of declaration IDs with the name @p II that are
4924/// visible at global scope.
4925///
4926/// \param Nonrecursive should be true to indicate that the caller knows that
4927/// this call is non-recursive, and therefore the globally-visible declarations
4928/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00004929void
Sebastian Redl2c499f62010-08-18 23:56:43 +00004930ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004931 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor1342e842009-07-06 18:54:52 +00004932 bool Nonrecursive) {
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00004933 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregor1342e842009-07-06 18:54:52 +00004934 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4935 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4936 PII.II = II;
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004937 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
Douglas Gregor1342e842009-07-06 18:54:52 +00004938 return;
4939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
Douglas Gregor1342e842009-07-06 18:54:52 +00004941 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4942 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4943 if (SemaObj) {
Douglas Gregor6fd55e02010-08-13 03:15:25 +00004944 if (SemaObj->TUScope) {
4945 // Introduce this declaration into the translation-unit scope
4946 // and add it to the declaration chain for this identifier, so
4947 // that (unqualified) name lookup will find it.
John McCall48871652010-08-21 09:40:31 +00004948 SemaObj->TUScope->AddDecl(D);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00004949 }
Douglas Gregor2fb99df2010-09-24 23:29:12 +00004950 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
Douglas Gregor1342e842009-07-06 18:54:52 +00004951 } else {
4952 // Queue this declaration so that it will be added to the
4953 // translation unit scope and identifier's declaration chain
4954 // once a Sema object is known.
4955 PreloadedDecls.push_back(D);
4956 }
4957 }
4958}
4959
Douglas Gregora3e41532011-07-28 20:55:49 +00004960IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004961 if (ID == 0)
4962 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004963
Sebastian Redlc713b962010-07-21 00:46:22 +00004964 if (IdentifiersLoaded.empty()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004965 Error("no identifier table in AST file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004966 return 0;
4967 }
Mike Stump11289f42009-09-09 15:08:12 +00004968
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00004969 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redlc713b962010-07-21 00:46:22 +00004970 ID -= 1;
4971 if (!IdentifiersLoaded[ID]) {
Douglas Gregor19d26352011-07-20 00:59:32 +00004972 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
4973 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00004974 Module *M = I->second;
4975 unsigned Index = ID - M->BaseIdentifierID;
4976 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
Douglas Gregor5287b4e2009-04-25 21:04:17 +00004977
Sebastian Redld44cd6a2010-08-18 23:57:06 +00004978 // All of the strings in the AST file are preceded by a 16-bit length.
4979 // Extract that 16-bit length to avoid having to execute strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00004980 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4981 // unsigned integers. This is important to avoid integer overflow when
4982 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00004983 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00004984 unsigned StrLen = (((unsigned) StrLenPtr[0])
4985 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redlc713b962010-07-21 00:46:22 +00004986 IdentifiersLoaded[ID]
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004987 = &PP->getIdentifierTable().get(StringRef(Str, StrLen));
Sebastian Redlff4a2952010-07-23 23:49:55 +00004988 if (DeserializationListener)
4989 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004990 }
Mike Stump11289f42009-09-09 15:08:12 +00004991
Sebastian Redlc713b962010-07-21 00:46:22 +00004992 return IdentifiersLoaded[ID];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004993}
4994
Douglas Gregora3e41532011-07-28 20:55:49 +00004995IdentifierInfo *ASTReader::getLocalIdentifier(Module &M, unsigned LocalID) {
4996 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
4997}
4998
4999IdentifierID ASTReader::getGlobalIdentifierID(Module &M, unsigned LocalID) {
Douglas Gregor1ab036c2011-08-03 21:49:18 +00005000 if (LocalID < NUM_PREDEF_IDENT_IDS)
5001 return LocalID;
5002
5003 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5004 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
5005 assert(I != M.IdentifierRemap.end()
5006 && "Invalid index into identifier index remap");
5007
5008 return LocalID + I->second;
Douglas Gregora3e41532011-07-28 20:55:49 +00005009}
5010
Douglas Gregor925296b2011-07-19 16:10:42 +00005011bool ASTReader::ReadSLocEntry(int ID) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00005012 return ReadSLocEntryRecord(ID) != Success;
Douglas Gregor258ae542009-04-27 06:38:32 +00005013}
5014
Douglas Gregor074fdc52011-07-28 21:16:51 +00005015Selector ASTReader::getLocalSelector(Module &M, unsigned LocalID) {
5016 return DecodeSelector(getGlobalSelectorID(M, LocalID));
5017}
5018
5019Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
Steve Naroff2ddea052009-04-23 10:39:46 +00005020 if (ID == 0)
5021 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00005022
Sebastian Redlada023c2010-08-04 20:40:17 +00005023 if (ID > SelectorsLoaded.size()) {
Sebastian Redld44cd6a2010-08-18 23:57:06 +00005024 Error("selector ID out of range in AST file");
Steve Naroff2ddea052009-04-23 10:39:46 +00005025 return Selector();
5026 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00005027
Sebastian Redlada023c2010-08-04 20:40:17 +00005028 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00005029 // Load this selector from the selector table.
Douglas Gregor2262d282011-07-20 01:10:58 +00005030 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
5031 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00005032 Module &M = *I->second;
5033 ASTSelectorLookupTrait Trait(*this, M);
Douglas Gregor8f364fb2011-08-03 23:28:44 +00005034 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
Douglas Gregor2262d282011-07-20 01:10:58 +00005035 SelectorsLoaded[ID - 1] =
Douglas Gregorbab6d2c2011-07-29 00:56:45 +00005036 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
Douglas Gregor2262d282011-07-20 01:10:58 +00005037 if (DeserializationListener)
5038 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
Douglas Gregor95c13f52009-04-25 17:48:32 +00005039 }
5040
Sebastian Redlada023c2010-08-04 20:40:17 +00005041 return SelectorsLoaded[ID - 1];
Steve Naroff2ddea052009-04-23 10:39:46 +00005042}
5043
Douglas Gregor3f8f04f2011-07-28 14:41:43 +00005044Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00005045 return DecodeSelector(ID);
5046}
5047
Sebastian Redl2c499f62010-08-18 23:56:43 +00005048uint32_t ASTReader::GetNumExternalSelectors() {
Sebastian Redlada023c2010-08-04 20:40:17 +00005049 // ID 0 (the null selector) is considered an external selector.
5050 return getTotalNumSelectors() + 1;
Douglas Gregord720daf2010-04-06 17:30:22 +00005051}
5052
Douglas Gregor8f364fb2011-08-03 23:28:44 +00005053serialization::SelectorID
5054ASTReader::getGlobalSelectorID(Module &M, unsigned LocalID) const {
5055 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
5056 return LocalID;
5057
5058 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5059 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
5060 assert(I != M.SelectorRemap.end()
5061 && "Invalid index into identifier index remap");
5062
5063 return LocalID + I->second;
Douglas Gregor3f8f04f2011-07-28 14:41:43 +00005064}
5065
Mike Stump11289f42009-09-09 15:08:12 +00005066DeclarationName
Douglas Gregora6895d82011-07-22 16:00:58 +00005067ASTReader::ReadDeclarationName(Module &F,
Douglas Gregor903b7e92011-07-22 00:38:23 +00005068 const RecordData &Record, unsigned &Idx) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005069 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
5070 switch (Kind) {
5071 case DeclarationName::Identifier:
Douglas Gregora3e41532011-07-28 20:55:49 +00005072 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005073
5074 case DeclarationName::ObjCZeroArgSelector:
5075 case DeclarationName::ObjCOneArgSelector:
5076 case DeclarationName::ObjCMultiArgSelector:
Douglas Gregor074fdc52011-07-28 21:16:51 +00005077 return DeclarationName(ReadSelector(F, Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005078
5079 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00005080 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor903b7e92011-07-22 00:38:23 +00005081 Context->getCanonicalType(readType(F, Record, Idx)));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005082
5083 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00005084 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor903b7e92011-07-22 00:38:23 +00005085 Context->getCanonicalType(readType(F, Record, Idx)));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005086
5087 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00005088 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor903b7e92011-07-22 00:38:23 +00005089 Context->getCanonicalType(readType(F, Record, Idx)));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005090
5091 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00005092 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005093 (OverloadedOperatorKind)Record[Idx++]);
5094
Alexis Hunt3d221f22009-11-29 07:34:05 +00005095 case DeclarationName::CXXLiteralOperatorName:
5096 return Context->DeclarationNames.getCXXLiteralOperatorName(
Douglas Gregora3e41532011-07-28 20:55:49 +00005097 GetIdentifierInfo(F, Record, Idx));
Alexis Hunt3d221f22009-11-29 07:34:05 +00005098
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005099 case DeclarationName::CXXUsingDirective:
5100 return DeclarationName::getUsingDirectiveName();
5101 }
5102
5103 // Required to silence GCC warning
5104 return DeclarationName();
5105}
Douglas Gregor55abb232009-04-10 20:39:37 +00005106
Douglas Gregora6895d82011-07-22 16:00:58 +00005107void ASTReader::ReadDeclarationNameLoc(Module &F,
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005108 DeclarationNameLoc &DNLoc,
5109 DeclarationName Name,
5110 const RecordData &Record, unsigned &Idx) {
5111 switch (Name.getNameKind()) {
5112 case DeclarationName::CXXConstructorName:
5113 case DeclarationName::CXXDestructorName:
5114 case DeclarationName::CXXConversionFunctionName:
5115 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
5116 break;
5117
5118 case DeclarationName::CXXOperatorName:
5119 DNLoc.CXXOperatorName.BeginOpNameLoc
5120 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5121 DNLoc.CXXOperatorName.EndOpNameLoc
5122 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5123 break;
5124
5125 case DeclarationName::CXXLiteralOperatorName:
5126 DNLoc.CXXLiteralOperatorName.OpNameLoc
5127 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5128 break;
5129
5130 case DeclarationName::Identifier:
5131 case DeclarationName::ObjCZeroArgSelector:
5132 case DeclarationName::ObjCOneArgSelector:
5133 case DeclarationName::ObjCMultiArgSelector:
5134 case DeclarationName::CXXUsingDirective:
5135 break;
5136 }
5137}
5138
Douglas Gregora6895d82011-07-22 16:00:58 +00005139void ASTReader::ReadDeclarationNameInfo(Module &F,
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005140 DeclarationNameInfo &NameInfo,
5141 const RecordData &Record, unsigned &Idx) {
Douglas Gregor903b7e92011-07-22 00:38:23 +00005142 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005143 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
5144 DeclarationNameLoc DNLoc;
5145 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
5146 NameInfo.setInfo(DNLoc);
5147}
5148
Douglas Gregora6895d82011-07-22 16:00:58 +00005149void ASTReader::ReadQualifierInfo(Module &F, QualifierInfo &Info,
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005150 const RecordData &Record, unsigned &Idx) {
Douglas Gregor14454802011-02-25 02:25:35 +00005151 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005152 unsigned NumTPLists = Record[Idx++];
5153 Info.NumTemplParamLists = NumTPLists;
5154 if (NumTPLists) {
5155 Info.TemplParamLists = new (*Context) TemplateParameterList*[NumTPLists];
5156 for (unsigned i=0; i != NumTPLists; ++i)
5157 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
5158 }
5159}
5160
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005161TemplateName
Douglas Gregora6895d82011-07-22 16:00:58 +00005162ASTReader::ReadTemplateName(Module &F, const RecordData &Record,
Douglas Gregor5590be02011-01-15 06:45:20 +00005163 unsigned &Idx) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005164 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005165 switch (Kind) {
5166 case TemplateName::Template:
Douglas Gregor7fb09192011-07-21 22:35:25 +00005167 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005168
5169 case TemplateName::OverloadedTemplate: {
5170 unsigned size = Record[Idx++];
5171 UnresolvedSet<8> Decls;
5172 while (size--)
Douglas Gregor7fb09192011-07-21 22:35:25 +00005173 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005174
5175 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
5176 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005177
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005178 case TemplateName::QualifiedTemplate: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005179 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005180 bool hasTemplKeyword = Record[Idx++];
Douglas Gregor7fb09192011-07-21 22:35:25 +00005181 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005182 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
5183 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005184
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005185 case TemplateName::DependentTemplate: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005186 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005187 if (Record[Idx++]) // isIdentifier
5188 return Context->getDependentTemplateName(NNS,
Douglas Gregora3e41532011-07-28 20:55:49 +00005189 GetIdentifierInfo(F, Record,
5190 Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005191 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005192 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005193 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005194
5195 case TemplateName::SubstTemplateTemplateParm: {
5196 TemplateTemplateParmDecl *param
Douglas Gregor7fb09192011-07-21 22:35:25 +00005197 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
John McCalld9dfe3a2011-06-30 08:33:18 +00005198 if (!param) return TemplateName();
5199 TemplateName replacement = ReadTemplateName(F, Record, Idx);
5200 return Context->getSubstTemplateTemplateParm(param, replacement);
5201 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005202
5203 case TemplateName::SubstTemplateTemplateParmPack: {
5204 TemplateTemplateParmDecl *Param
Douglas Gregor7fb09192011-07-21 22:35:25 +00005205 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Douglas Gregor5590be02011-01-15 06:45:20 +00005206 if (!Param)
5207 return TemplateName();
5208
5209 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
5210 if (ArgPack.getKind() != TemplateArgument::Pack)
5211 return TemplateName();
5212
5213 return Context->getSubstTemplateTemplateParmPack(Param, ArgPack);
5214 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005215 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005216
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005217 assert(0 && "Unhandled template name kind!");
5218 return TemplateName();
5219}
5220
5221TemplateArgument
Douglas Gregora6895d82011-07-22 16:00:58 +00005222ASTReader::ReadTemplateArgument(Module &F,
Sebastian Redlc67764e2010-07-22 22:43:28 +00005223 const RecordData &Record, unsigned &Idx) {
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005224 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
5225 switch (Kind) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005226 case TemplateArgument::Null:
5227 return TemplateArgument();
5228 case TemplateArgument::Type:
Douglas Gregor903b7e92011-07-22 00:38:23 +00005229 return TemplateArgument(readType(F, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005230 case TemplateArgument::Declaration:
Douglas Gregor7fb09192011-07-21 22:35:25 +00005231 return TemplateArgument(ReadDecl(F, Record, Idx));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00005232 case TemplateArgument::Integral: {
5233 llvm::APSInt Value = ReadAPSInt(Record, Idx);
Douglas Gregor903b7e92011-07-22 00:38:23 +00005234 QualType T = readType(F, Record, Idx);
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00005235 return TemplateArgument(Value, T);
5236 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005237 case TemplateArgument::Template:
Douglas Gregor5590be02011-01-15 06:45:20 +00005238 return TemplateArgument(ReadTemplateName(F, Record, Idx));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005239 case TemplateArgument::TemplateExpansion: {
Douglas Gregor5590be02011-01-15 06:45:20 +00005240 TemplateName Name = ReadTemplateName(F, Record, Idx);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005241 llvm::Optional<unsigned> NumTemplateExpansions;
5242 if (unsigned NumExpansions = Record[Idx++])
5243 NumTemplateExpansions = NumExpansions - 1;
5244 return TemplateArgument(Name, NumTemplateExpansions);
Douglas Gregoreb29d182011-01-05 17:40:24 +00005245 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005246 case TemplateArgument::Expression:
Sebastian Redl2c373b92010-10-05 15:59:54 +00005247 return TemplateArgument(ReadExpr(F));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005248 case TemplateArgument::Pack: {
5249 unsigned NumArgs = Record[Idx++];
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005250 TemplateArgument *Args = new (*Context) TemplateArgument[NumArgs];
5251 for (unsigned I = 0; I != NumArgs; ++I)
5252 Args[I] = ReadTemplateArgument(F, Record, Idx);
5253 return TemplateArgument(Args, NumArgs);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005254 }
5255 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005256
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00005257 assert(0 && "Unhandled template argument kind!");
5258 return TemplateArgument();
5259}
5260
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005261TemplateParameterList *
Douglas Gregora6895d82011-07-22 16:00:58 +00005262ASTReader::ReadTemplateParameterList(Module &F,
Sebastian Redl2c373b92010-10-05 15:59:54 +00005263 const RecordData &Record, unsigned &Idx) {
5264 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
5265 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
5266 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005267
5268 unsigned NumParams = Record[Idx++];
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005269 SmallVector<NamedDecl *, 16> Params;
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005270 Params.reserve(NumParams);
5271 while (NumParams--)
Douglas Gregor7fb09192011-07-21 22:35:25 +00005272 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005273
5274 TemplateParameterList* TemplateParams =
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005275 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
5276 Params.data(), Params.size(), RAngleLoc);
5277 return TemplateParams;
5278}
5279
5280void
Sebastian Redl2c499f62010-08-18 23:56:43 +00005281ASTReader::
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005282ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
Douglas Gregora6895d82011-07-22 16:00:58 +00005283 Module &F, const RecordData &Record,
Sebastian Redl2c373b92010-10-05 15:59:54 +00005284 unsigned &Idx) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005285 unsigned NumTemplateArgs = Record[Idx++];
5286 TemplArgs.reserve(NumTemplateArgs);
5287 while (NumTemplateArgs--)
Sebastian Redl2c373b92010-10-05 15:59:54 +00005288 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005289}
5290
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005291/// \brief Read a UnresolvedSet structure.
Douglas Gregora6895d82011-07-22 16:00:58 +00005292void ASTReader::ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005293 const RecordData &Record, unsigned &Idx) {
5294 unsigned NumDecls = Record[Idx++];
5295 while (NumDecls--) {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005296 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005297 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
5298 Set.addDecl(D, AS);
5299 }
5300}
5301
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005302CXXBaseSpecifier
Douglas Gregora6895d82011-07-22 16:00:58 +00005303ASTReader::ReadCXXBaseSpecifier(Module &F,
Nick Lewycky19b9f952010-07-26 16:56:01 +00005304 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005305 bool isVirtual = static_cast<bool>(Record[Idx++]);
5306 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
5307 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Sebastian Redl08905022011-02-05 19:23:19 +00005308 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Sebastian Redl2c373b92010-10-05 15:59:54 +00005309 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
5310 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor752a5952011-01-03 22:36:02 +00005311 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redl08905022011-02-05 19:23:19 +00005312 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Douglas Gregor752a5952011-01-03 22:36:02 +00005313 EllipsisLoc);
Sebastian Redl08905022011-02-05 19:23:19 +00005314 Result.setInheritConstructors(inheritConstructors);
5315 return Result;
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005316}
5317
Alexis Hunt1d792652011-01-08 20:30:50 +00005318std::pair<CXXCtorInitializer **, unsigned>
Douglas Gregora6895d82011-07-22 16:00:58 +00005319ASTReader::ReadCXXCtorInitializers(Module &F, const RecordData &Record,
Alexis Hunt1d792652011-01-08 20:30:50 +00005320 unsigned &Idx) {
5321 CXXCtorInitializer **CtorInitializers = 0;
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005322 unsigned NumInitializers = Record[Idx++];
5323 if (NumInitializers) {
5324 ASTContext &C = *getContext();
5325
Alexis Hunt1d792652011-01-08 20:30:50 +00005326 CtorInitializers
5327 = new (C) CXXCtorInitializer*[NumInitializers];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005328 for (unsigned i=0; i != NumInitializers; ++i) {
5329 TypeSourceInfo *BaseClassInfo = 0;
5330 bool IsBaseVirtual = false;
5331 FieldDecl *Member = 0;
Francois Pichetd583da02010-12-04 09:14:42 +00005332 IndirectFieldDecl *IndirectMember = 0;
Alexis Hunt37a477f2011-05-04 01:19:08 +00005333 CXXConstructorDecl *Target = 0;
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005334
Alexis Hunt37a477f2011-05-04 01:19:08 +00005335 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
5336 switch (Type) {
5337 case CTOR_INITIALIZER_BASE:
Sebastian Redl2c373b92010-10-05 15:59:54 +00005338 BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005339 IsBaseVirtual = Record[Idx++];
Alexis Hunt37a477f2011-05-04 01:19:08 +00005340 break;
5341
5342 case CTOR_INITIALIZER_DELEGATING:
Douglas Gregor7fb09192011-07-21 22:35:25 +00005343 Target = ReadDeclAs<CXXConstructorDecl>(F, Record, Idx);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005344 break;
5345
5346 case CTOR_INITIALIZER_MEMBER:
Douglas Gregor7fb09192011-07-21 22:35:25 +00005347 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005348 break;
5349
5350 case CTOR_INITIALIZER_INDIRECT_MEMBER:
Douglas Gregor7fb09192011-07-21 22:35:25 +00005351 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005352 break;
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005353 }
Alexis Hunt37a477f2011-05-04 01:19:08 +00005354
Douglas Gregor44e7df62011-01-04 00:32:56 +00005355 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redl2c373b92010-10-05 15:59:54 +00005356 Expr *Init = ReadExpr(F);
Sebastian Redl2c373b92010-10-05 15:59:54 +00005357 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
5358 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005359 bool IsWritten = Record[Idx++];
5360 unsigned SourceOrderOrNumArrayIndices;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005361 SmallVector<VarDecl *, 8> Indices;
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005362 if (IsWritten) {
5363 SourceOrderOrNumArrayIndices = Record[Idx++];
5364 } else {
5365 SourceOrderOrNumArrayIndices = Record[Idx++];
5366 Indices.reserve(SourceOrderOrNumArrayIndices);
5367 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
Douglas Gregor7fb09192011-07-21 22:35:25 +00005368 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005369 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005370
Alexis Hunt1d792652011-01-08 20:30:50 +00005371 CXXCtorInitializer *BOMInit;
Alexis Hunt37a477f2011-05-04 01:19:08 +00005372 if (Type == CTOR_INITIALIZER_BASE) {
Alexis Hunt1d792652011-01-08 20:30:50 +00005373 BOMInit = new (C) CXXCtorInitializer(C, BaseClassInfo, IsBaseVirtual,
5374 LParenLoc, Init, RParenLoc,
5375 MemberOrEllipsisLoc);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005376 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
5377 BOMInit = new (C) CXXCtorInitializer(C, MemberOrEllipsisLoc, LParenLoc,
5378 Target, Init, RParenLoc);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005379 } else if (IsWritten) {
Francois Pichetd583da02010-12-04 09:14:42 +00005380 if (Member)
Alexis Hunt1d792652011-01-08 20:30:50 +00005381 BOMInit = new (C) CXXCtorInitializer(C, Member, MemberOrEllipsisLoc,
5382 LParenLoc, Init, RParenLoc);
Francois Pichetd583da02010-12-04 09:14:42 +00005383 else
Alexis Hunt1d792652011-01-08 20:30:50 +00005384 BOMInit = new (C) CXXCtorInitializer(C, IndirectMember,
5385 MemberOrEllipsisLoc, LParenLoc,
5386 Init, RParenLoc);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005387 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00005388 BOMInit = CXXCtorInitializer::Create(C, Member, MemberOrEllipsisLoc,
5389 LParenLoc, Init, RParenLoc,
5390 Indices.data(), Indices.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005391 }
5392
Argyrios Kyrtzidisd05f3e32010-09-06 19:04:27 +00005393 if (IsWritten)
5394 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
Alexis Hunt1d792652011-01-08 20:30:50 +00005395 CtorInitializers[i] = BOMInit;
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005396 }
5397 }
5398
Alexis Hunt1d792652011-01-08 20:30:50 +00005399 return std::make_pair(CtorInitializers, NumInitializers);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005400}
5401
Chris Lattnerca025db2010-05-07 21:43:38 +00005402NestedNameSpecifier *
Douglas Gregora6895d82011-07-22 16:00:58 +00005403ASTReader::ReadNestedNameSpecifier(Module &F,
Douglas Gregor7fb09192011-07-21 22:35:25 +00005404 const RecordData &Record, unsigned &Idx) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005405 unsigned N = Record[Idx++];
5406 NestedNameSpecifier *NNS = 0, *Prev = 0;
5407 for (unsigned I = 0; I != N; ++I) {
5408 NestedNameSpecifier::SpecifierKind Kind
5409 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5410 switch (Kind) {
5411 case NestedNameSpecifier::Identifier: {
Douglas Gregora3e41532011-07-28 20:55:49 +00005412 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Chris Lattnerca025db2010-05-07 21:43:38 +00005413 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
5414 break;
5415 }
5416
5417 case NestedNameSpecifier::Namespace: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005418 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Chris Lattnerca025db2010-05-07 21:43:38 +00005419 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
5420 break;
5421 }
5422
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005423 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005424 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005425 NNS = NestedNameSpecifier::Create(*Context, Prev, Alias);
5426 break;
5427 }
5428
Chris Lattnerca025db2010-05-07 21:43:38 +00005429 case NestedNameSpecifier::TypeSpec:
5430 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregor903b7e92011-07-22 00:38:23 +00005431 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
Douglas Gregor0cdc8322010-12-10 17:03:06 +00005432 if (!T)
5433 return 0;
5434
Chris Lattnerca025db2010-05-07 21:43:38 +00005435 bool Template = Record[Idx++];
5436 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
5437 break;
5438 }
5439
5440 case NestedNameSpecifier::Global: {
5441 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
5442 // No associated value, and there can't be a prefix.
5443 break;
5444 }
Chris Lattnerca025db2010-05-07 21:43:38 +00005445 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00005446 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00005447 }
5448 return NNS;
5449}
5450
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005451NestedNameSpecifierLoc
Douglas Gregora6895d82011-07-22 16:00:58 +00005452ASTReader::ReadNestedNameSpecifierLoc(Module &F, const RecordData &Record,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005453 unsigned &Idx) {
5454 unsigned N = Record[Idx++];
Douglas Gregor9b272512011-02-28 23:58:31 +00005455 NestedNameSpecifierLocBuilder Builder;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005456 for (unsigned I = 0; I != N; ++I) {
5457 NestedNameSpecifier::SpecifierKind Kind
5458 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5459 switch (Kind) {
5460 case NestedNameSpecifier::Identifier: {
Douglas Gregora3e41532011-07-28 20:55:49 +00005461 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005462 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor9b272512011-02-28 23:58:31 +00005463 Builder.Extend(*Context, II, Range.getBegin(), Range.getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005464 break;
5465 }
5466
5467 case NestedNameSpecifier::Namespace: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005468 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005469 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor9b272512011-02-28 23:58:31 +00005470 Builder.Extend(*Context, NS, Range.getBegin(), Range.getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005471 break;
5472 }
5473
5474 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005475 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005476 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor9b272512011-02-28 23:58:31 +00005477 Builder.Extend(*Context, Alias, Range.getBegin(), Range.getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005478 break;
5479 }
5480
5481 case NestedNameSpecifier::TypeSpec:
5482 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005483 bool Template = Record[Idx++];
5484 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
5485 if (!T)
5486 return NestedNameSpecifierLoc();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005487 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor9b272512011-02-28 23:58:31 +00005488
5489 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
5490 Builder.Extend(*Context,
5491 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
5492 T->getTypeLoc(), ColonColonLoc);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005493 break;
5494 }
5495
5496 case NestedNameSpecifier::Global: {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005497 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor9b272512011-02-28 23:58:31 +00005498 Builder.MakeGlobal(*Context, ColonColonLoc);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005499 break;
5500 }
5501 }
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005502 }
5503
Douglas Gregor9b272512011-02-28 23:58:31 +00005504 return Builder.getWithLocInContext(*Context);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005505}
5506
Chris Lattnerca025db2010-05-07 21:43:38 +00005507SourceRange
Douglas Gregora6895d82011-07-22 16:00:58 +00005508ASTReader::ReadSourceRange(Module &F, const RecordData &Record,
Sebastian Redl2c373b92010-10-05 15:59:54 +00005509 unsigned &Idx) {
5510 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
5511 SourceLocation end = ReadSourceLocation(F, Record, Idx);
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00005512 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00005513}
5514
Douglas Gregor1daeb692009-04-13 18:14:40 +00005515/// \brief Read an integral value
Sebastian Redl2c499f62010-08-18 23:56:43 +00005516llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00005517 unsigned BitWidth = Record[Idx++];
5518 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
5519 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
5520 Idx += NumWords;
5521 return Result;
5522}
5523
5524/// \brief Read a signed integral value
Sebastian Redl2c499f62010-08-18 23:56:43 +00005525llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00005526 bool isUnsigned = Record[Idx++];
5527 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
5528}
5529
Douglas Gregore0a3a512009-04-14 21:55:33 +00005530/// \brief Read a floating-point value
Sebastian Redl2c499f62010-08-18 23:56:43 +00005531llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00005532 return llvm::APFloat(ReadAPInt(Record, Idx));
5533}
5534
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00005535// \brief Read a string
Sebastian Redl2c499f62010-08-18 23:56:43 +00005536std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00005537 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00005538 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00005539 Idx += Len;
5540 return Result;
5541}
5542
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00005543VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
5544 unsigned &Idx) {
5545 unsigned Major = Record[Idx++];
5546 unsigned Minor = Record[Idx++];
5547 unsigned Subminor = Record[Idx++];
5548 if (Minor == 0)
5549 return VersionTuple(Major);
5550 if (Subminor == 0)
5551 return VersionTuple(Major, Minor - 1);
5552 return VersionTuple(Major, Minor - 1, Subminor - 1);
5553}
5554
Douglas Gregora6895d82011-07-22 16:00:58 +00005555CXXTemporary *ASTReader::ReadCXXTemporary(Module &F,
Douglas Gregor7fb09192011-07-21 22:35:25 +00005556 const RecordData &Record,
Chris Lattnercba86142010-05-10 00:25:06 +00005557 unsigned &Idx) {
Douglas Gregor7fb09192011-07-21 22:35:25 +00005558 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Chris Lattnercba86142010-05-10 00:25:06 +00005559 return CXXTemporary::Create(*Context, Decl);
5560}
5561
Sebastian Redl2c499f62010-08-18 23:56:43 +00005562DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00005563 return Diag(SourceLocation(), DiagID);
5564}
5565
Sebastian Redl2c499f62010-08-18 23:56:43 +00005566DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00005567 return Diags.Report(Loc, DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00005568}
Douglas Gregora9af1d12009-04-17 00:04:06 +00005569
Douglas Gregora868bbd2009-04-21 22:25:48 +00005570/// \brief Retrieve the identifier table associated with the
5571/// preprocessor.
Sebastian Redl2c499f62010-08-18 23:56:43 +00005572IdentifierTable &ASTReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00005573 assert(PP && "Forgot to set Preprocessor ?");
5574 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00005575}
5576
Douglas Gregora9af1d12009-04-17 00:04:06 +00005577/// \brief Record that the given ID maps to the given switch-case
5578/// statement.
Sebastian Redl2c499f62010-08-18 23:56:43 +00005579void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Douglas Gregora9af1d12009-04-17 00:04:06 +00005580 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
5581 SwitchCaseStmts[ID] = SC;
5582}
5583
5584/// \brief Retrieve the switch-case statement with the given ID.
Sebastian Redl2c499f62010-08-18 23:56:43 +00005585SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Douglas Gregora9af1d12009-04-17 00:04:06 +00005586 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
5587 return SwitchCaseStmts[ID];
5588}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00005589
Argyrios Kyrtzidisd9f526f2010-10-28 09:29:32 +00005590void ASTReader::ClearSwitchCaseIDs() {
5591 SwitchCaseStmts.clear();
5592}
5593
Sebastian Redl2c499f62010-08-18 23:56:43 +00005594void ASTReader::FinishedDeserializing() {
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00005595 assert(NumCurrentElementsDeserializing &&
5596 "FinishedDeserializing not paired with StartedDeserializing");
5597 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregor1342e842009-07-06 18:54:52 +00005598 // If any identifiers with corresponding top-level declarations have
5599 // been loaded, load those declarations now.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00005600 while (!PendingIdentifierInfos.empty()) {
5601 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
5602 PendingIdentifierInfos.front().DeclIDs, true);
5603 PendingIdentifierInfos.pop_front();
Douglas Gregor1342e842009-07-06 18:54:52 +00005604 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00005605
Argyrios Kyrtzidis9fdd2542011-02-12 07:50:47 +00005606 // Ready to load previous declarations of Decls that were delayed.
5607 while (!PendingPreviousDecls.empty()) {
5608 loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
5609 PendingPreviousDecls.front().second);
5610 PendingPreviousDecls.pop_front();
5611 }
5612
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00005613 // We are not in recursive loading, so it's safe to pass the "interesting"
5614 // decls to the consumer.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00005615 if (Consumer)
5616 PassInterestingDeclsToConsumer();
Argyrios Kyrtzidisad5f95c2010-10-24 17:26:31 +00005617
5618 assert(PendingForwardRefs.size() == 0 &&
5619 "Some forward refs did not get linked to the definition!");
Douglas Gregor1342e842009-07-06 18:54:52 +00005620 }
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00005621 --NumCurrentElementsDeserializing;
Douglas Gregor1342e842009-07-06 18:54:52 +00005622}
Douglas Gregorb473b072010-08-19 00:28:17 +00005623
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005624ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorc567ba22011-07-22 16:35:34 +00005625 StringRef isysroot, bool DisableValidation,
Douglas Gregor606c4ac2011-02-05 19:42:43 +00005626 bool DisableStatCache)
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005627 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
5628 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
5629 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
Jonathan D. Turnerecc27402011-07-28 17:20:23 +00005630 Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
5631 RelocatablePCH(false), isysroot(isysroot),
Douglas Gregor925296b2011-07-19 16:10:42 +00005632 DisableValidation(DisableValidation),
Douglas Gregor606c4ac2011-02-05 19:42:43 +00005633 DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
Douglas Gregor925296b2011-07-19 16:10:42 +00005634 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor606c4ac2011-02-05 19:42:43 +00005635 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
5636 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
5637 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
5638 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
Jonathan D. Turner3766fdb2011-07-21 21:15:19 +00005639 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
5640 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
5641 NumCXXBaseSpecifiersLoaded(0)
Douglas Gregor606c4ac2011-02-05 19:42:43 +00005642{
Douglas Gregor925296b2011-07-19 16:10:42 +00005643 SourceMgr.setExternalSLocEntrySource(this);
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005644}
5645
5646ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorc567ba22011-07-22 16:35:34 +00005647 Diagnostic &Diags, StringRef isysroot,
Douglas Gregor606c4ac2011-02-05 19:42:43 +00005648 bool DisableValidation, bool DisableStatCache)
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005649 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Jonathan D. Turnerecc27402011-07-28 17:20:23 +00005650 Diags(Diags), SemaObj(0), PP(0), Context(0),
5651 Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
Douglas Gregor925296b2011-07-19 16:10:42 +00005652 RelocatablePCH(false), isysroot(isysroot),
5653 DisableValidation(DisableValidation), DisableStatCache(DisableStatCache),
5654 NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
5655 TotalNumSLocEntries(0), NumStatementsRead(0),
5656 TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
5657 NumSelectorsRead(0), NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
Sebastian Redlc1d035f2010-09-22 20:19:08 +00005658 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
5659 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Jonathan D. Turner3766fdb2011-07-21 21:15:19 +00005660 TotalVisibleDeclContexts(0), TotalModulesSizeInBits(0),
5661 NumCurrentElementsDeserializing(0), NumCXXBaseSpecifiersLoaded(0)
Douglas Gregor925296b2011-07-19 16:10:42 +00005662{
5663 SourceMgr.setExternalSLocEntrySource(this);
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005664}
5665
5666ASTReader::~ASTReader() {
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005667 for (DeclContextVisibleUpdatesPending::iterator
5668 I = PendingVisibleUpdates.begin(),
5669 E = PendingVisibleUpdates.end();
5670 I != E; ++I) {
5671 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
5672 F = I->second.end();
5673 J != F; ++J)
Douglas Gregorf7180622011-08-03 15:48:04 +00005674 delete static_cast<ASTDeclContextNameLookupTable*>(J->first);
Sebastian Redld7dce0a2010-08-24 00:50:04 +00005675 }
5676}
5677
Douglas Gregorab443b92011-08-20 04:39:52 +00005678//===----------------------------------------------------------------------===//
5679// Module implementation
5680//===----------------------------------------------------------------------===//
Douglas Gregora6895d82011-07-22 16:00:58 +00005681Module::Module(ModuleKind Kind)
Douglas Gregordf0c1512011-08-18 04:12:04 +00005682 : Kind(Kind), DirectlyImported(false), SizeInBits(0),
5683 LocalNumSLocEntries(0), SLocEntryBaseID(0),
Douglas Gregor925296b2011-07-19 16:10:42 +00005684 SLocEntryBaseOffset(0), SLocEntryOffsets(0),
5685 SLocFileOffsets(0), LocalNumIdentifiers(0),
Douglas Gregor00659902011-08-02 10:56:51 +00005686 IdentifierOffsets(0), BaseIdentifierID(0), IdentifierTableData(0),
5687 IdentifierLookupTable(0), BasePreprocessedEntityID(0),
5688 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
5689 BaseMacroDefinitionID(0), LocalNumHeaderFileInfos(0),
Douglas Gregor925296b2011-07-19 16:10:42 +00005690 HeaderFileInfoTableData(0), HeaderFileInfoTable(0),
Douglas Gregor4b123cb2011-07-28 04:50:02 +00005691 HeaderFileFrameworkStrings(0),
Douglas Gregor00659902011-08-02 10:56:51 +00005692 LocalNumSelectors(0), SelectorOffsets(0), BaseSelectorID(0),
Sebastian Redl949fe9e2010-09-22 00:42:27 +00005693 SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
Douglas Gregor00659902011-08-02 10:56:51 +00005694 DeclOffsets(0), BaseDeclID(0),
5695 LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0),
Douglas Gregor3b65ed02011-08-02 18:32:54 +00005696 LocalNumTypes(0), TypeOffsets(0), BaseTypeIndex(0), StatCache(0),
Jonathan D. Turner269f2562011-07-28 23:15:22 +00005697 NumPreallocatedPreprocessingEntities(0)
Douglas Gregorb473b072010-08-19 00:28:17 +00005698{}
5699
Douglas Gregora6895d82011-07-22 16:00:58 +00005700Module::~Module() {
Douglas Gregor94619c82011-08-24 19:03:07 +00005701 for (DeclContextInfosMap::iterator I = DeclContextInfos.begin(),
5702 E = DeclContextInfos.end();
5703 I != E; ++I) {
5704 if (I->second.NameLookupTableData)
5705 delete static_cast<ASTDeclContextNameLookupTable*>(
5706 I->second.NameLookupTableData);
5707 }
5708
Douglas Gregorb473b072010-08-19 00:28:17 +00005709 delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable);
Douglas Gregor09b69892011-02-10 17:09:37 +00005710 delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable);
Douglas Gregorb473b072010-08-19 00:28:17 +00005711 delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable);
5712}
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00005713
Douglas Gregor1cc9c062011-08-02 11:12:41 +00005714template<typename Key, typename Offset, unsigned InitialCapacity>
5715static void
5716dumpLocalRemap(StringRef Name,
5717 const ContinuousRangeMap<Key, Offset, InitialCapacity> &Map) {
5718 if (Map.begin() == Map.end())
5719 return;
5720
5721 typedef ContinuousRangeMap<Key, Offset, InitialCapacity> MapType;
5722 llvm::errs() << " " << Name << ":\n";
5723 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5724 I != IEnd; ++I) {
5725 llvm::errs() << " " << I->first << " -> " << I->second
5726 << "\n";
5727 }
5728}
5729
5730void Module::dump() {
5731 llvm::errs() << "\nModule: " << FileName << "\n";
5732 if (!Imports.empty()) {
5733 llvm::errs() << " Imports: ";
5734 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
5735 if (I)
5736 llvm::errs() << ", ";
5737 llvm::errs() << Imports[I]->FileName;
5738 }
5739 llvm::errs() << "\n";
5740 }
5741
5742 // Remapping tables.
5743 llvm::errs() << " Base source location offset: " << SLocEntryBaseOffset
5744 << '\n';
Douglas Gregorfddf5302011-08-04 19:00:50 +00005745 dumpLocalRemap("Source location offset local -> global map", SLocRemap);
5746
Douglas Gregor1ab036c2011-08-03 21:49:18 +00005747 llvm::errs() << " Base identifier ID: " << BaseIdentifierID << '\n'
Douglas Gregor2f555fc2011-08-04 18:56:47 +00005748 << " Number of identifiers: " << LocalNumIdentifiers << '\n';
Douglas Gregorfddf5302011-08-04 19:00:50 +00005749 dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap);
5750
5751 llvm::errs() << " Base selector ID: " << BaseSelectorID << '\n'
5752 << " Number of selectors: " << LocalNumSelectors << '\n';
5753 dumpLocalRemap("Selector ID local -> global map", SelectorRemap);
5754
Douglas Gregor2f555fc2011-08-04 18:56:47 +00005755 llvm::errs() << " Base preprocessed entity ID: " << BasePreprocessedEntityID
5756 << '\n'
Douglas Gregordab42432011-08-12 00:15:20 +00005757 << " Number of preprocessed entities: "
Douglas Gregor2f555fc2011-08-04 18:56:47 +00005758 << NumPreallocatedPreprocessingEntities << '\n';
Douglas Gregorfddf5302011-08-04 19:00:50 +00005759 dumpLocalRemap("Preprocessed entity ID local -> global map",
5760 PreprocessedEntityRemap);
5761
Douglas Gregora863b4b2011-08-04 16:36:56 +00005762 llvm::errs() << " Base macro definition ID: " << BaseMacroDefinitionID
5763 << '\n'
5764 << " Number of macro definitions: " << LocalNumMacroDefinitions
5765 << '\n';
Douglas Gregorfddf5302011-08-04 19:00:50 +00005766 dumpLocalRemap("Macro definition ID local -> global map",
5767 MacroDefinitionRemap);
5768
5769 llvm::errs() << " Base type index: " << BaseTypeIndex << '\n'
5770 << " Number of types: " << LocalNumTypes << '\n';
5771 dumpLocalRemap("Type index local -> global map", TypeRemap);
5772
Douglas Gregorf7180622011-08-03 15:48:04 +00005773 llvm::errs() << " Base decl ID: " << BaseDeclID << '\n'
5774 << " Number of decls: " << LocalNumDecls << '\n';
Douglas Gregorfddf5302011-08-04 19:00:50 +00005775 dumpLocalRemap("Decl ID local -> global map", DeclRemap);
Douglas Gregor1cc9c062011-08-02 11:12:41 +00005776}
5777
Douglas Gregorab443b92011-08-20 04:39:52 +00005778//===----------------------------------------------------------------------===//
5779// Module manager implementation
5780//===----------------------------------------------------------------------===//
5781
Jonathan D. Turnerecc27402011-07-28 17:20:23 +00005782Module *ModuleManager::lookup(StringRef Name) {
5783 const FileEntry *Entry = FileMgr.getFile(Name);
5784 return Modules[Entry];
5785}
5786
Jonathan D. Turnerdb1c9e32011-08-02 17:40:32 +00005787llvm::MemoryBuffer *ModuleManager::lookupBuffer(StringRef Name) {
5788 const FileEntry *Entry = FileMgr.getFile(Name);
5789 return InMemoryBuffers[Entry];
5790}
5791
Douglas Gregor4dd3e942011-08-19 02:29:29 +00005792std::pair<Module *, bool>
5793ModuleManager::addModule(StringRef FileName, ModuleKind Type,
5794 Module *ImportedBy, std::string &ErrorStr) {
Chad Rosier222e1872011-08-18 19:06:24 +00005795 const FileEntry *Entry = FileMgr.getFile(FileName);
Douglas Gregor4dd3e942011-08-19 02:29:29 +00005796 if (!Entry && FileName != "-") {
5797 ErrorStr = "file not found";
5798 return std::make_pair(static_cast<Module*>(0), false);
5799 }
5800
5801 // Check whether we already loaded this module, before
5802 Module *&ModuleEntry = Modules[Entry];
5803 bool NewModule = false;
5804 if (!ModuleEntry) {
5805 // Allocate a new module.
5806 Module *New = new Module(Type);
5807 New->FileName = FileName.str();
5808 Chain.push_back(New);
5809 NewModule = true;
5810 ModuleEntry = New;
5811
5812 // Load the contents of the module
5813 if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
5814 // The buffer was already provided for us.
5815 assert(Buffer && "Passed null buffer");
5816 New->Buffer.reset(Buffer);
5817 } else {
5818 // Open the AST file.
5819 llvm::error_code ec;
5820 if (FileName == "-") {
5821 ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
5822 if (ec)
5823 ErrorStr = ec.message();
5824 } else
5825 New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
5826
5827 if (!New->Buffer)
5828 return std::make_pair(static_cast<Module*>(0), false);
5829 }
5830
5831 // Initialize the stream
5832 New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
5833 (const unsigned char *)New->Buffer->getBufferEnd()); }
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00005834
Douglas Gregordf0c1512011-08-18 04:12:04 +00005835 if (ImportedBy) {
Douglas Gregor4dd3e942011-08-19 02:29:29 +00005836 ModuleEntry->ImportedBy.insert(ImportedBy);
5837 ImportedBy->Imports.insert(ModuleEntry);
Douglas Gregordf0c1512011-08-18 04:12:04 +00005838 } else {
Douglas Gregor4dd3e942011-08-19 02:29:29 +00005839 ModuleEntry->DirectlyImported = true;
Jonathan D. Turner10d52012011-07-29 18:09:09 +00005840 }
5841
Douglas Gregor4dd3e942011-08-19 02:29:29 +00005842 return std::make_pair(ModuleEntry, NewModule);
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00005843}
5844
Jonathan D. Turnerdb1c9e32011-08-02 17:40:32 +00005845void ModuleManager::addInMemoryBuffer(StringRef FileName,
5846 llvm::MemoryBuffer *Buffer) {
5847
5848 const FileEntry *Entry = FileMgr.getVirtualFile(FileName,
5849 Buffer->getBufferSize(), 0);
5850 InMemoryBuffers[Entry] = Buffer;
5851}
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00005852
Jonathan D. Turnerecc27402011-07-28 17:20:23 +00005853ModuleManager::ModuleManager(const FileSystemOptions &FSO) : FileMgr(FSO) { }
5854
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00005855ModuleManager::~ModuleManager() {
5856 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
5857 delete Chain[e - i - 1];
5858}
Douglas Gregorab443b92011-08-20 04:39:52 +00005859
5860void ModuleManager::visit(bool (*Visitor)(Module &M, void *UserData),
5861 void *UserData) {
5862 unsigned N = size();
5863
5864 // Record the number of incoming edges for each module. When we
5865 // encounter a module with no incoming edges, push it into the queue
5866 // to seed the queue.
5867 SmallVector<Module *, 4> Queue;
5868 Queue.reserve(N);
5869 llvm::DenseMap<Module *, unsigned> UnusedIncomingEdges;
5870 for (ModuleIterator M = begin(), MEnd = end(); M != MEnd; ++M) {
5871 if (unsigned Size = (*M)->ImportedBy.size())
5872 UnusedIncomingEdges[*M] = Size;
5873 else
5874 Queue.push_back(*M);
5875 }
5876
5877 llvm::SmallPtrSet<Module *, 4> Skipped;
5878 unsigned QueueStart = 0;
5879 while (QueueStart < Queue.size()) {
5880 Module *CurrentModule = Queue[QueueStart++];
5881
5882 // Check whether this module should be skipped.
5883 if (Skipped.count(CurrentModule))
5884 continue;
5885
5886 if (Visitor(*CurrentModule, UserData)) {
5887 // The visitor has requested that cut off visitation of any
5888 // module that the current module depends on. To indicate this
5889 // behavior, we mark all of the reachable modules as having N
5890 // incoming edges (which is impossible otherwise).
5891 SmallVector<Module *, 4> Stack;
5892 Stack.push_back(CurrentModule);
5893 Skipped.insert(CurrentModule);
5894 while (!Stack.empty()) {
5895 Module *NextModule = Stack.back();
5896 Stack.pop_back();
5897
5898 // For any module that this module depends on, push it on the
5899 // stack (if it hasn't already been marked as visited).
5900 for (llvm::SetVector<Module *>::iterator
5901 M = NextModule->Imports.begin(),
5902 MEnd = NextModule->Imports.end();
5903 M != MEnd; ++M) {
5904 if (Skipped.insert(*M))
5905 Stack.push_back(*M);
5906 }
5907 }
5908 continue;
5909 }
5910
5911 // For any module that this module depends on, push it on the
5912 // stack (if it hasn't already been marked as visited).
5913 for (llvm::SetVector<Module *>::iterator M = CurrentModule->Imports.begin(),
5914 MEnd = CurrentModule->Imports.end();
5915 M != MEnd; ++M) {
5916
5917 // Remove our current module as an impediment to visiting the
5918 // module we depend on. If we were the last unvisited module
5919 // that depends on this particular module, push it into the
5920 // queue to be visited.
5921 unsigned &NumUnusedEdges = UnusedIncomingEdges[*M];
5922 if (NumUnusedEdges && (--NumUnusedEdges == 0))
5923 Queue.push_back(*M);
5924 }
5925 }
5926}
Douglas Gregor1257f972011-08-24 21:27:34 +00005927
5928/// \brief Perform a depth-first visit of the current module.
5929static bool visitDepthFirst(Module &M,
5930 bool (*Visitor)(Module &M, bool Preorder,
5931 void *UserData),
5932 void *UserData,
5933 llvm::SmallPtrSet<Module *, 4> &Visited) {
5934 // Preorder visitation
5935 if (Visitor(M, /*Preorder=*/true, UserData))
5936 return true;
5937
5938 // Visit children
5939 for (llvm::SetVector<Module *>::iterator IM = M.Imports.begin(),
5940 IMEnd = M.Imports.end();
5941 IM != IMEnd; ++IM) {
5942 if (!Visited.insert(*IM))
5943 continue;
5944
5945 if (visitDepthFirst(**IM, Visitor, UserData, Visited))
5946 return true;
5947 }
5948
5949 // Postorder visitation
5950 return Visitor(M, /*Preorder=*/false, UserData);
5951}
5952
5953void ModuleManager::visitDepthFirst(bool (*Visitor)(Module &M, bool Preorder,
5954 void *UserData),
5955 void *UserData) {
5956 llvm::SmallPtrSet<Module *, 4> Visited;
5957 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
5958 if (!Visited.insert(Chain[I]))
5959 continue;
5960
5961 if (::visitDepthFirst(*Chain[I], Visitor, UserData, Visited))
5962 return;
5963 }
5964}