ASTReader.cpp revision f29f0a28c4d9599b389bbb6d186e14af753dc5a3
1a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//
3a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//                     The LLVM Compiler Infrastructure
46657678c3d86395084f6a699e73614195f06c445David 'Digit' Turner//
5a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner// This file is distributed under the University of Illinois Open Source
6a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner// License. See LICENSE.TXT for details.
7a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//
8a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//===----------------------------------------------------------------------===//
9a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//
10a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//  This file defines the ASTReader class, which reads AST files.
11a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//
12a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//===----------------------------------------------------------------------===//
13a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner
14a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Serialization/ASTReader.h"
15a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Serialization/ASTDeserializationListener.h"
16a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Frontend/FrontendDiagnostic.h"
17a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Frontend/Utils.h"
18a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Sema/Sema.h"
19a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/AST/ASTConsumer.h"
20a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/AST/ASTContext.h"
21a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/AST/Expr.h"
22a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/AST/Type.h"
23a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/AST/TypeLocVisitor.h"
24a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Lex/MacroInfo.h"
25a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Lex/PreprocessingRecord.h"
26a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Lex/Preprocessor.h"
27a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Lex/HeaderSearch.h"
28a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/OnDiskHashTable.h"
29a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/SourceManager.h"
30a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/SourceManagerInternals.h"
31a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/FileManager.h"
32a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/TargetInfo.h"
33a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "clang/Basic/Version.h"
34a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "llvm/ADT/StringExtras.h"
35a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "llvm/Bitcode/BitstreamReader.h"
36a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "llvm/Support/MemoryBuffer.h"
37a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "llvm/Support/ErrorHandling.h"
38a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include "llvm/System/Path.h"
39a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include <algorithm>
40a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include <iterator>
41a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include <cstdio>
42a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#include <sys/stat.h>
43a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turnerusing namespace clang;
44a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner
45a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//===----------------------------------------------------------------------===//
46a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner// PCH validator implementation
47a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner//===----------------------------------------------------------------------===//
48a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner
49a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' TurnerASTReaderListener::~ASTReaderListener() {}
50a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner
51a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turnerbool
52a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' TurnerPCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
53a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  const LangOptions &PPLangOpts = PP.getLangOptions();
54a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#define PARSE_LANGOPT_BENIGN(Option)
55a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#define PARSE_LANGOPT_IMPORTANT(Option, DiagID)                    \
56a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  if (PPLangOpts.Option != LangOpts.Option) {                      \
57a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner    Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option;   \
58a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner    return true;                                                   \
59a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  }
60a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner
61a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(Trigraphs);
62a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(BCPLComment);
63a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(DollarIdents);
64a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(AsmPreprocessor);
65a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
66a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
67a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(ImplicitInt);
68a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(Digraphs);
69a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(HexFloats);
70a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
71a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
72a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
73a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
74a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(CXXOperatorName);
75a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
76a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
77a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
78a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
79a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner                          diag::warn_pch_no_constant_cfstrings);
81a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(PascalStrings);
82a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(WritableStrings);
83a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
84a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner                          diag::warn_pch_lax_vector_conversions);
85a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
86a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
87a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
88a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
89a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
90a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
91a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
92a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner                          diag::warn_pch_thread_safe_statics);
93a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
94a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
95a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(EmitAllDecls);
96a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
97a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
98a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
99a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner                          diag::warn_pch_heinous_extensions);
100a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // FIXME: Most of the options below are benign if the macro wasn't
101a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // used. Unfortunately, this means that a PCH compiled without
102a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // optimization can't be used with optimization turned on, even
103a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // though the only thing that changes is whether __OPTIMIZE__ was
104a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // defined... but if __OPTIMIZE__ never showed up in the header, it
105a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // doesn't matter. We could consider making this some special kind
106a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  // of check.
107a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
108a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
109a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
110a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
111a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
112a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
113a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
114a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
115a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
116a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
117a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner    Reader.Diag(diag::warn_pch_gc_mode)
118a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner      << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner    return true;
120a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  }
121a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(getVisibilityMode());
122a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner                          diag::warn_pch_stack_protector);
124a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(InstantiationDepth);
125a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
126a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(CatchUndefined);
127a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
128a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner  PARSE_LANGOPT_BENIGN(SpellChecking);
129a49711e9c9b502d186114e600a045d33b5b61c4cDavid 'Digit' Turner#undef PARSE_LANGOPT_IMPORTANT
130#undef PARSE_LANGOPT_BENIGN
131
132  return false;
133}
134
135bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
136  if (Triple == PP.getTargetInfo().getTriple().str())
137    return false;
138
139  Reader.Diag(diag::warn_pch_target_triple)
140    << Triple << PP.getTargetInfo().getTriple().str();
141  return true;
142}
143
144struct EmptyStringRef {
145  bool operator ()(llvm::StringRef r) const { return r.empty(); }
146};
147struct EmptyBlock {
148  bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
149};
150
151static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
152                                PCHPredefinesBlocks R) {
153  // First, sum up the lengths.
154  unsigned LL = 0, RL = 0;
155  for (unsigned I = 0, N = L.size(); I != N; ++I) {
156    LL += L[I].size();
157  }
158  for (unsigned I = 0, N = R.size(); I != N; ++I) {
159    RL += R[I].Data.size();
160  }
161  if (LL != RL)
162    return false;
163  if (LL == 0 && RL == 0)
164    return true;
165
166  // Kick out empty parts, they confuse the algorithm below.
167  L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
168  R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
169
170  // Do it the hard way. At this point, both vectors must be non-empty.
171  llvm::StringRef LR = L[0], RR = R[0].Data;
172  unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
173  (void) RN;
174  for (;;) {
175    // Compare the current pieces.
176    if (LR.size() == RR.size()) {
177      // If they're the same length, it's pretty easy.
178      if (LR != RR)
179        return false;
180      // Both pieces are done, advance.
181      ++LI;
182      ++RI;
183      // If either string is done, they're both done, since they're the same
184      // length.
185      if (LI == LN) {
186        assert(RI == RN && "Strings not the same length after all?");
187        return true;
188      }
189      LR = L[LI];
190      RR = R[RI].Data;
191    } else if (LR.size() < RR.size()) {
192      // Right piece is longer.
193      if (!RR.startswith(LR))
194        return false;
195      ++LI;
196      assert(LI != LN && "Strings not the same length after all?");
197      RR = RR.substr(LR.size());
198      LR = L[LI];
199    } else {
200      // Left piece is longer.
201      if (!LR.startswith(RR))
202        return false;
203      ++RI;
204      assert(RI != RN && "Strings not the same length after all?");
205      LR = LR.substr(RR.size());
206      RR = R[RI].Data;
207    }
208  }
209}
210
211static std::pair<FileID, llvm::StringRef::size_type>
212FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
213  std::pair<FileID, llvm::StringRef::size_type> Res;
214  for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
215    Res.second = Buffers[I].Data.find(MacroDef);
216    if (Res.second != llvm::StringRef::npos) {
217      Res.first = Buffers[I].BufferID;
218      break;
219    }
220  }
221  return Res;
222}
223
224bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
225                                        llvm::StringRef OriginalFileName,
226                                        std::string &SuggestedPredefines) {
227  // We are in the context of an implicit include, so the predefines buffer will
228  // have a #include entry for the PCH file itself (as normalized by the
229  // preprocessor initialization). Find it and skip over it in the checking
230  // below.
231  llvm::SmallString<256> PCHInclude;
232  PCHInclude += "#include \"";
233  PCHInclude += NormalizeDashIncludePath(OriginalFileName);
234  PCHInclude += "\"\n";
235  std::pair<llvm::StringRef,llvm::StringRef> Split =
236    llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
237  llvm::StringRef Left =  Split.first, Right = Split.second;
238  if (Left == PP.getPredefines()) {
239    Error("Missing PCH include entry!");
240    return true;
241  }
242
243  // If the concatenation of all the PCH buffers is equal to the adjusted
244  // command line, we're done.
245  llvm::SmallVector<llvm::StringRef, 2> CommandLine;
246  CommandLine.push_back(Left);
247  CommandLine.push_back(Right);
248  if (EqualConcatenations(CommandLine, Buffers))
249    return false;
250
251  SourceManager &SourceMgr = PP.getSourceManager();
252
253  // The predefines buffers are different. Determine what the differences are,
254  // and whether they require us to reject the PCH file.
255  llvm::SmallVector<llvm::StringRef, 8> PCHLines;
256  for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
257    Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
258
259  llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
260  Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
261  Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
262
263  // Sort both sets of predefined buffer lines, since we allow some extra
264  // definitions and they may appear at any point in the output.
265  std::sort(CmdLineLines.begin(), CmdLineLines.end());
266  std::sort(PCHLines.begin(), PCHLines.end());
267
268  // Determine which predefines that were used to build the PCH file are missing
269  // from the command line.
270  std::vector<llvm::StringRef> MissingPredefines;
271  std::set_difference(PCHLines.begin(), PCHLines.end(),
272                      CmdLineLines.begin(), CmdLineLines.end(),
273                      std::back_inserter(MissingPredefines));
274
275  bool MissingDefines = false;
276  bool ConflictingDefines = false;
277  for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
278    llvm::StringRef Missing = MissingPredefines[I];
279    if (!Missing.startswith("#define ")) {
280      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
281      return true;
282    }
283
284    // This is a macro definition. Determine the name of the macro we're
285    // defining.
286    std::string::size_type StartOfMacroName = strlen("#define ");
287    std::string::size_type EndOfMacroName
288      = Missing.find_first_of("( \n\r", StartOfMacroName);
289    assert(EndOfMacroName != std::string::npos &&
290           "Couldn't find the end of the macro name");
291    llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
292
293    // Determine whether this macro was given a different definition on the
294    // command line.
295    std::string MacroDefStart = "#define " + MacroName.str();
296    std::string::size_type MacroDefLen = MacroDefStart.size();
297    llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
298      = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
299                         MacroDefStart);
300    for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
301      if (!ConflictPos->startswith(MacroDefStart)) {
302        // Different macro; we're done.
303        ConflictPos = CmdLineLines.end();
304        break;
305      }
306
307      assert(ConflictPos->size() > MacroDefLen &&
308             "Invalid #define in predefines buffer?");
309      if ((*ConflictPos)[MacroDefLen] != ' ' &&
310          (*ConflictPos)[MacroDefLen] != '(')
311        continue; // Longer macro name; keep trying.
312
313      // We found a conflicting macro definition.
314      break;
315    }
316
317    if (ConflictPos != CmdLineLines.end()) {
318      Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
319          << MacroName;
320
321      // Show the definition of this macro within the PCH file.
322      std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
323          FindMacro(Buffers, Missing);
324      assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
325      SourceLocation PCHMissingLoc =
326          SourceMgr.getLocForStartOfFile(MacroLoc.first)
327            .getFileLocWithOffset(MacroLoc.second);
328      Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
329
330      ConflictingDefines = true;
331      continue;
332    }
333
334    // If the macro doesn't conflict, then we'll just pick up the macro
335    // definition from the PCH file. Warn the user that they made a mistake.
336    if (ConflictingDefines)
337      continue; // Don't complain if there are already conflicting defs
338
339    if (!MissingDefines) {
340      Reader.Diag(diag::warn_cmdline_missing_macro_defs);
341      MissingDefines = true;
342    }
343
344    // Show the definition of this macro within the PCH file.
345    std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
346        FindMacro(Buffers, Missing);
347    assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
348    SourceLocation PCHMissingLoc =
349        SourceMgr.getLocForStartOfFile(MacroLoc.first)
350          .getFileLocWithOffset(MacroLoc.second);
351    Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
352  }
353
354  if (ConflictingDefines)
355    return true;
356
357  // Determine what predefines were introduced based on command-line
358  // parameters that were not present when building the PCH
359  // file. Extra #defines are okay, so long as the identifiers being
360  // defined were not used within the precompiled header.
361  std::vector<llvm::StringRef> ExtraPredefines;
362  std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
363                      PCHLines.begin(), PCHLines.end(),
364                      std::back_inserter(ExtraPredefines));
365  for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
366    llvm::StringRef &Extra = ExtraPredefines[I];
367    if (!Extra.startswith("#define ")) {
368      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
369      return true;
370    }
371
372    // This is an extra macro definition. Determine the name of the
373    // macro we're defining.
374    std::string::size_type StartOfMacroName = strlen("#define ");
375    std::string::size_type EndOfMacroName
376      = Extra.find_first_of("( \n\r", StartOfMacroName);
377    assert(EndOfMacroName != std::string::npos &&
378           "Couldn't find the end of the macro name");
379    llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
380
381    // Check whether this name was used somewhere in the PCH file. If
382    // so, defining it as a macro could change behavior, so we reject
383    // the PCH file.
384    if (IdentifierInfo *II = Reader.get(MacroName)) {
385      Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
386      return true;
387    }
388
389    // Add this definition to the suggested predefines buffer.
390    SuggestedPredefines += Extra;
391    SuggestedPredefines += '\n';
392  }
393
394  // If we get here, it's because the predefines buffer had compatible
395  // contents. Accept the PCH file.
396  return false;
397}
398
399void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
400                                      unsigned ID) {
401  PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
402  ++NumHeaderInfos;
403}
404
405void PCHValidator::ReadCounter(unsigned Value) {
406  PP.setCounterValue(Value);
407}
408
409//===----------------------------------------------------------------------===//
410// AST reader implementation
411//===----------------------------------------------------------------------===//
412
413ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
414                     const char *isysroot, bool DisableValidation)
415  : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
416    SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
417    Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
418    Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
419    NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
420    TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
421    NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
422    NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
423    TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
424    TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
425    TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
426  RelocatablePCH = false;
427}
428
429ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
430                     Diagnostic &Diags, const char *isysroot,
431                     bool DisableValidation)
432  : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
433    Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
434    isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
435    NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
436    NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
437    TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
438    NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
439    NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
440    NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
441    NumCurrentElementsDeserializing(0) {
442  RelocatablePCH = false;
443}
444
445ASTReader::~ASTReader() {
446  for (unsigned i = 0, e = Chain.size(); i != e; ++i)
447    delete Chain[e - i - 1];
448}
449
450ASTReader::PerFileData::PerFileData()
451  : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
452    LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
453    IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
454    LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
455    NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
456    SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
457{}
458
459void
460ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
461  DeserializationListener = Listener;
462  if (DeserializationListener)
463    DeserializationListener->SetReader(this);
464}
465
466
467namespace {
468class ASTSelectorLookupTrait {
469  ASTReader &Reader;
470
471public:
472  struct data_type {
473    pch::SelectorID ID;
474    ObjCMethodList Instance, Factory;
475  };
476
477  typedef Selector external_key_type;
478  typedef external_key_type internal_key_type;
479
480  explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { }
481
482  static bool EqualKey(const internal_key_type& a,
483                       const internal_key_type& b) {
484    return a == b;
485  }
486
487  static unsigned ComputeHash(Selector Sel) {
488    unsigned N = Sel.getNumArgs();
489    if (N == 0)
490      ++N;
491    unsigned R = 5381;
492    for (unsigned I = 0; I != N; ++I)
493      if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
494        R = llvm::HashString(II->getName(), R);
495    return R;
496  }
497
498  // This hopefully will just get inlined and removed by the optimizer.
499  static const internal_key_type&
500  GetInternalKey(const external_key_type& x) { return x; }
501
502  static std::pair<unsigned, unsigned>
503  ReadKeyDataLength(const unsigned char*& d) {
504    using namespace clang::io;
505    unsigned KeyLen = ReadUnalignedLE16(d);
506    unsigned DataLen = ReadUnalignedLE16(d);
507    return std::make_pair(KeyLen, DataLen);
508  }
509
510  internal_key_type ReadKey(const unsigned char* d, unsigned) {
511    using namespace clang::io;
512    SelectorTable &SelTable = Reader.getContext()->Selectors;
513    unsigned N = ReadUnalignedLE16(d);
514    IdentifierInfo *FirstII
515      = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
516    if (N == 0)
517      return SelTable.getNullarySelector(FirstII);
518    else if (N == 1)
519      return SelTable.getUnarySelector(FirstII);
520
521    llvm::SmallVector<IdentifierInfo *, 16> Args;
522    Args.push_back(FirstII);
523    for (unsigned I = 1; I != N; ++I)
524      Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
525
526    return SelTable.getSelector(N, Args.data());
527  }
528
529  data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
530    using namespace clang::io;
531
532    data_type Result;
533
534    Result.ID = ReadUnalignedLE32(d);
535    unsigned NumInstanceMethods = ReadUnalignedLE16(d);
536    unsigned NumFactoryMethods = ReadUnalignedLE16(d);
537
538    // Load instance methods
539    ObjCMethodList *Prev = 0;
540    for (unsigned I = 0; I != NumInstanceMethods; ++I) {
541      ObjCMethodDecl *Method
542        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
543      if (!Result.Instance.Method) {
544        // This is the first method, which is the easy case.
545        Result.Instance.Method = Method;
546        Prev = &Result.Instance;
547        continue;
548      }
549
550      ObjCMethodList *Mem =
551        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
552      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
553      Prev = Prev->Next;
554    }
555
556    // Load factory methods
557    Prev = 0;
558    for (unsigned I = 0; I != NumFactoryMethods; ++I) {
559      ObjCMethodDecl *Method
560        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
561      if (!Result.Factory.Method) {
562        // This is the first method, which is the easy case.
563        Result.Factory.Method = Method;
564        Prev = &Result.Factory;
565        continue;
566      }
567
568      ObjCMethodList *Mem =
569        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
570      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
571      Prev = Prev->Next;
572    }
573
574    return Result;
575  }
576};
577
578} // end anonymous namespace
579
580/// \brief The on-disk hash table used for the global method pool.
581typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
582  ASTSelectorLookupTable;
583
584namespace {
585class ASTIdentifierLookupTrait {
586  ASTReader &Reader;
587  llvm::BitstreamCursor &Stream;
588
589  // If we know the IdentifierInfo in advance, it is here and we will
590  // not build a new one. Used when deserializing information about an
591  // identifier that was constructed before the AST file was read.
592  IdentifierInfo *KnownII;
593
594public:
595  typedef IdentifierInfo * data_type;
596
597  typedef const std::pair<const char*, unsigned> external_key_type;
598
599  typedef external_key_type internal_key_type;
600
601  ASTIdentifierLookupTrait(ASTReader &Reader, llvm::BitstreamCursor &Stream,
602                           IdentifierInfo *II = 0)
603    : Reader(Reader), Stream(Stream), KnownII(II) { }
604
605  static bool EqualKey(const internal_key_type& a,
606                       const internal_key_type& b) {
607    return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
608                                  : false;
609  }
610
611  static unsigned ComputeHash(const internal_key_type& a) {
612    return llvm::HashString(llvm::StringRef(a.first, a.second));
613  }
614
615  // This hopefully will just get inlined and removed by the optimizer.
616  static const internal_key_type&
617  GetInternalKey(const external_key_type& x) { return x; }
618
619  static std::pair<unsigned, unsigned>
620  ReadKeyDataLength(const unsigned char*& d) {
621    using namespace clang::io;
622    unsigned DataLen = ReadUnalignedLE16(d);
623    unsigned KeyLen = ReadUnalignedLE16(d);
624    return std::make_pair(KeyLen, DataLen);
625  }
626
627  static std::pair<const char*, unsigned>
628  ReadKey(const unsigned char* d, unsigned n) {
629    assert(n >= 2 && d[n-1] == '\0');
630    return std::make_pair((const char*) d, n-1);
631  }
632
633  IdentifierInfo *ReadData(const internal_key_type& k,
634                           const unsigned char* d,
635                           unsigned DataLen) {
636    using namespace clang::io;
637    pch::IdentID ID = ReadUnalignedLE32(d);
638    bool IsInteresting = ID & 0x01;
639
640    // Wipe out the "is interesting" bit.
641    ID = ID >> 1;
642
643    if (!IsInteresting) {
644      // For uninteresting identifiers, just build the IdentifierInfo
645      // and associate it with the persistent ID.
646      IdentifierInfo *II = KnownII;
647      if (!II)
648        II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
649      Reader.SetIdentifierInfo(ID, II);
650      II->setIsFromAST();
651      return II;
652    }
653
654    unsigned Bits = ReadUnalignedLE16(d);
655    bool CPlusPlusOperatorKeyword = Bits & 0x01;
656    Bits >>= 1;
657    bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
658    Bits >>= 1;
659    bool Poisoned = Bits & 0x01;
660    Bits >>= 1;
661    bool ExtensionToken = Bits & 0x01;
662    Bits >>= 1;
663    bool hasMacroDefinition = Bits & 0x01;
664    Bits >>= 1;
665    unsigned ObjCOrBuiltinID = Bits & 0x3FF;
666    Bits >>= 10;
667
668    assert(Bits == 0 && "Extra bits in the identifier?");
669    DataLen -= 6;
670
671    // Build the IdentifierInfo itself and link the identifier ID with
672    // the new IdentifierInfo.
673    IdentifierInfo *II = KnownII;
674    if (!II)
675      II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
676    Reader.SetIdentifierInfo(ID, II);
677
678    // Set or check the various bits in the IdentifierInfo structure.
679    // Token IDs are read-only.
680    if (HasRevertedTokenIDToIdentifier)
681      II->RevertTokenIDToIdentifier();
682    II->setObjCOrBuiltinID(ObjCOrBuiltinID);
683    assert(II->isExtensionToken() == ExtensionToken &&
684           "Incorrect extension token flag");
685    (void)ExtensionToken;
686    II->setIsPoisoned(Poisoned);
687    assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
688           "Incorrect C++ operator keyword flag");
689    (void)CPlusPlusOperatorKeyword;
690
691    // If this identifier is a macro, deserialize the macro
692    // definition.
693    if (hasMacroDefinition) {
694      uint32_t Offset = ReadUnalignedLE32(d);
695      Reader.ReadMacroRecord(Stream, Offset);
696      DataLen -= 4;
697    }
698
699    // Read all of the declarations visible at global scope with this
700    // name.
701    if (Reader.getContext() == 0) return II;
702    if (DataLen > 0) {
703      llvm::SmallVector<uint32_t, 4> DeclIDs;
704      for (; DataLen > 0; DataLen -= 4)
705        DeclIDs.push_back(ReadUnalignedLE32(d));
706      Reader.SetGloballyVisibleDecls(II, DeclIDs);
707    }
708
709    II->setIsFromAST();
710    return II;
711  }
712};
713
714} // end anonymous namespace
715
716/// \brief The on-disk hash table used to contain information about
717/// all of the identifiers in the program.
718typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
719  ASTIdentifierLookupTable;
720
721void ASTReader::Error(const char *Msg) {
722  Diag(diag::err_fe_pch_malformed) << Msg;
723}
724
725/// \brief Tell the AST listener about the predefines buffers in the chain.
726bool ASTReader::CheckPredefinesBuffers() {
727  if (Listener)
728    return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
729                                          ActualOriginalFileName,
730                                          SuggestedPredefines);
731  return false;
732}
733
734//===----------------------------------------------------------------------===//
735// Source Manager Deserialization
736//===----------------------------------------------------------------------===//
737
738/// \brief Read the line table in the source manager block.
739/// \returns true if ther was an error.
740bool ASTReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
741  unsigned Idx = 0;
742  LineTableInfo &LineTable = SourceMgr.getLineTable();
743
744  // Parse the file names
745  std::map<int, int> FileIDs;
746  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
747    // Extract the file name
748    unsigned FilenameLen = Record[Idx++];
749    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
750    Idx += FilenameLen;
751    MaybeAddSystemRootToFilename(Filename);
752    FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
753                                                  Filename.size());
754  }
755
756  // Parse the line entries
757  std::vector<LineEntry> Entries;
758  while (Idx < Record.size()) {
759    int FID = Record[Idx++];
760
761    // Extract the line entries
762    unsigned NumEntries = Record[Idx++];
763    assert(NumEntries && "Numentries is 00000");
764    Entries.clear();
765    Entries.reserve(NumEntries);
766    for (unsigned I = 0; I != NumEntries; ++I) {
767      unsigned FileOffset = Record[Idx++];
768      unsigned LineNo = Record[Idx++];
769      int FilenameID = FileIDs[Record[Idx++]];
770      SrcMgr::CharacteristicKind FileKind
771        = (SrcMgr::CharacteristicKind)Record[Idx++];
772      unsigned IncludeOffset = Record[Idx++];
773      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
774                                       FileKind, IncludeOffset));
775    }
776    LineTable.AddEntry(FID, Entries);
777  }
778
779  return false;
780}
781
782namespace {
783
784class ASTStatData {
785public:
786  const bool hasStat;
787  const ino_t ino;
788  const dev_t dev;
789  const mode_t mode;
790  const time_t mtime;
791  const off_t size;
792
793  ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
794  : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
795
796  ASTStatData()
797    : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
798};
799
800class ASTStatLookupTrait {
801 public:
802  typedef const char *external_key_type;
803  typedef const char *internal_key_type;
804
805  typedef ASTStatData data_type;
806
807  static unsigned ComputeHash(const char *path) {
808    return llvm::HashString(path);
809  }
810
811  static internal_key_type GetInternalKey(const char *path) { return path; }
812
813  static bool EqualKey(internal_key_type a, internal_key_type b) {
814    return strcmp(a, b) == 0;
815  }
816
817  static std::pair<unsigned, unsigned>
818  ReadKeyDataLength(const unsigned char*& d) {
819    unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
820    unsigned DataLen = (unsigned) *d++;
821    return std::make_pair(KeyLen + 1, DataLen);
822  }
823
824  static internal_key_type ReadKey(const unsigned char *d, unsigned) {
825    return (const char *)d;
826  }
827
828  static data_type ReadData(const internal_key_type, const unsigned char *d,
829                            unsigned /*DataLen*/) {
830    using namespace clang::io;
831
832    if (*d++ == 1)
833      return data_type();
834
835    ino_t ino = (ino_t) ReadUnalignedLE32(d);
836    dev_t dev = (dev_t) ReadUnalignedLE32(d);
837    mode_t mode = (mode_t) ReadUnalignedLE16(d);
838    time_t mtime = (time_t) ReadUnalignedLE64(d);
839    off_t size = (off_t) ReadUnalignedLE64(d);
840    return data_type(ino, dev, mode, mtime, size);
841  }
842};
843
844/// \brief stat() cache for precompiled headers.
845///
846/// This cache is very similar to the stat cache used by pretokenized
847/// headers.
848class ASTStatCache : public StatSysCallCache {
849  typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
850  CacheTy *Cache;
851
852  unsigned &NumStatHits, &NumStatMisses;
853public:
854  ASTStatCache(const unsigned char *Buckets,
855               const unsigned char *Base,
856               unsigned &NumStatHits,
857               unsigned &NumStatMisses)
858    : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
859    Cache = CacheTy::Create(Buckets, Base);
860  }
861
862  ~ASTStatCache() { delete Cache; }
863
864  int stat(const char *path, struct stat *buf) {
865    // Do the lookup for the file's data in the AST file.
866    CacheTy::iterator I = Cache->find(path);
867
868    // If we don't get a hit in the AST file just forward to 'stat'.
869    if (I == Cache->end()) {
870      ++NumStatMisses;
871      return StatSysCallCache::stat(path, buf);
872    }
873
874    ++NumStatHits;
875    ASTStatData Data = *I;
876
877    if (!Data.hasStat)
878      return 1;
879
880    buf->st_ino = Data.ino;
881    buf->st_dev = Data.dev;
882    buf->st_mtime = Data.mtime;
883    buf->st_mode = Data.mode;
884    buf->st_size = Data.size;
885    return 0;
886  }
887};
888} // end anonymous namespace
889
890
891/// \brief Read a source manager block
892ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) {
893  using namespace SrcMgr;
894
895  llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
896
897  // Set the source-location entry cursor to the current position in
898  // the stream. This cursor will be used to read the contents of the
899  // source manager block initially, and then lazily read
900  // source-location entries as needed.
901  SLocEntryCursor = F.Stream;
902
903  // The stream itself is going to skip over the source manager block.
904  if (F.Stream.SkipBlock()) {
905    Error("malformed block record in AST file");
906    return Failure;
907  }
908
909  // Enter the source manager block.
910  if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
911    Error("malformed source manager block record in AST file");
912    return Failure;
913  }
914
915  RecordData Record;
916  while (true) {
917    unsigned Code = SLocEntryCursor.ReadCode();
918    if (Code == llvm::bitc::END_BLOCK) {
919      if (SLocEntryCursor.ReadBlockEnd()) {
920        Error("error at end of Source Manager block in AST file");
921        return Failure;
922      }
923      return Success;
924    }
925
926    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
927      // No known subblocks, always skip them.
928      SLocEntryCursor.ReadSubBlockID();
929      if (SLocEntryCursor.SkipBlock()) {
930        Error("malformed block record in AST file");
931        return Failure;
932      }
933      continue;
934    }
935
936    if (Code == llvm::bitc::DEFINE_ABBREV) {
937      SLocEntryCursor.ReadAbbrevRecord();
938      continue;
939    }
940
941    // Read a record.
942    const char *BlobStart;
943    unsigned BlobLen;
944    Record.clear();
945    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
946    default:  // Default behavior: ignore.
947      break;
948
949    case pch::SM_LINE_TABLE:
950      if (ParseLineTable(Record))
951        return Failure;
952      break;
953
954    case pch::SM_SLOC_FILE_ENTRY:
955    case pch::SM_SLOC_BUFFER_ENTRY:
956    case pch::SM_SLOC_INSTANTIATION_ENTRY:
957      // Once we hit one of the source location entries, we're done.
958      return Success;
959    }
960  }
961}
962
963/// \brief Get a cursor that's correctly positioned for reading the source
964/// location entry with the given ID.
965llvm::BitstreamCursor &ASTReader::SLocCursorForID(unsigned ID) {
966  assert(ID != 0 && ID <= TotalNumSLocEntries &&
967         "SLocCursorForID should only be called for real IDs.");
968
969  ID -= 1;
970  PerFileData *F = 0;
971  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
972    F = Chain[N - I - 1];
973    if (ID < F->LocalNumSLocEntries)
974      break;
975    ID -= F->LocalNumSLocEntries;
976  }
977  assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
978
979  F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
980  return F->SLocEntryCursor;
981}
982
983/// \brief Read in the source location entry with the given ID.
984ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(unsigned ID) {
985  if (ID == 0)
986    return Success;
987
988  if (ID > TotalNumSLocEntries) {
989    Error("source location entry ID out-of-range for AST file");
990    return Failure;
991  }
992
993  llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
994
995  ++NumSLocEntriesRead;
996  unsigned Code = SLocEntryCursor.ReadCode();
997  if (Code == llvm::bitc::END_BLOCK ||
998      Code == llvm::bitc::ENTER_SUBBLOCK ||
999      Code == llvm::bitc::DEFINE_ABBREV) {
1000    Error("incorrectly-formatted source location entry in AST file");
1001    return Failure;
1002  }
1003
1004  RecordData Record;
1005  const char *BlobStart;
1006  unsigned BlobLen;
1007  switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1008  default:
1009    Error("incorrectly-formatted source location entry in AST file");
1010    return Failure;
1011
1012  case pch::SM_SLOC_FILE_ENTRY: {
1013    std::string Filename(BlobStart, BlobStart + BlobLen);
1014    MaybeAddSystemRootToFilename(Filename);
1015    const FileEntry *File = FileMgr.getFile(Filename);
1016    if (File == 0) {
1017      std::string ErrorStr = "could not find file '";
1018      ErrorStr += Filename;
1019      ErrorStr += "' referenced by AST file";
1020      Error(ErrorStr.c_str());
1021      return Failure;
1022    }
1023
1024    if (Record.size() < 10) {
1025      Error("source location entry is incorrect");
1026      return Failure;
1027    }
1028
1029    if (!DisableValidation &&
1030        ((off_t)Record[4] != File->getSize()
1031#if !defined(LLVM_ON_WIN32)
1032        // In our regression testing, the Windows file system seems to
1033        // have inconsistent modification times that sometimes
1034        // erroneously trigger this error-handling path.
1035         || (time_t)Record[5] != File->getModificationTime()
1036#endif
1037        )) {
1038      Diag(diag::err_fe_pch_file_modified)
1039        << Filename;
1040      return Failure;
1041    }
1042
1043    FileID FID = SourceMgr.createFileID(File,
1044                                SourceLocation::getFromRawEncoding(Record[1]),
1045                                       (SrcMgr::CharacteristicKind)Record[2],
1046                                        ID, Record[0]);
1047    if (Record[3])
1048      const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1049        .setHasLineDirectives();
1050
1051    // Reconstruct header-search information for this file.
1052    HeaderFileInfo HFI;
1053    HFI.isImport = Record[6];
1054    HFI.DirInfo = Record[7];
1055    HFI.NumIncludes = Record[8];
1056    HFI.ControllingMacroID = Record[9];
1057    if (Listener)
1058      Listener->ReadHeaderFileInfo(HFI, File->getUID());
1059    break;
1060  }
1061
1062  case pch::SM_SLOC_BUFFER_ENTRY: {
1063    const char *Name = BlobStart;
1064    unsigned Offset = Record[0];
1065    unsigned Code = SLocEntryCursor.ReadCode();
1066    Record.clear();
1067    unsigned RecCode
1068      = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1069
1070    if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1071      Error("AST record has invalid code");
1072      return Failure;
1073    }
1074
1075    llvm::MemoryBuffer *Buffer
1076    = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1077                                       Name);
1078    FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
1079
1080    if (strcmp(Name, "<built-in>") == 0) {
1081      PCHPredefinesBlock Block = {
1082        BufferID,
1083        llvm::StringRef(BlobStart, BlobLen - 1)
1084      };
1085      PCHPredefinesBuffers.push_back(Block);
1086    }
1087
1088    break;
1089  }
1090
1091  case pch::SM_SLOC_INSTANTIATION_ENTRY: {
1092    SourceLocation SpellingLoc
1093      = SourceLocation::getFromRawEncoding(Record[1]);
1094    SourceMgr.createInstantiationLoc(SpellingLoc,
1095                              SourceLocation::getFromRawEncoding(Record[2]),
1096                              SourceLocation::getFromRawEncoding(Record[3]),
1097                                     Record[4],
1098                                     ID,
1099                                     Record[0]);
1100    break;
1101  }
1102  }
1103
1104  return Success;
1105}
1106
1107/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1108/// specified cursor.  Read the abbreviations that are at the top of the block
1109/// and then leave the cursor pointing into the block.
1110bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1111                                 unsigned BlockID) {
1112  if (Cursor.EnterSubBlock(BlockID)) {
1113    Error("malformed block record in AST file");
1114    return Failure;
1115  }
1116
1117  while (true) {
1118    unsigned Code = Cursor.ReadCode();
1119
1120    // We expect all abbrevs to be at the start of the block.
1121    if (Code != llvm::bitc::DEFINE_ABBREV)
1122      return false;
1123    Cursor.ReadAbbrevRecord();
1124  }
1125}
1126
1127void ASTReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
1128  assert(PP && "Forgot to set Preprocessor ?");
1129
1130  // Keep track of where we are in the stream, then jump back there
1131  // after reading this macro.
1132  SavedStreamPosition SavedPosition(Stream);
1133
1134  Stream.JumpToBit(Offset);
1135  RecordData Record;
1136  llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1137  MacroInfo *Macro = 0;
1138
1139  while (true) {
1140    unsigned Code = Stream.ReadCode();
1141    switch (Code) {
1142    case llvm::bitc::END_BLOCK:
1143      return;
1144
1145    case llvm::bitc::ENTER_SUBBLOCK:
1146      // No known subblocks, always skip them.
1147      Stream.ReadSubBlockID();
1148      if (Stream.SkipBlock()) {
1149        Error("malformed block record in AST file");
1150        return;
1151      }
1152      continue;
1153
1154    case llvm::bitc::DEFINE_ABBREV:
1155      Stream.ReadAbbrevRecord();
1156      continue;
1157    default: break;
1158    }
1159
1160    // Read a record.
1161    Record.clear();
1162    pch::PreprocessorRecordTypes RecType =
1163      (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1164    switch (RecType) {
1165    case pch::PP_MACRO_OBJECT_LIKE:
1166    case pch::PP_MACRO_FUNCTION_LIKE: {
1167      // If we already have a macro, that means that we've hit the end
1168      // of the definition of the macro we were looking for. We're
1169      // done.
1170      if (Macro)
1171        return;
1172
1173      IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1174      if (II == 0) {
1175        Error("macro must have a name in AST file");
1176        return;
1177      }
1178      SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1179      bool isUsed = Record[2];
1180
1181      MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1182      MI->setIsUsed(isUsed);
1183      MI->setIsFromAST();
1184
1185      unsigned NextIndex = 3;
1186      if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1187        // Decode function-like macro info.
1188        bool isC99VarArgs = Record[3];
1189        bool isGNUVarArgs = Record[4];
1190        MacroArgs.clear();
1191        unsigned NumArgs = Record[5];
1192        NextIndex = 6 + NumArgs;
1193        for (unsigned i = 0; i != NumArgs; ++i)
1194          MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1195
1196        // Install function-like macro info.
1197        MI->setIsFunctionLike();
1198        if (isC99VarArgs) MI->setIsC99Varargs();
1199        if (isGNUVarArgs) MI->setIsGNUVarargs();
1200        MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1201                            PP->getPreprocessorAllocator());
1202      }
1203
1204      // Finally, install the macro.
1205      PP->setMacroInfo(II, MI);
1206
1207      // Remember that we saw this macro last so that we add the tokens that
1208      // form its body to it.
1209      Macro = MI;
1210
1211      if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1212        // We have a macro definition. Load it now.
1213        PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1214                                        getMacroDefinition(Record[NextIndex]));
1215      }
1216
1217      ++NumMacrosRead;
1218      break;
1219    }
1220
1221    case pch::PP_TOKEN: {
1222      // If we see a TOKEN before a PP_MACRO_*, then the file is
1223      // erroneous, just pretend we didn't see this.
1224      if (Macro == 0) break;
1225
1226      Token Tok;
1227      Tok.startToken();
1228      Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1229      Tok.setLength(Record[1]);
1230      if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1231        Tok.setIdentifierInfo(II);
1232      Tok.setKind((tok::TokenKind)Record[3]);
1233      Tok.setFlag((Token::TokenFlags)Record[4]);
1234      Macro->AddTokenToBody(Tok);
1235      break;
1236    }
1237
1238    case pch::PP_MACRO_INSTANTIATION: {
1239      // If we already have a macro, that means that we've hit the end
1240      // of the definition of the macro we were looking for. We're
1241      // done.
1242      if (Macro)
1243        return;
1244
1245      if (!PP->getPreprocessingRecord()) {
1246        Error("missing preprocessing record in AST file");
1247        return;
1248      }
1249
1250      PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1251      if (PPRec.getPreprocessedEntity(Record[0]))
1252        return;
1253
1254      MacroInstantiation *MI
1255        = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1256                               SourceRange(
1257                                 SourceLocation::getFromRawEncoding(Record[1]),
1258                                 SourceLocation::getFromRawEncoding(Record[2])),
1259                                         getMacroDefinition(Record[4]));
1260      PPRec.SetPreallocatedEntity(Record[0], MI);
1261      return;
1262    }
1263
1264    case pch::PP_MACRO_DEFINITION: {
1265      // If we already have a macro, that means that we've hit the end
1266      // of the definition of the macro we were looking for. We're
1267      // done.
1268      if (Macro)
1269        return;
1270
1271      if (!PP->getPreprocessingRecord()) {
1272        Error("missing preprocessing record in AST file");
1273        return;
1274      }
1275
1276      PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1277      if (PPRec.getPreprocessedEntity(Record[0]))
1278        return;
1279
1280      if (Record[1] >= MacroDefinitionsLoaded.size()) {
1281        Error("out-of-bounds macro definition record");
1282        return;
1283      }
1284
1285      MacroDefinition *MD
1286        = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1287                                SourceLocation::getFromRawEncoding(Record[5]),
1288                              SourceRange(
1289                                SourceLocation::getFromRawEncoding(Record[2]),
1290                                SourceLocation::getFromRawEncoding(Record[3])));
1291      PPRec.SetPreallocatedEntity(Record[0], MD);
1292      MacroDefinitionsLoaded[Record[1]] = MD;
1293      return;
1294    }
1295  }
1296  }
1297}
1298
1299void ASTReader::ReadDefinedMacros() {
1300  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1301    llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
1302
1303    // If there was no preprocessor block, skip this file.
1304    if (!MacroCursor.getBitStreamReader())
1305      continue;
1306
1307    llvm::BitstreamCursor Cursor = MacroCursor;
1308    if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1309      Error("malformed preprocessor block record in AST file");
1310      return;
1311    }
1312
1313    RecordData Record;
1314    while (true) {
1315      unsigned Code = Cursor.ReadCode();
1316      if (Code == llvm::bitc::END_BLOCK) {
1317        if (Cursor.ReadBlockEnd()) {
1318          Error("error at end of preprocessor block in AST file");
1319          return;
1320        }
1321        break;
1322      }
1323
1324      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1325        // No known subblocks, always skip them.
1326        Cursor.ReadSubBlockID();
1327        if (Cursor.SkipBlock()) {
1328          Error("malformed block record in AST file");
1329          return;
1330        }
1331        continue;
1332      }
1333
1334      if (Code == llvm::bitc::DEFINE_ABBREV) {
1335        Cursor.ReadAbbrevRecord();
1336        continue;
1337      }
1338
1339      // Read a record.
1340      const char *BlobStart;
1341      unsigned BlobLen;
1342      Record.clear();
1343      switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1344      default:  // Default behavior: ignore.
1345        break;
1346
1347      case pch::PP_MACRO_OBJECT_LIKE:
1348      case pch::PP_MACRO_FUNCTION_LIKE:
1349        DecodeIdentifierInfo(Record[0]);
1350        break;
1351
1352      case pch::PP_TOKEN:
1353        // Ignore tokens.
1354        break;
1355
1356      case pch::PP_MACRO_INSTANTIATION:
1357      case pch::PP_MACRO_DEFINITION:
1358        // Read the macro record.
1359        ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1360        break;
1361      }
1362    }
1363  }
1364}
1365
1366MacroDefinition *ASTReader::getMacroDefinition(pch::IdentID ID) {
1367  if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1368    return 0;
1369
1370  if (!MacroDefinitionsLoaded[ID]) {
1371    unsigned Index = ID;
1372    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1373      PerFileData &F = *Chain[N - I - 1];
1374      if (Index < F.LocalNumMacroDefinitions) {
1375        ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1376        break;
1377      }
1378      Index -= F.LocalNumMacroDefinitions;
1379    }
1380    assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1381  }
1382
1383  return MacroDefinitionsLoaded[ID];
1384}
1385
1386/// \brief If we are loading a relocatable PCH file, and the filename is
1387/// not an absolute path, add the system root to the beginning of the file
1388/// name.
1389void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1390  // If this is not a relocatable PCH file, there's nothing to do.
1391  if (!RelocatablePCH)
1392    return;
1393
1394  if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
1395    return;
1396
1397  if (isysroot == 0) {
1398    // If no system root was given, default to '/'
1399    Filename.insert(Filename.begin(), '/');
1400    return;
1401  }
1402
1403  unsigned Length = strlen(isysroot);
1404  if (isysroot[Length - 1] != '/')
1405    Filename.insert(Filename.begin(), '/');
1406
1407  Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1408}
1409
1410ASTReader::ASTReadResult
1411ASTReader::ReadASTBlock(PerFileData &F) {
1412  llvm::BitstreamCursor &Stream = F.Stream;
1413
1414  if (Stream.EnterSubBlock(pch::AST_BLOCK_ID)) {
1415    Error("malformed block record in AST file");
1416    return Failure;
1417  }
1418
1419  // Read all of the records and blocks for the ASt file.
1420  RecordData Record;
1421  bool First = true;
1422  while (!Stream.AtEndOfStream()) {
1423    unsigned Code = Stream.ReadCode();
1424    if (Code == llvm::bitc::END_BLOCK) {
1425      if (Stream.ReadBlockEnd()) {
1426        Error("error at end of module block in AST file");
1427        return Failure;
1428      }
1429
1430      return Success;
1431    }
1432
1433    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1434      switch (Stream.ReadSubBlockID()) {
1435      case pch::DECLTYPES_BLOCK_ID:
1436        // We lazily load the decls block, but we want to set up the
1437        // DeclsCursor cursor to point into it.  Clone our current bitcode
1438        // cursor to it, enter the block and read the abbrevs in that block.
1439        // With the main cursor, we just skip over it.
1440        F.DeclsCursor = Stream;
1441        if (Stream.SkipBlock() ||  // Skip with the main cursor.
1442            // Read the abbrevs.
1443            ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
1444          Error("malformed block record in AST file");
1445          return Failure;
1446        }
1447        break;
1448
1449      case pch::PREPROCESSOR_BLOCK_ID:
1450        F.MacroCursor = Stream;
1451        if (PP)
1452          PP->setExternalSource(this);
1453
1454        if (Stream.SkipBlock()) {
1455          Error("malformed block record in AST file");
1456          return Failure;
1457        }
1458        break;
1459
1460      case pch::SOURCE_MANAGER_BLOCK_ID:
1461        switch (ReadSourceManagerBlock(F)) {
1462        case Success:
1463          break;
1464
1465        case Failure:
1466          Error("malformed source manager block in AST file");
1467          return Failure;
1468
1469        case IgnorePCH:
1470          return IgnorePCH;
1471        }
1472        break;
1473      }
1474      First = false;
1475      continue;
1476    }
1477
1478    if (Code == llvm::bitc::DEFINE_ABBREV) {
1479      Stream.ReadAbbrevRecord();
1480      continue;
1481    }
1482
1483    // Read and process a record.
1484    Record.clear();
1485    const char *BlobStart = 0;
1486    unsigned BlobLen = 0;
1487    switch ((pch::ASTRecordTypes)Stream.ReadRecord(Code, Record,
1488                                                   &BlobStart, &BlobLen)) {
1489    default:  // Default behavior: ignore.
1490      break;
1491
1492    case pch::METADATA: {
1493      if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
1494        Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1495                                           : diag::warn_pch_version_too_new);
1496        return IgnorePCH;
1497      }
1498
1499      RelocatablePCH = Record[4];
1500      if (Listener) {
1501        std::string TargetTriple(BlobStart, BlobLen);
1502        if (Listener->ReadTargetTriple(TargetTriple))
1503          return IgnorePCH;
1504      }
1505      break;
1506    }
1507
1508    case pch::CHAINED_METADATA: {
1509      if (!First) {
1510        Error("CHAINED_METADATA is not first record in block");
1511        return Failure;
1512      }
1513      if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
1514        Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1515                                           : diag::warn_pch_version_too_new);
1516        return IgnorePCH;
1517      }
1518
1519      // Load the chained file.
1520      switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen))) {
1521      case Failure: return Failure;
1522        // If we have to ignore the dependency, we'll have to ignore this too.
1523      case IgnorePCH: return IgnorePCH;
1524      case Success: break;
1525      }
1526      break;
1527    }
1528
1529    case pch::TYPE_OFFSET:
1530      if (F.LocalNumTypes != 0) {
1531        Error("duplicate TYPE_OFFSET record in AST file");
1532        return Failure;
1533      }
1534      F.TypeOffsets = (const uint32_t *)BlobStart;
1535      F.LocalNumTypes = Record[0];
1536      break;
1537
1538    case pch::DECL_OFFSET:
1539      if (F.LocalNumDecls != 0) {
1540        Error("duplicate DECL_OFFSET record in AST file");
1541        return Failure;
1542      }
1543      F.DeclOffsets = (const uint32_t *)BlobStart;
1544      F.LocalNumDecls = Record[0];
1545      break;
1546
1547    case pch::TU_UPDATE_LEXICAL: {
1548      DeclContextInfo Info = {
1549        /* No visible information */ 0, 0,
1550        reinterpret_cast<const pch::DeclID *>(BlobStart),
1551        BlobLen / sizeof(pch::DeclID)
1552      };
1553      DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1554      break;
1555    }
1556
1557    case pch::REDECLS_UPDATE_LATEST: {
1558      assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1559      for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1560        pch::DeclID First = Record[i], Latest = Record[i+1];
1561        assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1562                Latest > FirstLatestDeclIDs[First]) &&
1563               "The new latest is supposed to come after the previous latest");
1564        FirstLatestDeclIDs[First] = Latest;
1565      }
1566      break;
1567    }
1568
1569    case pch::LANGUAGE_OPTIONS:
1570      if (ParseLanguageOptions(Record) && !DisableValidation)
1571        return IgnorePCH;
1572      break;
1573
1574    case pch::IDENTIFIER_TABLE:
1575      F.IdentifierTableData = BlobStart;
1576      if (Record[0]) {
1577        F.IdentifierLookupTable
1578          = ASTIdentifierLookupTable::Create(
1579                       (const unsigned char *)F.IdentifierTableData + Record[0],
1580                       (const unsigned char *)F.IdentifierTableData,
1581                       ASTIdentifierLookupTrait(*this, F.Stream));
1582        if (PP)
1583          PP->getIdentifierTable().setExternalIdentifierLookup(this);
1584      }
1585      break;
1586
1587    case pch::IDENTIFIER_OFFSET:
1588      if (F.LocalNumIdentifiers != 0) {
1589        Error("duplicate IDENTIFIER_OFFSET record in AST file");
1590        return Failure;
1591      }
1592      F.IdentifierOffsets = (const uint32_t *)BlobStart;
1593      F.LocalNumIdentifiers = Record[0];
1594      break;
1595
1596    case pch::EXTERNAL_DEFINITIONS:
1597      // Optimization for the first block.
1598      if (ExternalDefinitions.empty())
1599        ExternalDefinitions.swap(Record);
1600      else
1601        ExternalDefinitions.insert(ExternalDefinitions.end(),
1602                                   Record.begin(), Record.end());
1603      break;
1604
1605    case pch::SPECIAL_TYPES:
1606      // Optimization for the first block
1607      if (SpecialTypes.empty())
1608        SpecialTypes.swap(Record);
1609      else
1610        SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
1611      break;
1612
1613    case pch::STATISTICS:
1614      TotalNumStatements += Record[0];
1615      TotalNumMacros += Record[1];
1616      TotalLexicalDeclContexts += Record[2];
1617      TotalVisibleDeclContexts += Record[3];
1618      break;
1619
1620    case pch::TENTATIVE_DEFINITIONS:
1621      // Optimization for the first block.
1622      if (TentativeDefinitions.empty())
1623        TentativeDefinitions.swap(Record);
1624      else
1625        TentativeDefinitions.insert(TentativeDefinitions.end(),
1626                                    Record.begin(), Record.end());
1627      break;
1628
1629    case pch::UNUSED_FILESCOPED_DECLS:
1630      // Optimization for the first block.
1631      if (UnusedFileScopedDecls.empty())
1632        UnusedFileScopedDecls.swap(Record);
1633      else
1634        UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(),
1635                                     Record.begin(), Record.end());
1636      break;
1637
1638    case pch::WEAK_UNDECLARED_IDENTIFIERS:
1639      // Later blocks overwrite earlier ones.
1640      WeakUndeclaredIdentifiers.swap(Record);
1641      break;
1642
1643    case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1644      // Optimization for the first block.
1645      if (LocallyScopedExternalDecls.empty())
1646        LocallyScopedExternalDecls.swap(Record);
1647      else
1648        LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1649                                          Record.begin(), Record.end());
1650      break;
1651
1652    case pch::SELECTOR_OFFSETS:
1653      F.SelectorOffsets = (const uint32_t *)BlobStart;
1654      F.LocalNumSelectors = Record[0];
1655      break;
1656
1657    case pch::METHOD_POOL:
1658      F.SelectorLookupTableData = (const unsigned char *)BlobStart;
1659      if (Record[0])
1660        F.SelectorLookupTable
1661          = ASTSelectorLookupTable::Create(
1662                        F.SelectorLookupTableData + Record[0],
1663                        F.SelectorLookupTableData,
1664                        ASTSelectorLookupTrait(*this));
1665      TotalNumMethodPoolEntries += Record[1];
1666      break;
1667
1668    case pch::REFERENCED_SELECTOR_POOL: {
1669      ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1670          Record.begin(), Record.end());
1671      break;
1672    }
1673
1674    case pch::PP_COUNTER_VALUE:
1675      if (!Record.empty() && Listener)
1676        Listener->ReadCounter(Record[0]);
1677      break;
1678
1679    case pch::SOURCE_LOCATION_OFFSETS:
1680      F.SLocOffsets = (const uint32_t *)BlobStart;
1681      F.LocalNumSLocEntries = Record[0];
1682      // We cannot delay this until the entire chain is loaded, because then
1683      // source location preloads would also have to be delayed.
1684      // FIXME: Is there a reason not to do that?
1685      TotalNumSLocEntries += F.LocalNumSLocEntries;
1686      SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
1687      break;
1688
1689    case pch::SOURCE_LOCATION_PRELOADS:
1690      for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1691        ASTReadResult Result = ReadSLocEntryRecord(Record[I]);
1692        if (Result != Success)
1693          return Result;
1694      }
1695      break;
1696
1697    case pch::STAT_CACHE: {
1698      ASTStatCache *MyStatCache =
1699        new ASTStatCache((const unsigned char *)BlobStart + Record[0],
1700                         (const unsigned char *)BlobStart,
1701                         NumStatHits, NumStatMisses);
1702      FileMgr.addStatCache(MyStatCache);
1703      F.StatCache = MyStatCache;
1704      break;
1705    }
1706
1707    case pch::EXT_VECTOR_DECLS:
1708      // Optimization for the first block.
1709      if (ExtVectorDecls.empty())
1710        ExtVectorDecls.swap(Record);
1711      else
1712        ExtVectorDecls.insert(ExtVectorDecls.end(),
1713                              Record.begin(), Record.end());
1714      break;
1715
1716    case pch::VTABLE_USES:
1717      // Later tables overwrite earlier ones.
1718      VTableUses.swap(Record);
1719      break;
1720
1721    case pch::DYNAMIC_CLASSES:
1722      // Optimization for the first block.
1723      if (DynamicClasses.empty())
1724        DynamicClasses.swap(Record);
1725      else
1726        DynamicClasses.insert(DynamicClasses.end(),
1727                              Record.begin(), Record.end());
1728      break;
1729
1730    case pch::PENDING_IMPLICIT_INSTANTIATIONS:
1731      // Optimization for the first block.
1732      if (PendingImplicitInstantiations.empty())
1733        PendingImplicitInstantiations.swap(Record);
1734      else
1735        PendingImplicitInstantiations.insert(
1736             PendingImplicitInstantiations.end(), Record.begin(), Record.end());
1737      break;
1738
1739    case pch::SEMA_DECL_REFS:
1740      // Later tables overwrite earlier ones.
1741      SemaDeclRefs.swap(Record);
1742      break;
1743
1744    case pch::ORIGINAL_FILE_NAME:
1745      // The primary AST will be the last to get here, so it will be the one
1746      // that's used.
1747      ActualOriginalFileName.assign(BlobStart, BlobLen);
1748      OriginalFileName = ActualOriginalFileName;
1749      MaybeAddSystemRootToFilename(OriginalFileName);
1750      break;
1751
1752    case pch::VERSION_CONTROL_BRANCH_REVISION: {
1753      const std::string &CurBranch = getClangFullRepositoryVersion();
1754      llvm::StringRef ASTBranch(BlobStart, BlobLen);
1755      if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1756        Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1757        return IgnorePCH;
1758      }
1759      break;
1760    }
1761
1762    case pch::MACRO_DEFINITION_OFFSETS:
1763      F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1764      F.NumPreallocatedPreprocessingEntities = Record[0];
1765      F.LocalNumMacroDefinitions = Record[1];
1766      break;
1767
1768    case pch::DECL_REPLACEMENTS: {
1769      if (Record.size() % 2 != 0) {
1770        Error("invalid DECL_REPLACEMENTS block in AST file");
1771        return Failure;
1772      }
1773      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
1774        ReplacedDecls[static_cast<pch::DeclID>(Record[I])] =
1775            std::make_pair(&F, Record[I+1]);
1776      break;
1777    }
1778    }
1779    First = false;
1780  }
1781  Error("premature end of bitstream in AST file");
1782  return Failure;
1783}
1784
1785ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName) {
1786  switch(ReadASTCore(FileName)) {
1787  case Failure: return Failure;
1788  case IgnorePCH: return IgnorePCH;
1789  case Success: break;
1790  }
1791
1792  // Here comes stuff that we only do once the entire chain is loaded.
1793
1794  // Allocate space for loaded identifiers, decls and types.
1795  unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1796           TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1797           TotalNumSelectors = 0;
1798  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1799    TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
1800    TotalNumTypes += Chain[I]->LocalNumTypes;
1801    TotalNumDecls += Chain[I]->LocalNumDecls;
1802    TotalNumPreallocatedPreprocessingEntities +=
1803        Chain[I]->NumPreallocatedPreprocessingEntities;
1804    TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
1805    TotalNumSelectors += Chain[I]->LocalNumSelectors;
1806  }
1807  IdentifiersLoaded.resize(TotalNumIdentifiers);
1808  TypesLoaded.resize(TotalNumTypes);
1809  DeclsLoaded.resize(TotalNumDecls);
1810  MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1811  if (PP) {
1812    if (TotalNumIdentifiers > 0)
1813      PP->getHeaderSearchInfo().SetExternalLookup(this);
1814    if (TotalNumPreallocatedPreprocessingEntities > 0) {
1815      if (!PP->getPreprocessingRecord())
1816        PP->createPreprocessingRecord();
1817      PP->getPreprocessingRecord()->SetExternalSource(*this,
1818                                     TotalNumPreallocatedPreprocessingEntities);
1819    }
1820  }
1821  SelectorsLoaded.resize(TotalNumSelectors);
1822
1823  // Check the predefines buffers.
1824  if (!DisableValidation && CheckPredefinesBuffers())
1825    return IgnorePCH;
1826
1827  if (PP) {
1828    // Initialization of keywords and pragmas occurs before the
1829    // AST file is read, so there may be some identifiers that were
1830    // loaded into the IdentifierTable before we intercepted the
1831    // creation of identifiers. Iterate through the list of known
1832    // identifiers and determine whether we have to establish
1833    // preprocessor definitions or top-level identifier declaration
1834    // chains for those identifiers.
1835    //
1836    // We copy the IdentifierInfo pointers to a small vector first,
1837    // since de-serializing declarations or macro definitions can add
1838    // new entries into the identifier table, invalidating the
1839    // iterators.
1840    llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1841    for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1842                                IdEnd = PP->getIdentifierTable().end();
1843         Id != IdEnd; ++Id)
1844      Identifiers.push_back(Id->second);
1845    // We need to search the tables in all files.
1846    for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1847      ASTIdentifierLookupTable *IdTable
1848        = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
1849      // Not all AST files necessarily have identifier tables, only the useful
1850      // ones.
1851      if (!IdTable)
1852        continue;
1853      for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1854        IdentifierInfo *II = Identifiers[I];
1855        // Look in the on-disk hash tables for an entry for this identifier
1856        ASTIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
1857        std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
1858        ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1859        if (Pos == IdTable->end())
1860          continue;
1861
1862        // Dereferencing the iterator has the effect of populating the
1863        // IdentifierInfo node with the various declarations it needs.
1864        (void)*Pos;
1865      }
1866    }
1867  }
1868
1869  if (Context)
1870    InitializeContext(*Context);
1871
1872  return Success;
1873}
1874
1875ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName) {
1876  Chain.push_back(new PerFileData());
1877  PerFileData &F = *Chain.back();
1878
1879  // Set the AST file name.
1880  F.FileName = FileName;
1881
1882  // Open the AST file.
1883  //
1884  // FIXME: This shouldn't be here, we should just take a raw_ostream.
1885  std::string ErrStr;
1886  F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1887  if (!F.Buffer) {
1888    Error(ErrStr.c_str());
1889    return IgnorePCH;
1890  }
1891
1892  // Initialize the stream
1893  F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1894                    (const unsigned char *)F.Buffer->getBufferEnd());
1895  llvm::BitstreamCursor &Stream = F.Stream;
1896  Stream.init(F.StreamFile);
1897  F.SizeInBits = F.Buffer->getBufferSize() * 8;
1898
1899  // Sniff for the signature.
1900  if (Stream.Read(8) != 'C' ||
1901      Stream.Read(8) != 'P' ||
1902      Stream.Read(8) != 'C' ||
1903      Stream.Read(8) != 'H') {
1904    Diag(diag::err_not_a_pch_file) << FileName;
1905    return Failure;
1906  }
1907
1908  while (!Stream.AtEndOfStream()) {
1909    unsigned Code = Stream.ReadCode();
1910
1911    if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1912      Error("invalid record at top-level of AST file");
1913      return Failure;
1914    }
1915
1916    unsigned BlockID = Stream.ReadSubBlockID();
1917
1918    // We only know the AST subblock ID.
1919    switch (BlockID) {
1920    case llvm::bitc::BLOCKINFO_BLOCK_ID:
1921      if (Stream.ReadBlockInfoBlock()) {
1922        Error("malformed BlockInfoBlock in AST file");
1923        return Failure;
1924      }
1925      break;
1926    case pch::AST_BLOCK_ID:
1927      switch (ReadASTBlock(F)) {
1928      case Success:
1929        break;
1930
1931      case Failure:
1932        return Failure;
1933
1934      case IgnorePCH:
1935        // FIXME: We could consider reading through to the end of this
1936        // AST block, skipping subblocks, to see if there are other
1937        // AST blocks elsewhere.
1938
1939        // Clear out any preallocated source location entries, so that
1940        // the source manager does not try to resolve them later.
1941        SourceMgr.ClearPreallocatedSLocEntries();
1942
1943        // Remove the stat cache.
1944        if (F.StatCache)
1945          FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
1946
1947        return IgnorePCH;
1948      }
1949      break;
1950    default:
1951      if (Stream.SkipBlock()) {
1952        Error("malformed block record in AST file");
1953        return Failure;
1954      }
1955      break;
1956    }
1957  }
1958
1959  return Success;
1960}
1961
1962void ASTReader::setPreprocessor(Preprocessor &pp) {
1963  PP = &pp;
1964
1965  unsigned TotalNum = 0;
1966  for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1967    TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1968  if (TotalNum) {
1969    if (!PP->getPreprocessingRecord())
1970      PP->createPreprocessingRecord();
1971    PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
1972  }
1973}
1974
1975void ASTReader::InitializeContext(ASTContext &Ctx) {
1976  Context = &Ctx;
1977  assert(Context && "Passed null context!");
1978
1979  assert(PP && "Forgot to set Preprocessor ?");
1980  PP->getIdentifierTable().setExternalIdentifierLookup(this);
1981  PP->getHeaderSearchInfo().SetExternalLookup(this);
1982  PP->setExternalSource(this);
1983
1984  // Load the translation unit declaration
1985  GetTranslationUnitDecl();
1986
1987  // Load the special types.
1988  Context->setBuiltinVaListType(
1989    GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1990  if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1991    Context->setObjCIdType(GetType(Id));
1992  if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1993    Context->setObjCSelType(GetType(Sel));
1994  if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1995    Context->setObjCProtoType(GetType(Proto));
1996  if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1997    Context->setObjCClassType(GetType(Class));
1998
1999  if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
2000    Context->setCFConstantStringType(GetType(String));
2001  if (unsigned FastEnum
2002        = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2003    Context->setObjCFastEnumerationStateType(GetType(FastEnum));
2004  if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
2005    QualType FileType = GetType(File);
2006    if (FileType.isNull()) {
2007      Error("FILE type is NULL");
2008      return;
2009    }
2010    if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2011      Context->setFILEDecl(Typedef->getDecl());
2012    else {
2013      const TagType *Tag = FileType->getAs<TagType>();
2014      if (!Tag) {
2015        Error("Invalid FILE type in AST file");
2016        return;
2017      }
2018      Context->setFILEDecl(Tag->getDecl());
2019    }
2020  }
2021  if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2022    QualType Jmp_bufType = GetType(Jmp_buf);
2023    if (Jmp_bufType.isNull()) {
2024      Error("jmp_bug type is NULL");
2025      return;
2026    }
2027    if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2028      Context->setjmp_bufDecl(Typedef->getDecl());
2029    else {
2030      const TagType *Tag = Jmp_bufType->getAs<TagType>();
2031      if (!Tag) {
2032        Error("Invalid jmp_buf type in AST file");
2033        return;
2034      }
2035      Context->setjmp_bufDecl(Tag->getDecl());
2036    }
2037  }
2038  if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2039    QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2040    if (Sigjmp_bufType.isNull()) {
2041      Error("sigjmp_buf type is NULL");
2042      return;
2043    }
2044    if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2045      Context->setsigjmp_bufDecl(Typedef->getDecl());
2046    else {
2047      const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2048      assert(Tag && "Invalid sigjmp_buf type in AST file");
2049      Context->setsigjmp_bufDecl(Tag->getDecl());
2050    }
2051  }
2052  if (unsigned ObjCIdRedef
2053        = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2054    Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2055  if (unsigned ObjCClassRedef
2056      = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2057    Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2058  if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2059    Context->setBlockDescriptorType(GetType(String));
2060  if (unsigned String
2061      = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2062    Context->setBlockDescriptorExtendedType(GetType(String));
2063  if (unsigned ObjCSelRedef
2064      = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2065    Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2066  if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2067    Context->setNSConstantStringType(GetType(String));
2068
2069  if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2070    Context->setInt128Installed();
2071}
2072
2073/// \brief Retrieve the name of the original source file name
2074/// directly from the AST file, without actually loading the AST
2075/// file.
2076std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2077                                             Diagnostic &Diags) {
2078  // Open the AST file.
2079  std::string ErrStr;
2080  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2081  Buffer.reset(llvm::MemoryBuffer::getFile(ASTFileName.c_str(), &ErrStr));
2082  if (!Buffer) {
2083    Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2084    return std::string();
2085  }
2086
2087  // Initialize the stream
2088  llvm::BitstreamReader StreamFile;
2089  llvm::BitstreamCursor Stream;
2090  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2091                  (const unsigned char *)Buffer->getBufferEnd());
2092  Stream.init(StreamFile);
2093
2094  // Sniff for the signature.
2095  if (Stream.Read(8) != 'C' ||
2096      Stream.Read(8) != 'P' ||
2097      Stream.Read(8) != 'C' ||
2098      Stream.Read(8) != 'H') {
2099    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2100    return std::string();
2101  }
2102
2103  RecordData Record;
2104  while (!Stream.AtEndOfStream()) {
2105    unsigned Code = Stream.ReadCode();
2106
2107    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2108      unsigned BlockID = Stream.ReadSubBlockID();
2109
2110      // We only know the AST subblock ID.
2111      switch (BlockID) {
2112      case pch::AST_BLOCK_ID:
2113        if (Stream.EnterSubBlock(pch::AST_BLOCK_ID)) {
2114          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2115          return std::string();
2116        }
2117        break;
2118
2119      default:
2120        if (Stream.SkipBlock()) {
2121          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2122          return std::string();
2123        }
2124        break;
2125      }
2126      continue;
2127    }
2128
2129    if (Code == llvm::bitc::END_BLOCK) {
2130      if (Stream.ReadBlockEnd()) {
2131        Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2132        return std::string();
2133      }
2134      continue;
2135    }
2136
2137    if (Code == llvm::bitc::DEFINE_ABBREV) {
2138      Stream.ReadAbbrevRecord();
2139      continue;
2140    }
2141
2142    Record.clear();
2143    const char *BlobStart = 0;
2144    unsigned BlobLen = 0;
2145    if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2146          == pch::ORIGINAL_FILE_NAME)
2147      return std::string(BlobStart, BlobLen);
2148  }
2149
2150  return std::string();
2151}
2152
2153/// \brief Parse the record that corresponds to a LangOptions data
2154/// structure.
2155///
2156/// This routine parses the language options from the AST file and then gives
2157/// them to the AST listener if one is set.
2158///
2159/// \returns true if the listener deems the file unacceptable, false otherwise.
2160bool ASTReader::ParseLanguageOptions(
2161                             const llvm::SmallVectorImpl<uint64_t> &Record) {
2162  if (Listener) {
2163    LangOptions LangOpts;
2164
2165  #define PARSE_LANGOPT(Option)                  \
2166      LangOpts.Option = Record[Idx];             \
2167      ++Idx
2168
2169    unsigned Idx = 0;
2170    PARSE_LANGOPT(Trigraphs);
2171    PARSE_LANGOPT(BCPLComment);
2172    PARSE_LANGOPT(DollarIdents);
2173    PARSE_LANGOPT(AsmPreprocessor);
2174    PARSE_LANGOPT(GNUMode);
2175    PARSE_LANGOPT(GNUKeywords);
2176    PARSE_LANGOPT(ImplicitInt);
2177    PARSE_LANGOPT(Digraphs);
2178    PARSE_LANGOPT(HexFloats);
2179    PARSE_LANGOPT(C99);
2180    PARSE_LANGOPT(Microsoft);
2181    PARSE_LANGOPT(CPlusPlus);
2182    PARSE_LANGOPT(CPlusPlus0x);
2183    PARSE_LANGOPT(CXXOperatorNames);
2184    PARSE_LANGOPT(ObjC1);
2185    PARSE_LANGOPT(ObjC2);
2186    PARSE_LANGOPT(ObjCNonFragileABI);
2187    PARSE_LANGOPT(ObjCNonFragileABI2);
2188    PARSE_LANGOPT(NoConstantCFStrings);
2189    PARSE_LANGOPT(PascalStrings);
2190    PARSE_LANGOPT(WritableStrings);
2191    PARSE_LANGOPT(LaxVectorConversions);
2192    PARSE_LANGOPT(AltiVec);
2193    PARSE_LANGOPT(Exceptions);
2194    PARSE_LANGOPT(SjLjExceptions);
2195    PARSE_LANGOPT(NeXTRuntime);
2196    PARSE_LANGOPT(Freestanding);
2197    PARSE_LANGOPT(NoBuiltin);
2198    PARSE_LANGOPT(ThreadsafeStatics);
2199    PARSE_LANGOPT(POSIXThreads);
2200    PARSE_LANGOPT(Blocks);
2201    PARSE_LANGOPT(EmitAllDecls);
2202    PARSE_LANGOPT(MathErrno);
2203    LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2204                                       Record[Idx++]);
2205    PARSE_LANGOPT(HeinousExtensions);
2206    PARSE_LANGOPT(Optimize);
2207    PARSE_LANGOPT(OptimizeSize);
2208    PARSE_LANGOPT(Static);
2209    PARSE_LANGOPT(PICLevel);
2210    PARSE_LANGOPT(GNUInline);
2211    PARSE_LANGOPT(NoInline);
2212    PARSE_LANGOPT(AccessControl);
2213    PARSE_LANGOPT(CharIsSigned);
2214    PARSE_LANGOPT(ShortWChar);
2215    LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2216    LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
2217    LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
2218                                   Record[Idx++]);
2219    PARSE_LANGOPT(InstantiationDepth);
2220    PARSE_LANGOPT(OpenCL);
2221    PARSE_LANGOPT(CatchUndefined);
2222    // FIXME: Missing ElideConstructors?!
2223  #undef PARSE_LANGOPT
2224
2225    return Listener->ReadLanguageOptions(LangOpts);
2226  }
2227
2228  return false;
2229}
2230
2231void ASTReader::ReadPreprocessedEntities() {
2232  ReadDefinedMacros();
2233}
2234
2235/// \brief Get the correct cursor and offset for loading a type.
2236ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
2237  PerFileData *F = 0;
2238  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2239    F = Chain[N - I - 1];
2240    if (Index < F->LocalNumTypes)
2241      break;
2242    Index -= F->LocalNumTypes;
2243  }
2244  assert(F && F->LocalNumTypes > Index && "Broken chain");
2245  return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
2246}
2247
2248/// \brief Read and return the type with the given index..
2249///
2250/// The index is the type ID, shifted and minus the number of predefs. This
2251/// routine actually reads the record corresponding to the type at the given
2252/// location. It is a helper routine for GetType, which deals with reading type
2253/// IDs.
2254QualType ASTReader::ReadTypeRecord(unsigned Index) {
2255  RecordLocation Loc = TypeCursorForIndex(Index);
2256  llvm::BitstreamCursor &DeclsCursor = *Loc.first;
2257
2258  // Keep track of where we are in the stream, then jump back there
2259  // after reading this type.
2260  SavedStreamPosition SavedPosition(DeclsCursor);
2261
2262  ReadingKindTracker ReadingKind(Read_Type, *this);
2263
2264  // Note that we are loading a type record.
2265  Deserializing AType(this);
2266
2267  DeclsCursor.JumpToBit(Loc.second);
2268  RecordData Record;
2269  unsigned Code = DeclsCursor.ReadCode();
2270  switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
2271  case pch::TYPE_EXT_QUAL: {
2272    if (Record.size() != 2) {
2273      Error("Incorrect encoding of extended qualifier type");
2274      return QualType();
2275    }
2276    QualType Base = GetType(Record[0]);
2277    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2278    return Context->getQualifiedType(Base, Quals);
2279  }
2280
2281  case pch::TYPE_COMPLEX: {
2282    if (Record.size() != 1) {
2283      Error("Incorrect encoding of complex type");
2284      return QualType();
2285    }
2286    QualType ElemType = GetType(Record[0]);
2287    return Context->getComplexType(ElemType);
2288  }
2289
2290  case pch::TYPE_POINTER: {
2291    if (Record.size() != 1) {
2292      Error("Incorrect encoding of pointer type");
2293      return QualType();
2294    }
2295    QualType PointeeType = GetType(Record[0]);
2296    return Context->getPointerType(PointeeType);
2297  }
2298
2299  case pch::TYPE_BLOCK_POINTER: {
2300    if (Record.size() != 1) {
2301      Error("Incorrect encoding of block pointer type");
2302      return QualType();
2303    }
2304    QualType PointeeType = GetType(Record[0]);
2305    return Context->getBlockPointerType(PointeeType);
2306  }
2307
2308  case pch::TYPE_LVALUE_REFERENCE: {
2309    if (Record.size() != 1) {
2310      Error("Incorrect encoding of lvalue reference type");
2311      return QualType();
2312    }
2313    QualType PointeeType = GetType(Record[0]);
2314    return Context->getLValueReferenceType(PointeeType);
2315  }
2316
2317  case pch::TYPE_RVALUE_REFERENCE: {
2318    if (Record.size() != 1) {
2319      Error("Incorrect encoding of rvalue reference type");
2320      return QualType();
2321    }
2322    QualType PointeeType = GetType(Record[0]);
2323    return Context->getRValueReferenceType(PointeeType);
2324  }
2325
2326  case pch::TYPE_MEMBER_POINTER: {
2327    if (Record.size() != 2) {
2328      Error("Incorrect encoding of member pointer type");
2329      return QualType();
2330    }
2331    QualType PointeeType = GetType(Record[0]);
2332    QualType ClassType = GetType(Record[1]);
2333    return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
2334  }
2335
2336  case pch::TYPE_CONSTANT_ARRAY: {
2337    QualType ElementType = GetType(Record[0]);
2338    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2339    unsigned IndexTypeQuals = Record[2];
2340    unsigned Idx = 3;
2341    llvm::APInt Size = ReadAPInt(Record, Idx);
2342    return Context->getConstantArrayType(ElementType, Size,
2343                                         ASM, IndexTypeQuals);
2344  }
2345
2346  case pch::TYPE_INCOMPLETE_ARRAY: {
2347    QualType ElementType = GetType(Record[0]);
2348    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2349    unsigned IndexTypeQuals = Record[2];
2350    return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
2351  }
2352
2353  case pch::TYPE_VARIABLE_ARRAY: {
2354    QualType ElementType = GetType(Record[0]);
2355    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2356    unsigned IndexTypeQuals = Record[2];
2357    SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2358    SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
2359    return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
2360                                         ASM, IndexTypeQuals,
2361                                         SourceRange(LBLoc, RBLoc));
2362  }
2363
2364  case pch::TYPE_VECTOR: {
2365    if (Record.size() != 3) {
2366      Error("incorrect encoding of vector type in AST file");
2367      return QualType();
2368    }
2369
2370    QualType ElementType = GetType(Record[0]);
2371    unsigned NumElements = Record[1];
2372    unsigned AltiVecSpec = Record[2];
2373    return Context->getVectorType(ElementType, NumElements,
2374                                  (VectorType::AltiVecSpecific)AltiVecSpec);
2375  }
2376
2377  case pch::TYPE_EXT_VECTOR: {
2378    if (Record.size() != 3) {
2379      Error("incorrect encoding of extended vector type in AST file");
2380      return QualType();
2381    }
2382
2383    QualType ElementType = GetType(Record[0]);
2384    unsigned NumElements = Record[1];
2385    return Context->getExtVectorType(ElementType, NumElements);
2386  }
2387
2388  case pch::TYPE_FUNCTION_NO_PROTO: {
2389    if (Record.size() != 4) {
2390      Error("incorrect encoding of no-proto function type");
2391      return QualType();
2392    }
2393    QualType ResultType = GetType(Record[0]);
2394    FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
2395    return Context->getFunctionNoProtoType(ResultType, Info);
2396  }
2397
2398  case pch::TYPE_FUNCTION_PROTO: {
2399    QualType ResultType = GetType(Record[0]);
2400    bool NoReturn = Record[1];
2401    unsigned RegParm = Record[2];
2402    CallingConv CallConv = (CallingConv)Record[3];
2403    unsigned Idx = 4;
2404    unsigned NumParams = Record[Idx++];
2405    llvm::SmallVector<QualType, 16> ParamTypes;
2406    for (unsigned I = 0; I != NumParams; ++I)
2407      ParamTypes.push_back(GetType(Record[Idx++]));
2408    bool isVariadic = Record[Idx++];
2409    unsigned Quals = Record[Idx++];
2410    bool hasExceptionSpec = Record[Idx++];
2411    bool hasAnyExceptionSpec = Record[Idx++];
2412    unsigned NumExceptions = Record[Idx++];
2413    llvm::SmallVector<QualType, 2> Exceptions;
2414    for (unsigned I = 0; I != NumExceptions; ++I)
2415      Exceptions.push_back(GetType(Record[Idx++]));
2416    return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
2417                                    isVariadic, Quals, hasExceptionSpec,
2418                                    hasAnyExceptionSpec, NumExceptions,
2419                                    Exceptions.data(),
2420                                    FunctionType::ExtInfo(NoReturn, RegParm,
2421                                                          CallConv));
2422  }
2423
2424  case pch::TYPE_UNRESOLVED_USING:
2425    return Context->getTypeDeclType(
2426             cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2427
2428  case pch::TYPE_TYPEDEF: {
2429    if (Record.size() != 2) {
2430      Error("incorrect encoding of typedef type");
2431      return QualType();
2432    }
2433    TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2434    QualType Canonical = GetType(Record[1]);
2435    return Context->getTypedefType(Decl, Canonical);
2436  }
2437
2438  case pch::TYPE_TYPEOF_EXPR:
2439    return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
2440
2441  case pch::TYPE_TYPEOF: {
2442    if (Record.size() != 1) {
2443      Error("incorrect encoding of typeof(type) in AST file");
2444      return QualType();
2445    }
2446    QualType UnderlyingType = GetType(Record[0]);
2447    return Context->getTypeOfType(UnderlyingType);
2448  }
2449
2450  case pch::TYPE_DECLTYPE:
2451    return Context->getDecltypeType(ReadExpr(DeclsCursor));
2452
2453  case pch::TYPE_RECORD: {
2454    if (Record.size() != 2) {
2455      Error("incorrect encoding of record type");
2456      return QualType();
2457    }
2458    bool IsDependent = Record[0];
2459    QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2460    T->Dependent = IsDependent;
2461    return T;
2462  }
2463
2464  case pch::TYPE_ENUM: {
2465    if (Record.size() != 2) {
2466      Error("incorrect encoding of enum type");
2467      return QualType();
2468    }
2469    bool IsDependent = Record[0];
2470    QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2471    T->Dependent = IsDependent;
2472    return T;
2473  }
2474
2475  case pch::TYPE_ELABORATED: {
2476    unsigned Idx = 0;
2477    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2478    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2479    QualType NamedType = GetType(Record[Idx++]);
2480    return Context->getElaboratedType(Keyword, NNS, NamedType);
2481  }
2482
2483  case pch::TYPE_OBJC_INTERFACE: {
2484    unsigned Idx = 0;
2485    ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
2486    return Context->getObjCInterfaceType(ItfD);
2487  }
2488
2489  case pch::TYPE_OBJC_OBJECT: {
2490    unsigned Idx = 0;
2491    QualType Base = GetType(Record[Idx++]);
2492    unsigned NumProtos = Record[Idx++];
2493    llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2494    for (unsigned I = 0; I != NumProtos; ++I)
2495      Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
2496    return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
2497  }
2498
2499  case pch::TYPE_OBJC_OBJECT_POINTER: {
2500    unsigned Idx = 0;
2501    QualType Pointee = GetType(Record[Idx++]);
2502    return Context->getObjCObjectPointerType(Pointee);
2503  }
2504
2505  case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2506    unsigned Idx = 0;
2507    QualType Parm = GetType(Record[Idx++]);
2508    QualType Replacement = GetType(Record[Idx++]);
2509    return
2510      Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2511                                            Replacement);
2512  }
2513
2514  case pch::TYPE_INJECTED_CLASS_NAME: {
2515    CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2516    QualType TST = GetType(Record[1]); // probably derivable
2517    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2518    // for AST reading, too much interdependencies.
2519    return
2520      QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
2521  }
2522
2523  case pch::TYPE_TEMPLATE_TYPE_PARM: {
2524    unsigned Idx = 0;
2525    unsigned Depth = Record[Idx++];
2526    unsigned Index = Record[Idx++];
2527    bool Pack = Record[Idx++];
2528    IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2529    return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2530  }
2531
2532  case pch::TYPE_DEPENDENT_NAME: {
2533    unsigned Idx = 0;
2534    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2535    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2536    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2537    QualType Canon = GetType(Record[Idx++]);
2538    return Context->getDependentNameType(Keyword, NNS, Name, Canon);
2539  }
2540
2541  case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2542    unsigned Idx = 0;
2543    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2544    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2545    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2546    unsigned NumArgs = Record[Idx++];
2547    llvm::SmallVector<TemplateArgument, 8> Args;
2548    Args.reserve(NumArgs);
2549    while (NumArgs--)
2550      Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
2551    return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2552                                                      Args.size(), Args.data());
2553  }
2554
2555  case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2556    unsigned Idx = 0;
2557
2558    // ArrayType
2559    QualType ElementType = GetType(Record[Idx++]);
2560    ArrayType::ArraySizeModifier ASM
2561      = (ArrayType::ArraySizeModifier)Record[Idx++];
2562    unsigned IndexTypeQuals = Record[Idx++];
2563
2564    // DependentSizedArrayType
2565    Expr *NumElts = ReadExpr(DeclsCursor);
2566    SourceRange Brackets = ReadSourceRange(Record, Idx);
2567
2568    return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2569                                               IndexTypeQuals, Brackets);
2570  }
2571
2572  case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2573    unsigned Idx = 0;
2574    bool IsDependent = Record[Idx++];
2575    TemplateName Name = ReadTemplateName(Record, Idx);
2576    llvm::SmallVector<TemplateArgument, 8> Args;
2577    ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
2578    QualType Canon = GetType(Record[Idx++]);
2579    QualType T;
2580    if (Canon.isNull())
2581      T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2582                                                          Args.size());
2583    else
2584      T = Context->getTemplateSpecializationType(Name, Args.data(),
2585                                                 Args.size(), Canon);
2586    T->Dependent = IsDependent;
2587    return T;
2588  }
2589  }
2590  // Suppress a GCC warning
2591  return QualType();
2592}
2593
2594namespace {
2595
2596class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2597  ASTReader &Reader;
2598  llvm::BitstreamCursor &DeclsCursor;
2599  const ASTReader::RecordData &Record;
2600  unsigned &Idx;
2601
2602public:
2603  TypeLocReader(ASTReader &Reader, llvm::BitstreamCursor &Cursor,
2604                const ASTReader::RecordData &Record, unsigned &Idx)
2605    : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
2606
2607  // We want compile-time assurance that we've enumerated all of
2608  // these, so unfortunately we have to declare them first, then
2609  // define them out-of-line.
2610#define ABSTRACT_TYPELOC(CLASS, PARENT)
2611#define TYPELOC(CLASS, PARENT) \
2612  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
2613#include "clang/AST/TypeLocNodes.def"
2614
2615  void VisitFunctionTypeLoc(FunctionTypeLoc);
2616  void VisitArrayTypeLoc(ArrayTypeLoc);
2617};
2618
2619}
2620
2621void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2622  // nothing to do
2623}
2624void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2625  TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2626  if (TL.needsExtraLocalData()) {
2627    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2628    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2629    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2630    TL.setModeAttr(Record[Idx++]);
2631  }
2632}
2633void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2634  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2635}
2636void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2637  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2638}
2639void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2640  TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2641}
2642void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2643  TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2644}
2645void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2646  TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2647}
2648void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2649  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2650}
2651void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2652  TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2653  TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2654  if (Record[Idx++])
2655    TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
2656  else
2657    TL.setSizeExpr(0);
2658}
2659void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2660  VisitArrayTypeLoc(TL);
2661}
2662void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2663  VisitArrayTypeLoc(TL);
2664}
2665void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2666  VisitArrayTypeLoc(TL);
2667}
2668void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2669                                            DependentSizedArrayTypeLoc TL) {
2670  VisitArrayTypeLoc(TL);
2671}
2672void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2673                                        DependentSizedExtVectorTypeLoc TL) {
2674  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2675}
2676void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2677  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2678}
2679void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2680  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2681}
2682void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2683  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2684  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2685  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2686    TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2687  }
2688}
2689void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2690  VisitFunctionTypeLoc(TL);
2691}
2692void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2693  VisitFunctionTypeLoc(TL);
2694}
2695void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2696  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2697}
2698void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2699  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2700}
2701void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2702  TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2703  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2704  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2705}
2706void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2707  TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2708  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2709  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
2711}
2712void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2713  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2714}
2715void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2716  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2717}
2718void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2719  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720}
2721void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2722  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2723}
2724void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2725                                            SubstTemplateTypeParmTypeLoc TL) {
2726  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2727}
2728void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2729                                           TemplateSpecializationTypeLoc TL) {
2730  TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2731  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2732  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2734    TL.setArgLocInfo(i,
2735        Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2736                                          DeclsCursor, Record, Idx));
2737}
2738void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2739  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2740  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2741}
2742void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2743  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2744}
2745void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2746  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2747  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2748  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2749}
2750void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2751       DependentTemplateSpecializationTypeLoc TL) {
2752  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2753  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2754  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2755  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2756  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2757  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2758    TL.setArgLocInfo(I,
2759        Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2760                                          DeclsCursor, Record, Idx));
2761}
2762void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2763  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2764}
2765void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2766  TL.setHasBaseTypeAsWritten(Record[Idx++]);
2767  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2768  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2769  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2770    TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2771}
2772void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2773  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2774}
2775
2776TypeSourceInfo *ASTReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2777                                             const RecordData &Record,
2778                                             unsigned &Idx) {
2779  QualType InfoTy = GetType(Record[Idx++]);
2780  if (InfoTy.isNull())
2781    return 0;
2782
2783  TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
2784  TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
2785  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2786    TLR.Visit(TL);
2787  return TInfo;
2788}
2789
2790QualType ASTReader::GetType(pch::TypeID ID) {
2791  unsigned FastQuals = ID & Qualifiers::FastMask;
2792  unsigned Index = ID >> Qualifiers::FastWidth;
2793
2794  if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2795    QualType T;
2796    switch ((pch::PredefinedTypeIDs)Index) {
2797    case pch::PREDEF_TYPE_NULL_ID: return QualType();
2798    case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2799    case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
2800
2801    case pch::PREDEF_TYPE_CHAR_U_ID:
2802    case pch::PREDEF_TYPE_CHAR_S_ID:
2803      // FIXME: Check that the signedness of CharTy is correct!
2804      T = Context->CharTy;
2805      break;
2806
2807    case pch::PREDEF_TYPE_UCHAR_ID:      T = Context->UnsignedCharTy;     break;
2808    case pch::PREDEF_TYPE_USHORT_ID:     T = Context->UnsignedShortTy;    break;
2809    case pch::PREDEF_TYPE_UINT_ID:       T = Context->UnsignedIntTy;      break;
2810    case pch::PREDEF_TYPE_ULONG_ID:      T = Context->UnsignedLongTy;     break;
2811    case pch::PREDEF_TYPE_ULONGLONG_ID:  T = Context->UnsignedLongLongTy; break;
2812    case pch::PREDEF_TYPE_UINT128_ID:    T = Context->UnsignedInt128Ty;   break;
2813    case pch::PREDEF_TYPE_SCHAR_ID:      T = Context->SignedCharTy;       break;
2814    case pch::PREDEF_TYPE_WCHAR_ID:      T = Context->WCharTy;            break;
2815    case pch::PREDEF_TYPE_SHORT_ID:      T = Context->ShortTy;            break;
2816    case pch::PREDEF_TYPE_INT_ID:        T = Context->IntTy;              break;
2817    case pch::PREDEF_TYPE_LONG_ID:       T = Context->LongTy;             break;
2818    case pch::PREDEF_TYPE_LONGLONG_ID:   T = Context->LongLongTy;         break;
2819    case pch::PREDEF_TYPE_INT128_ID:     T = Context->Int128Ty;           break;
2820    case pch::PREDEF_TYPE_FLOAT_ID:      T = Context->FloatTy;            break;
2821    case pch::PREDEF_TYPE_DOUBLE_ID:     T = Context->DoubleTy;           break;
2822    case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy;       break;
2823    case pch::PREDEF_TYPE_OVERLOAD_ID:   T = Context->OverloadTy;         break;
2824    case pch::PREDEF_TYPE_DEPENDENT_ID:  T = Context->DependentTy;        break;
2825    case pch::PREDEF_TYPE_NULLPTR_ID:    T = Context->NullPtrTy;          break;
2826    case pch::PREDEF_TYPE_CHAR16_ID:     T = Context->Char16Ty;           break;
2827    case pch::PREDEF_TYPE_CHAR32_ID:     T = Context->Char32Ty;           break;
2828    case pch::PREDEF_TYPE_OBJC_ID:       T = Context->ObjCBuiltinIdTy;    break;
2829    case pch::PREDEF_TYPE_OBJC_CLASS:    T = Context->ObjCBuiltinClassTy; break;
2830    case pch::PREDEF_TYPE_OBJC_SEL:      T = Context->ObjCBuiltinSelTy;   break;
2831    }
2832
2833    assert(!T.isNull() && "Unknown predefined type");
2834    return T.withFastQualifiers(FastQuals);
2835  }
2836
2837  Index -= pch::NUM_PREDEF_TYPE_IDS;
2838  assert(Index < TypesLoaded.size() && "Type index out-of-range");
2839  if (TypesLoaded[Index].isNull()) {
2840    TypesLoaded[Index] = ReadTypeRecord(Index);
2841    TypesLoaded[Index]->setFromAST();
2842    if (DeserializationListener)
2843      DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2844                                        TypesLoaded[Index]);
2845  }
2846
2847  return TypesLoaded[Index].withFastQualifiers(FastQuals);
2848}
2849
2850TemplateArgumentLocInfo
2851ASTReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2852                                      llvm::BitstreamCursor &DeclsCursor,
2853                                      const RecordData &Record,
2854                                      unsigned &Index) {
2855  switch (Kind) {
2856  case TemplateArgument::Expression:
2857    return ReadExpr(DeclsCursor);
2858  case TemplateArgument::Type:
2859    return GetTypeSourceInfo(DeclsCursor, Record, Index);
2860  case TemplateArgument::Template: {
2861    SourceRange QualifierRange = ReadSourceRange(Record, Index);
2862    SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2863    return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
2864  }
2865  case TemplateArgument::Null:
2866  case TemplateArgument::Integral:
2867  case TemplateArgument::Declaration:
2868  case TemplateArgument::Pack:
2869    return TemplateArgumentLocInfo();
2870  }
2871  llvm_unreachable("unexpected template argument loc");
2872  return TemplateArgumentLocInfo();
2873}
2874
2875TemplateArgumentLoc
2876ASTReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2877                                   const RecordData &Record, unsigned &Index) {
2878  TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
2879
2880  if (Arg.getKind() == TemplateArgument::Expression) {
2881    if (Record[Index++]) // bool InfoHasSameExpr.
2882      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2883  }
2884  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
2885                                                             DeclsCursor,
2886                                                             Record, Index));
2887}
2888
2889Decl *ASTReader::GetExternalDecl(uint32_t ID) {
2890  return GetDecl(ID);
2891}
2892
2893TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() {
2894  if (!DeclsLoaded[0]) {
2895    ReadDeclRecord(0, 0);
2896    if (DeserializationListener)
2897      DeserializationListener->DeclRead(1, DeclsLoaded[0]);
2898  }
2899
2900  return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2901}
2902
2903Decl *ASTReader::GetDecl(pch::DeclID ID) {
2904  if (ID == 0)
2905    return 0;
2906
2907  if (ID > DeclsLoaded.size()) {
2908    Error("declaration ID out-of-range for AST file");
2909    return 0;
2910  }
2911
2912  unsigned Index = ID - 1;
2913  if (!DeclsLoaded[Index]) {
2914    ReadDeclRecord(Index, ID);
2915    if (DeserializationListener)
2916      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2917  }
2918
2919  return DeclsLoaded[Index];
2920}
2921
2922/// \brief Resolve the offset of a statement into a statement.
2923///
2924/// This operation will read a new statement from the external
2925/// source each time it is called, and is meant to be used via a
2926/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2927Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
2928  // Offset here is a global offset across the entire chain.
2929  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2930    PerFileData &F = *Chain[N - I - 1];
2931    if (Offset < F.SizeInBits) {
2932      // Since we know that this statement is part of a decl, make sure to use
2933      // the decl cursor to read it.
2934      F.DeclsCursor.JumpToBit(Offset);
2935      return ReadStmtFromStream(F.DeclsCursor);
2936    }
2937    Offset -= F.SizeInBits;
2938  }
2939  llvm_unreachable("Broken chain");
2940}
2941
2942bool ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
2943                                         llvm::SmallVectorImpl<Decl*> &Decls) {
2944  assert(DC->hasExternalLexicalStorage() &&
2945         "DeclContext has no lexical decls in storage");
2946
2947  // There might be lexical decls in multiple parts of the chain, for the TU
2948  // at least.
2949  DeclContextInfos &Infos = DeclContextOffsets[DC];
2950  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2951       I != E; ++I) {
2952    // IDs can be 0 if this context doesn't contain declarations.
2953    if (!I->LexicalDecls)
2954      continue;
2955
2956    // Load all of the declaration IDs
2957    for (const pch::DeclID *ID = I->LexicalDecls,
2958                           *IDE = ID + I->NumLexicalDecls;
2959         ID != IDE; ++ID)
2960      Decls.push_back(GetDecl(*ID));
2961  }
2962
2963  ++NumLexicalDeclContextsRead;
2964  return false;
2965}
2966
2967DeclContext::lookup_result
2968ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2969                                          DeclarationName Name) {
2970  assert(DC->hasExternalVisibleStorage() &&
2971         "DeclContext has no visible decls in storage");
2972
2973  llvm::SmallVector<VisibleDeclaration, 64> Decls;
2974  // There might be lexical decls in multiple parts of the chain, for the TU
2975  // and namespaces.
2976  DeclContextInfos &Infos = DeclContextOffsets[DC];
2977  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2978       I != E; ++I) {
2979    uint64_t Offset = I->OffsetToVisibleDecls;
2980    if (Offset == 0)
2981      continue;
2982
2983    llvm::BitstreamCursor &DeclsCursor = *I->Stream;
2984
2985    // Keep track of where we are in the stream, then jump back there
2986    // after reading this context.
2987    SavedStreamPosition SavedPosition(DeclsCursor);
2988
2989    // Load the record containing all of the declarations visible in
2990    // this context.
2991    DeclsCursor.JumpToBit(Offset);
2992    RecordData Record;
2993    unsigned Code = DeclsCursor.ReadCode();
2994    unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2995    if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2996      Error("Expected visible block");
2997      return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2998                                        DeclContext::lookup_iterator());
2999    }
3000
3001    if (Record.empty())
3002      continue;
3003
3004    unsigned Idx = 0;
3005    while (Idx < Record.size()) {
3006      Decls.push_back(VisibleDeclaration());
3007      Decls.back().Name = ReadDeclarationName(Record, Idx);
3008
3009      unsigned Size = Record[Idx++];
3010      llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3011      LoadedDecls.reserve(Size);
3012      for (unsigned J = 0; J < Size; ++J)
3013        LoadedDecls.push_back(Record[Idx++]);
3014    }
3015  }
3016
3017  ++NumVisibleDeclContextsRead;
3018
3019  SetExternalVisibleDecls(DC, Decls);
3020  return const_cast<DeclContext*>(DC)->lookup(Name);
3021}
3022
3023void ASTReader::PassInterestingDeclsToConsumer() {
3024  assert(Consumer);
3025  while (!InterestingDecls.empty()) {
3026    DeclGroupRef DG(InterestingDecls.front());
3027    InterestingDecls.pop_front();
3028    Consumer->HandleInterestingDecl(DG);
3029  }
3030}
3031
3032void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
3033  this->Consumer = Consumer;
3034
3035  if (!Consumer)
3036    return;
3037
3038  for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
3039    // Force deserialization of this decl, which will cause it to be queued for
3040    // passing to the consumer.
3041    GetDecl(ExternalDefinitions[I]);
3042  }
3043
3044  PassInterestingDeclsToConsumer();
3045}
3046
3047void ASTReader::PrintStats() {
3048  std::fprintf(stderr, "*** AST File Statistics:\n");
3049
3050  unsigned NumTypesLoaded
3051    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
3052                                      QualType());
3053  unsigned NumDeclsLoaded
3054    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3055                                      (Decl *)0);
3056  unsigned NumIdentifiersLoaded
3057    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3058                                            IdentifiersLoaded.end(),
3059                                            (IdentifierInfo *)0);
3060  unsigned NumSelectorsLoaded
3061    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3062                                          SelectorsLoaded.end(),
3063                                          Selector());
3064
3065  std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
3066  std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
3067  if (TotalNumSLocEntries)
3068    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
3069                 NumSLocEntriesRead, TotalNumSLocEntries,
3070                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
3071  if (!TypesLoaded.empty())
3072    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
3073                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3074                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3075  if (!DeclsLoaded.empty())
3076    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
3077                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3078                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
3079  if (!IdentifiersLoaded.empty())
3080    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
3081                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3082                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
3083  if (!SelectorsLoaded.empty())
3084    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
3085                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3086                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
3087  if (TotalNumStatements)
3088    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
3089                 NumStatementsRead, TotalNumStatements,
3090                 ((float)NumStatementsRead/TotalNumStatements * 100));
3091  if (TotalNumMacros)
3092    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
3093                 NumMacrosRead, TotalNumMacros,
3094                 ((float)NumMacrosRead/TotalNumMacros * 100));
3095  if (TotalLexicalDeclContexts)
3096    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
3097                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3098                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3099                  * 100));
3100  if (TotalVisibleDeclContexts)
3101    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
3102                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3103                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3104                  * 100));
3105  if (TotalNumMethodPoolEntries) {
3106    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
3107                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3108                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
3109                  * 100));
3110    std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
3111  }
3112  std::fprintf(stderr, "\n");
3113}
3114
3115void ASTReader::InitializeSema(Sema &S) {
3116  SemaObj = &S;
3117  S.ExternalSource = this;
3118
3119  // Makes sure any declarations that were deserialized "too early"
3120  // still get added to the identifier's declaration chains.
3121  if (SemaObj->TUScope) {
3122    for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3123      SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3124      SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
3125    }
3126  }
3127  PreloadedDecls.clear();
3128
3129  // If there were any tentative definitions, deserialize them and add
3130  // them to Sema's list of tentative definitions.
3131  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3132    VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
3133    SemaObj->TentativeDefinitions.push_back(Var);
3134  }
3135
3136  // If there were any unused file scoped decls, deserialize them and add to
3137  // Sema's list of unused file scoped decls.
3138  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
3139    DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
3140    SemaObj->UnusedFileScopedDecls.push_back(D);
3141  }
3142
3143  // If there were any weak undeclared identifiers, deserialize them and add to
3144  // Sema's list of weak undeclared identifiers.
3145  if (!WeakUndeclaredIdentifiers.empty()) {
3146    unsigned Idx = 0;
3147    for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
3148      IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3149      IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3150      SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
3151      bool Used = WeakUndeclaredIdentifiers[Idx++];
3152      Sema::WeakInfo WI(AliasId, Loc);
3153      WI.setUsed(Used);
3154      SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
3155    }
3156  }
3157
3158  // If there were any locally-scoped external declarations,
3159  // deserialize them and add them to Sema's table of locally-scoped
3160  // external declarations.
3161  for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3162    NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3163    SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3164  }
3165
3166  // If there were any ext_vector type declarations, deserialize them
3167  // and add them to Sema's vector of such declarations.
3168  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3169    SemaObj->ExtVectorDecls.push_back(
3170                               cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
3171
3172  // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3173  // Can we cut them down before writing them ?
3174
3175  // If there were any VTable uses, deserialize the information and add it
3176  // to Sema's vector and map of VTable uses.
3177  if (!VTableUses.empty()) {
3178    unsigned Idx = 0;
3179    for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3180      CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3181      SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3182      bool DefinitionRequired = VTableUses[Idx++];
3183      SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3184      SemaObj->VTablesUsed[Class] = DefinitionRequired;
3185    }
3186  }
3187
3188  // If there were any dynamic classes declarations, deserialize them
3189  // and add them to Sema's vector of such declarations.
3190  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3191    SemaObj->DynamicClasses.push_back(
3192                               cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
3193
3194  // If there were any pending implicit instantiations, deserialize them
3195  // and add them to Sema's queue of such instantiations.
3196  assert(PendingImplicitInstantiations.size() % 2 == 0 &&
3197         "Expected pairs of entries");
3198  for (unsigned Idx = 0, N = PendingImplicitInstantiations.size(); Idx < N;) {
3199    ValueDecl *D=cast<ValueDecl>(GetDecl(PendingImplicitInstantiations[Idx++]));
3200    SourceLocation Loc = ReadSourceLocation(PendingImplicitInstantiations, Idx);
3201    SemaObj->PendingImplicitInstantiations.push_back(std::make_pair(D, Loc));
3202  }
3203
3204  // Load the offsets of the declarations that Sema references.
3205  // They will be lazily deserialized when needed.
3206  if (!SemaDeclRefs.empty()) {
3207    assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3208    SemaObj->StdNamespace = SemaDeclRefs[0];
3209    SemaObj->StdBadAlloc = SemaDeclRefs[1];
3210  }
3211
3212  // If there are @selector references added them to its pool. This is for
3213  // implementation of -Wselector.
3214  if (!ReferencedSelectorsData.empty()) {
3215    unsigned int DataSize = ReferencedSelectorsData.size()-1;
3216    unsigned I = 0;
3217    while (I < DataSize) {
3218      Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
3219      SourceLocation SelLoc =
3220        SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
3221      SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3222    }
3223  }
3224}
3225
3226IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
3227  // Try to find this name within our on-disk hash tables. We start with the
3228  // most recent one, since that one contains the most up-to-date info.
3229  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3230    ASTIdentifierLookupTable *IdTable
3231        = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
3232    if (!IdTable)
3233      continue;
3234    std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3235    ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3236    if (Pos == IdTable->end())
3237      continue;
3238
3239    // Dereferencing the iterator has the effect of building the
3240    // IdentifierInfo node and populating it with the various
3241    // declarations it needs.
3242    return *Pos;
3243  }
3244  return 0;
3245}
3246
3247std::pair<ObjCMethodList, ObjCMethodList>
3248ASTReader::ReadMethodPool(Selector Sel) {
3249  // Find this selector in a hash table. We want to find the most recent entry.
3250  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3251    PerFileData &F = *Chain[I];
3252    if (!F.SelectorLookupTable)
3253      continue;
3254
3255    ASTSelectorLookupTable *PoolTable
3256      = (ASTSelectorLookupTable*)F.SelectorLookupTable;
3257    ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3258    if (Pos != PoolTable->end()) {
3259      ++NumSelectorsRead;
3260      // FIXME: Not quite happy with the statistics here. We probably should
3261      // disable this tracking when called via LoadSelector.
3262      // Also, should entries without methods count as misses?
3263      ++NumMethodPoolEntriesRead;
3264      ASTSelectorLookupTrait::data_type Data = *Pos;
3265      if (DeserializationListener)
3266        DeserializationListener->SelectorRead(Data.ID, Sel);
3267      return std::make_pair(Data.Instance, Data.Factory);
3268    }
3269  }
3270
3271  ++NumMethodPoolMisses;
3272  return std::pair<ObjCMethodList, ObjCMethodList>();
3273}
3274
3275void ASTReader::LoadSelector(Selector Sel) {
3276  // It would be complicated to avoid reading the methods anyway. So don't.
3277  ReadMethodPool(Sel);
3278}
3279
3280void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
3281  assert(ID && "Non-zero identifier ID required");
3282  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
3283  IdentifiersLoaded[ID - 1] = II;
3284  if (DeserializationListener)
3285    DeserializationListener->IdentifierRead(ID, II);
3286}
3287
3288/// \brief Set the globally-visible declarations associated with the given
3289/// identifier.
3290///
3291/// If the AST reader is currently in a state where the given declaration IDs
3292/// cannot safely be resolved, they are queued until it is safe to resolve
3293/// them.
3294///
3295/// \param II an IdentifierInfo that refers to one or more globally-visible
3296/// declarations.
3297///
3298/// \param DeclIDs the set of declaration IDs with the name @p II that are
3299/// visible at global scope.
3300///
3301/// \param Nonrecursive should be true to indicate that the caller knows that
3302/// this call is non-recursive, and therefore the globally-visible declarations
3303/// will not be placed onto the pending queue.
3304void
3305ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
3306                              const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3307                                   bool Nonrecursive) {
3308  if (NumCurrentElementsDeserializing && !Nonrecursive) {
3309    PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3310    PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3311    PII.II = II;
3312    for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3313      PII.DeclIDs.push_back(DeclIDs[I]);
3314    return;
3315  }
3316
3317  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3318    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3319    if (SemaObj) {
3320      if (SemaObj->TUScope) {
3321        // Introduce this declaration into the translation-unit scope
3322        // and add it to the declaration chain for this identifier, so
3323        // that (unqualified) name lookup will find it.
3324        SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3325        SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3326      }
3327    } else {
3328      // Queue this declaration so that it will be added to the
3329      // translation unit scope and identifier's declaration chain
3330      // once a Sema object is known.
3331      PreloadedDecls.push_back(D);
3332    }
3333  }
3334}
3335
3336IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) {
3337  if (ID == 0)
3338    return 0;
3339
3340  if (IdentifiersLoaded.empty()) {
3341    Error("no identifier table in AST file");
3342    return 0;
3343  }
3344
3345  assert(PP && "Forgot to set Preprocessor ?");
3346  ID -= 1;
3347  if (!IdentifiersLoaded[ID]) {
3348    unsigned Index = ID;
3349    const char *Str = 0;
3350    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3351      PerFileData *F = Chain[N - I - 1];
3352      if (Index < F->LocalNumIdentifiers) {
3353         uint32_t Offset = F->IdentifierOffsets[Index];
3354         Str = F->IdentifierTableData + Offset;
3355         break;
3356      }
3357      Index -= F->LocalNumIdentifiers;
3358    }
3359    assert(Str && "Broken Chain");
3360
3361    // All of the strings in the AST file are preceded by a 16-bit length.
3362    // Extract that 16-bit length to avoid having to execute strlen().
3363    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3364    //  unsigned integers.  This is important to avoid integer overflow when
3365    //  we cast them to 'unsigned'.
3366    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
3367    unsigned StrLen = (((unsigned) StrLenPtr[0])
3368                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
3369    IdentifiersLoaded[ID]
3370      = &PP->getIdentifierTable().get(Str, StrLen);
3371    if (DeserializationListener)
3372      DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
3373  }
3374
3375  return IdentifiersLoaded[ID];
3376}
3377
3378void ASTReader::ReadSLocEntry(unsigned ID) {
3379  ReadSLocEntryRecord(ID);
3380}
3381
3382Selector ASTReader::DecodeSelector(unsigned ID) {
3383  if (ID == 0)
3384    return Selector();
3385
3386  if (ID > SelectorsLoaded.size()) {
3387    Error("selector ID out of range in AST file");
3388    return Selector();
3389  }
3390
3391  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
3392    // Load this selector from the selector table.
3393    unsigned Idx = ID - 1;
3394    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3395      PerFileData &F = *Chain[N - I - 1];
3396      if (Idx < F.LocalNumSelectors) {
3397        ASTSelectorLookupTrait Trait(*this);
3398        SelectorsLoaded[ID - 1] =
3399           Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3400        if (DeserializationListener)
3401          DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3402        break;
3403      }
3404      Idx -= F.LocalNumSelectors;
3405    }
3406  }
3407
3408  return SelectorsLoaded[ID - 1];
3409}
3410
3411Selector ASTReader::GetExternalSelector(uint32_t ID) {
3412  return DecodeSelector(ID);
3413}
3414
3415uint32_t ASTReader::GetNumExternalSelectors() {
3416  // ID 0 (the null selector) is considered an external selector.
3417  return getTotalNumSelectors() + 1;
3418}
3419
3420DeclarationName
3421ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3422  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3423  switch (Kind) {
3424  case DeclarationName::Identifier:
3425    return DeclarationName(GetIdentifierInfo(Record, Idx));
3426
3427  case DeclarationName::ObjCZeroArgSelector:
3428  case DeclarationName::ObjCOneArgSelector:
3429  case DeclarationName::ObjCMultiArgSelector:
3430    return DeclarationName(GetSelector(Record, Idx));
3431
3432  case DeclarationName::CXXConstructorName:
3433    return Context->DeclarationNames.getCXXConstructorName(
3434                          Context->getCanonicalType(GetType(Record[Idx++])));
3435
3436  case DeclarationName::CXXDestructorName:
3437    return Context->DeclarationNames.getCXXDestructorName(
3438                          Context->getCanonicalType(GetType(Record[Idx++])));
3439
3440  case DeclarationName::CXXConversionFunctionName:
3441    return Context->DeclarationNames.getCXXConversionFunctionName(
3442                          Context->getCanonicalType(GetType(Record[Idx++])));
3443
3444  case DeclarationName::CXXOperatorName:
3445    return Context->DeclarationNames.getCXXOperatorName(
3446                                       (OverloadedOperatorKind)Record[Idx++]);
3447
3448  case DeclarationName::CXXLiteralOperatorName:
3449    return Context->DeclarationNames.getCXXLiteralOperatorName(
3450                                       GetIdentifierInfo(Record, Idx));
3451
3452  case DeclarationName::CXXUsingDirective:
3453    return DeclarationName::getUsingDirectiveName();
3454  }
3455
3456  // Required to silence GCC warning
3457  return DeclarationName();
3458}
3459
3460TemplateName
3461ASTReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3462  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3463  switch (Kind) {
3464  case TemplateName::Template:
3465    return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3466
3467  case TemplateName::OverloadedTemplate: {
3468    unsigned size = Record[Idx++];
3469    UnresolvedSet<8> Decls;
3470    while (size--)
3471      Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3472
3473    return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3474  }
3475
3476  case TemplateName::QualifiedTemplate: {
3477    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3478    bool hasTemplKeyword = Record[Idx++];
3479    TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3480    return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3481  }
3482
3483  case TemplateName::DependentTemplate: {
3484    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3485    if (Record[Idx++])  // isIdentifier
3486      return Context->getDependentTemplateName(NNS,
3487                                               GetIdentifierInfo(Record, Idx));
3488    return Context->getDependentTemplateName(NNS,
3489                                         (OverloadedOperatorKind)Record[Idx++]);
3490  }
3491  }
3492
3493  assert(0 && "Unhandled template name kind!");
3494  return TemplateName();
3495}
3496
3497TemplateArgument
3498ASTReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3499                                const RecordData &Record, unsigned &Idx) {
3500  switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3501  case TemplateArgument::Null:
3502    return TemplateArgument();
3503  case TemplateArgument::Type:
3504    return TemplateArgument(GetType(Record[Idx++]));
3505  case TemplateArgument::Declaration:
3506    return TemplateArgument(GetDecl(Record[Idx++]));
3507  case TemplateArgument::Integral: {
3508    llvm::APSInt Value = ReadAPSInt(Record, Idx);
3509    QualType T = GetType(Record[Idx++]);
3510    return TemplateArgument(Value, T);
3511  }
3512  case TemplateArgument::Template:
3513    return TemplateArgument(ReadTemplateName(Record, Idx));
3514  case TemplateArgument::Expression:
3515    return TemplateArgument(ReadExpr(DeclsCursor));
3516  case TemplateArgument::Pack: {
3517    unsigned NumArgs = Record[Idx++];
3518    llvm::SmallVector<TemplateArgument, 8> Args;
3519    Args.reserve(NumArgs);
3520    while (NumArgs--)
3521      Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
3522    TemplateArgument TemplArg;
3523    TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3524    return TemplArg;
3525  }
3526  }
3527
3528  assert(0 && "Unhandled template argument kind!");
3529  return TemplateArgument();
3530}
3531
3532TemplateParameterList *
3533ASTReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3534  SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3535  SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3536  SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3537
3538  unsigned NumParams = Record[Idx++];
3539  llvm::SmallVector<NamedDecl *, 16> Params;
3540  Params.reserve(NumParams);
3541  while (NumParams--)
3542    Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3543
3544  TemplateParameterList* TemplateParams =
3545    TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3546                                  Params.data(), Params.size(), RAngleLoc);
3547  return TemplateParams;
3548}
3549
3550void
3551ASTReader::
3552ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3553                         llvm::BitstreamCursor &DeclsCursor,
3554                         const RecordData &Record, unsigned &Idx) {
3555  unsigned NumTemplateArgs = Record[Idx++];
3556  TemplArgs.reserve(NumTemplateArgs);
3557  while (NumTemplateArgs--)
3558    TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
3559}
3560
3561/// \brief Read a UnresolvedSet structure.
3562void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3563                                  const RecordData &Record, unsigned &Idx) {
3564  unsigned NumDecls = Record[Idx++];
3565  while (NumDecls--) {
3566    NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3567    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3568    Set.addDecl(D, AS);
3569  }
3570}
3571
3572CXXBaseSpecifier
3573ASTReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3574                                const RecordData &Record, unsigned &Idx) {
3575  bool isVirtual = static_cast<bool>(Record[Idx++]);
3576  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3577  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3578  TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
3579  SourceRange Range = ReadSourceRange(Record, Idx);
3580  return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
3581}
3582
3583std::pair<CXXBaseOrMemberInitializer **, unsigned>
3584ASTReader::ReadCXXBaseOrMemberInitializers(llvm::BitstreamCursor &Cursor,
3585                                           const RecordData &Record,
3586                                           unsigned &Idx) {
3587  CXXBaseOrMemberInitializer **BaseOrMemberInitializers = 0;
3588  unsigned NumInitializers = Record[Idx++];
3589  if (NumInitializers) {
3590    ASTContext &C = *getContext();
3591
3592    BaseOrMemberInitializers
3593        = new (C) CXXBaseOrMemberInitializer*[NumInitializers];
3594    for (unsigned i=0; i != NumInitializers; ++i) {
3595      TypeSourceInfo *BaseClassInfo = 0;
3596      bool IsBaseVirtual = false;
3597      FieldDecl *Member = 0;
3598
3599      bool IsBaseInitializer = Record[Idx++];
3600      if (IsBaseInitializer) {
3601        BaseClassInfo = GetTypeSourceInfo(Cursor, Record, Idx);
3602        IsBaseVirtual = Record[Idx++];
3603      } else {
3604        Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
3605      }
3606      SourceLocation MemberLoc = ReadSourceLocation(Record, Idx);
3607      Expr *Init = ReadExpr(Cursor);
3608      FieldDecl *AnonUnionMember
3609          = cast_or_null<FieldDecl>(GetDecl(Record[Idx++]));
3610      SourceLocation LParenLoc = ReadSourceLocation(Record, Idx);
3611      SourceLocation RParenLoc = ReadSourceLocation(Record, Idx);
3612      bool IsWritten = Record[Idx++];
3613      unsigned SourceOrderOrNumArrayIndices;
3614      llvm::SmallVector<VarDecl *, 8> Indices;
3615      if (IsWritten) {
3616        SourceOrderOrNumArrayIndices = Record[Idx++];
3617      } else {
3618        SourceOrderOrNumArrayIndices = Record[Idx++];
3619        Indices.reserve(SourceOrderOrNumArrayIndices);
3620        for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
3621          Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
3622      }
3623
3624      CXXBaseOrMemberInitializer *BOMInit;
3625      if (IsBaseInitializer) {
3626        BOMInit = new (C) CXXBaseOrMemberInitializer(C, BaseClassInfo,
3627                                                     IsBaseVirtual, LParenLoc,
3628                                                     Init, RParenLoc);
3629      } else if (IsWritten) {
3630        BOMInit = new (C) CXXBaseOrMemberInitializer(C, Member, MemberLoc,
3631                                                     LParenLoc, Init, RParenLoc);
3632      } else {
3633        BOMInit = CXXBaseOrMemberInitializer::Create(C, Member, MemberLoc,
3634                                                     LParenLoc, Init, RParenLoc,
3635                                                     Indices.data(),
3636                                                     Indices.size());
3637      }
3638
3639      BOMInit->setAnonUnionMember(AnonUnionMember);
3640      BaseOrMemberInitializers[i] = BOMInit;
3641    }
3642  }
3643
3644  return std::make_pair(BaseOrMemberInitializers, NumInitializers);
3645}
3646
3647NestedNameSpecifier *
3648ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3649  unsigned N = Record[Idx++];
3650  NestedNameSpecifier *NNS = 0, *Prev = 0;
3651  for (unsigned I = 0; I != N; ++I) {
3652    NestedNameSpecifier::SpecifierKind Kind
3653      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3654    switch (Kind) {
3655    case NestedNameSpecifier::Identifier: {
3656      IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3657      NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3658      break;
3659    }
3660
3661    case NestedNameSpecifier::Namespace: {
3662      NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3663      NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3664      break;
3665    }
3666
3667    case NestedNameSpecifier::TypeSpec:
3668    case NestedNameSpecifier::TypeSpecWithTemplate: {
3669      Type *T = GetType(Record[Idx++]).getTypePtr();
3670      bool Template = Record[Idx++];
3671      NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3672      break;
3673    }
3674
3675    case NestedNameSpecifier::Global: {
3676      NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3677      // No associated value, and there can't be a prefix.
3678      break;
3679    }
3680    }
3681    Prev = NNS;
3682  }
3683  return NNS;
3684}
3685
3686SourceRange
3687ASTReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
3688  SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3689  SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3690  return SourceRange(beg, end);
3691}
3692
3693/// \brief Read an integral value
3694llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3695  unsigned BitWidth = Record[Idx++];
3696  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3697  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3698  Idx += NumWords;
3699  return Result;
3700}
3701
3702/// \brief Read a signed integral value
3703llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3704  bool isUnsigned = Record[Idx++];
3705  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3706}
3707
3708/// \brief Read a floating-point value
3709llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
3710  return llvm::APFloat(ReadAPInt(Record, Idx));
3711}
3712
3713// \brief Read a string
3714std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
3715  unsigned Len = Record[Idx++];
3716  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
3717  Idx += Len;
3718  return Result;
3719}
3720
3721CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record,
3722                                          unsigned &Idx) {
3723  CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3724  return CXXTemporary::Create(*Context, Decl);
3725}
3726
3727DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
3728  return Diag(SourceLocation(), DiagID);
3729}
3730
3731DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
3732  return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
3733}
3734
3735/// \brief Retrieve the identifier table associated with the
3736/// preprocessor.
3737IdentifierTable &ASTReader::getIdentifierTable() {
3738  assert(PP && "Forgot to set Preprocessor ?");
3739  return PP->getIdentifierTable();
3740}
3741
3742/// \brief Record that the given ID maps to the given switch-case
3743/// statement.
3744void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3745  assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3746  SwitchCaseStmts[ID] = SC;
3747}
3748
3749/// \brief Retrieve the switch-case statement with the given ID.
3750SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
3751  assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3752  return SwitchCaseStmts[ID];
3753}
3754
3755/// \brief Record that the given label statement has been
3756/// deserialized and has the given ID.
3757void ASTReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
3758  assert(LabelStmts.find(ID) == LabelStmts.end() &&
3759         "Deserialized label twice");
3760  LabelStmts[ID] = S;
3761
3762  // If we've already seen any goto statements that point to this
3763  // label, resolve them now.
3764  typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3765  std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3766  for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3767    Goto->second->setLabel(S);
3768  UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
3769
3770  // If we've already seen any address-label statements that point to
3771  // this label, resolve them now.
3772  typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
3773  std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
3774    = UnresolvedAddrLabelExprs.equal_range(ID);
3775  for (AddrLabelIter AddrLabel = AddrLabels.first;
3776       AddrLabel != AddrLabels.second; ++AddrLabel)
3777    AddrLabel->second->setLabel(S);
3778  UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
3779}
3780
3781/// \brief Set the label of the given statement to the label
3782/// identified by ID.
3783///
3784/// Depending on the order in which the label and other statements
3785/// referencing that label occur, this operation may complete
3786/// immediately (updating the statement) or it may queue the
3787/// statement to be back-patched later.
3788void ASTReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3789  std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3790  if (Label != LabelStmts.end()) {
3791    // We've already seen this label, so set the label of the goto and
3792    // we're done.
3793    S->setLabel(Label->second);
3794  } else {
3795    // We haven't seen this label yet, so add this goto to the set of
3796    // unresolved goto statements.
3797    UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3798  }
3799}
3800
3801/// \brief Set the label of the given expression to the label
3802/// identified by ID.
3803///
3804/// Depending on the order in which the label and other statements
3805/// referencing that label occur, this operation may complete
3806/// immediately (updating the statement) or it may queue the
3807/// statement to be back-patched later.
3808void ASTReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3809  std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3810  if (Label != LabelStmts.end()) {
3811    // We've already seen this label, so set the label of the
3812    // label-address expression and we're done.
3813    S->setLabel(Label->second);
3814  } else {
3815    // We haven't seen this label yet, so add this label-address
3816    // expression to the set of unresolved label-address expressions.
3817    UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3818  }
3819}
3820
3821void ASTReader::FinishedDeserializing() {
3822  assert(NumCurrentElementsDeserializing &&
3823         "FinishedDeserializing not paired with StartedDeserializing");
3824  if (NumCurrentElementsDeserializing == 1) {
3825    // If any identifiers with corresponding top-level declarations have
3826    // been loaded, load those declarations now.
3827    while (!PendingIdentifierInfos.empty()) {
3828      SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3829                              PendingIdentifierInfos.front().DeclIDs, true);
3830      PendingIdentifierInfos.pop_front();
3831    }
3832
3833    // We are not in recursive loading, so it's safe to pass the "interesting"
3834    // decls to the consumer.
3835    if (Consumer)
3836      PassInterestingDeclsToConsumer();
3837  }
3838  --NumCurrentElementsDeserializing;
3839}
3840