ASTReader.cpp revision 8b5b4099c61a136e9a1714c4d8a593febe942268
1//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "clang/Serialization/ASTDeserializationListener.h"
16#include "ASTCommon.h"
17#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/Utils.h"
19#include "clang/Sema/Sema.h"
20#include "clang/Sema/Scope.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/Type.h"
28#include "clang/AST/TypeLocVisitor.h"
29#include "clang/Lex/MacroInfo.h"
30#include "clang/Lex/PreprocessingRecord.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "clang/Basic/OnDiskHashTable.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/SourceManagerInternals.h"
36#include "clang/Basic/FileManager.h"
37#include "clang/Basic/FileSystemStatCache.h"
38#include "clang/Basic/TargetInfo.h"
39#include "clang/Basic/Version.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/Bitcode/BitstreamReader.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/FileSystem.h"
45#include "llvm/Support/Path.h"
46#include "llvm/Support/system_error.h"
47#include <algorithm>
48#include <iterator>
49#include <cstdio>
50#include <sys/stat.h>
51
52using namespace clang;
53using namespace clang::serialization;
54
55//===----------------------------------------------------------------------===//
56// PCH validator implementation
57//===----------------------------------------------------------------------===//
58
59ASTReaderListener::~ASTReaderListener() {}
60
61bool
62PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
63  const LangOptions &PPLangOpts = PP.getLangOptions();
64#define PARSE_LANGOPT_BENIGN(Option)
65#define PARSE_LANGOPT_IMPORTANT(Option, DiagID)                    \
66  if (PPLangOpts.Option != LangOpts.Option) {                      \
67    Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option;   \
68    return true;                                                   \
69  }
70
71  PARSE_LANGOPT_BENIGN(Trigraphs);
72  PARSE_LANGOPT_BENIGN(BCPLComment);
73  PARSE_LANGOPT_BENIGN(DollarIdents);
74  PARSE_LANGOPT_BENIGN(AsmPreprocessor);
75  PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
76  PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
77  PARSE_LANGOPT_BENIGN(ImplicitInt);
78  PARSE_LANGOPT_BENIGN(Digraphs);
79  PARSE_LANGOPT_BENIGN(HexFloats);
80  PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
81  PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
82  PARSE_LANGOPT_BENIGN(MSCVersion);
83  PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
84  PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
85  PARSE_LANGOPT_BENIGN(CXXOperatorName);
86  PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
87  PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
88  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
89  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
90  PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext);
91  PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties,
92                          diag::warn_pch_objc_auto_properties);
93  PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
94                          diag::warn_pch_no_constant_cfstrings);
95  PARSE_LANGOPT_BENIGN(PascalStrings);
96  PARSE_LANGOPT_BENIGN(WritableStrings);
97  PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
98                          diag::warn_pch_lax_vector_conversions);
99  PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
100  PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
101  PARSE_LANGOPT_IMPORTANT(ObjCExceptions, diag::warn_pch_objc_exceptions);
102  PARSE_LANGOPT_IMPORTANT(CXXExceptions, diag::warn_pch_cxx_exceptions);
103  PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
104  PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields);
105  PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
106  PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
107  PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
108  PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
109                          diag::warn_pch_thread_safe_statics);
110  PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
111  PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
112  PARSE_LANGOPT_BENIGN(EmitAllDecls);
113  PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
114  PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
115  PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
116                          diag::warn_pch_heinous_extensions);
117  // FIXME: Most of the options below are benign if the macro wasn't
118  // used. Unfortunately, this means that a PCH compiled without
119  // optimization can't be used with optimization turned on, even
120  // though the only thing that changes is whether __OPTIMIZE__ was
121  // defined... but if __OPTIMIZE__ never showed up in the header, it
122  // doesn't matter. We could consider making this some special kind
123  // of check.
124  PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
125  PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
126  PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
127  PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
128  PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
129  PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
130  PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
131  PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
132  PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
133  PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums);
134  if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
135    Reader.Diag(diag::warn_pch_gc_mode)
136      << LangOpts.getGCMode() << PPLangOpts.getGCMode();
137    return true;
138  }
139  PARSE_LANGOPT_BENIGN(getVisibilityMode());
140  PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
141                          diag::warn_pch_stack_protector);
142  PARSE_LANGOPT_BENIGN(InstantiationDepth);
143  PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
144  PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda);
145  PARSE_LANGOPT_BENIGN(CatchUndefined);
146  PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
147  PARSE_LANGOPT_BENIGN(SpellChecking);
148  PARSE_LANGOPT_BENIGN(DefaultFPContract);
149#undef PARSE_LANGOPT_IMPORTANT
150#undef PARSE_LANGOPT_BENIGN
151
152  return false;
153}
154
155bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
156  if (Triple == PP.getTargetInfo().getTriple().str())
157    return false;
158
159  Reader.Diag(diag::warn_pch_target_triple)
160    << Triple << PP.getTargetInfo().getTriple().str();
161  return true;
162}
163
164namespace {
165  struct EmptyStringRef {
166    bool operator ()(llvm::StringRef r) const { return r.empty(); }
167  };
168  struct EmptyBlock {
169    bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
170  };
171}
172
173static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
174                                PCHPredefinesBlocks R) {
175  // First, sum up the lengths.
176  unsigned LL = 0, RL = 0;
177  for (unsigned I = 0, N = L.size(); I != N; ++I) {
178    LL += L[I].size();
179  }
180  for (unsigned I = 0, N = R.size(); I != N; ++I) {
181    RL += R[I].Data.size();
182  }
183  if (LL != RL)
184    return false;
185  if (LL == 0 && RL == 0)
186    return true;
187
188  // Kick out empty parts, they confuse the algorithm below.
189  L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
190  R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
191
192  // Do it the hard way. At this point, both vectors must be non-empty.
193  llvm::StringRef LR = L[0], RR = R[0].Data;
194  unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
195  (void) RN;
196  for (;;) {
197    // Compare the current pieces.
198    if (LR.size() == RR.size()) {
199      // If they're the same length, it's pretty easy.
200      if (LR != RR)
201        return false;
202      // Both pieces are done, advance.
203      ++LI;
204      ++RI;
205      // If either string is done, they're both done, since they're the same
206      // length.
207      if (LI == LN) {
208        assert(RI == RN && "Strings not the same length after all?");
209        return true;
210      }
211      LR = L[LI];
212      RR = R[RI].Data;
213    } else if (LR.size() < RR.size()) {
214      // Right piece is longer.
215      if (!RR.startswith(LR))
216        return false;
217      ++LI;
218      assert(LI != LN && "Strings not the same length after all?");
219      RR = RR.substr(LR.size());
220      LR = L[LI];
221    } else {
222      // Left piece is longer.
223      if (!LR.startswith(RR))
224        return false;
225      ++RI;
226      assert(RI != RN && "Strings not the same length after all?");
227      LR = LR.substr(RR.size());
228      RR = R[RI].Data;
229    }
230  }
231}
232
233static std::pair<FileID, llvm::StringRef::size_type>
234FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
235  std::pair<FileID, llvm::StringRef::size_type> Res;
236  for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
237    Res.second = Buffers[I].Data.find(MacroDef);
238    if (Res.second != llvm::StringRef::npos) {
239      Res.first = Buffers[I].BufferID;
240      break;
241    }
242  }
243  return Res;
244}
245
246bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
247                                        llvm::StringRef OriginalFileName,
248                                        std::string &SuggestedPredefines,
249                                        FileManager &FileMgr) {
250  // We are in the context of an implicit include, so the predefines buffer will
251  // have a #include entry for the PCH file itself (as normalized by the
252  // preprocessor initialization). Find it and skip over it in the checking
253  // below.
254  llvm::SmallString<256> PCHInclude;
255  PCHInclude += "#include \"";
256  PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
257  PCHInclude += "\"\n";
258  std::pair<llvm::StringRef,llvm::StringRef> Split =
259    llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
260  llvm::StringRef Left =  Split.first, Right = Split.second;
261  if (Left == PP.getPredefines()) {
262    Error("Missing PCH include entry!");
263    return true;
264  }
265
266  // If the concatenation of all the PCH buffers is equal to the adjusted
267  // command line, we're done.
268  llvm::SmallVector<llvm::StringRef, 2> CommandLine;
269  CommandLine.push_back(Left);
270  CommandLine.push_back(Right);
271  if (EqualConcatenations(CommandLine, Buffers))
272    return false;
273
274  SourceManager &SourceMgr = PP.getSourceManager();
275
276  // The predefines buffers are different. Determine what the differences are,
277  // and whether they require us to reject the PCH file.
278  llvm::SmallVector<llvm::StringRef, 8> PCHLines;
279  for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
280    Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
281
282  llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
283  Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
284
285  // Pick out implicit #includes after the PCH and don't consider them for
286  // validation; we will insert them into SuggestedPredefines so that the
287  // preprocessor includes them.
288  std::string IncludesAfterPCH;
289  llvm::SmallVector<llvm::StringRef, 8> AfterPCHLines;
290  Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
291  for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
292    if (AfterPCHLines[i].startswith("#include ")) {
293      IncludesAfterPCH += AfterPCHLines[i];
294      IncludesAfterPCH += '\n';
295    } else {
296      CmdLineLines.push_back(AfterPCHLines[i]);
297    }
298  }
299
300  // Make sure we add the includes last into SuggestedPredefines before we
301  // exit this function.
302  struct AddIncludesRAII {
303    std::string &SuggestedPredefines;
304    std::string &IncludesAfterPCH;
305
306    AddIncludesRAII(std::string &SuggestedPredefines,
307                    std::string &IncludesAfterPCH)
308      : SuggestedPredefines(SuggestedPredefines),
309        IncludesAfterPCH(IncludesAfterPCH) { }
310    ~AddIncludesRAII() {
311      SuggestedPredefines += IncludesAfterPCH;
312    }
313  } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
314
315  // Sort both sets of predefined buffer lines, since we allow some extra
316  // definitions and they may appear at any point in the output.
317  std::sort(CmdLineLines.begin(), CmdLineLines.end());
318  std::sort(PCHLines.begin(), PCHLines.end());
319
320  // Determine which predefines that were used to build the PCH file are missing
321  // from the command line.
322  std::vector<llvm::StringRef> MissingPredefines;
323  std::set_difference(PCHLines.begin(), PCHLines.end(),
324                      CmdLineLines.begin(), CmdLineLines.end(),
325                      std::back_inserter(MissingPredefines));
326
327  bool MissingDefines = false;
328  bool ConflictingDefines = false;
329  for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
330    llvm::StringRef Missing = MissingPredefines[I];
331    if (Missing.startswith("#include ")) {
332      // An -include was specified when generating the PCH; it is included in
333      // the PCH, just ignore it.
334      continue;
335    }
336    if (!Missing.startswith("#define ")) {
337      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
338      return true;
339    }
340
341    // This is a macro definition. Determine the name of the macro we're
342    // defining.
343    std::string::size_type StartOfMacroName = strlen("#define ");
344    std::string::size_type EndOfMacroName
345      = Missing.find_first_of("( \n\r", StartOfMacroName);
346    assert(EndOfMacroName != std::string::npos &&
347           "Couldn't find the end of the macro name");
348    llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
349
350    // Determine whether this macro was given a different definition on the
351    // command line.
352    std::string MacroDefStart = "#define " + MacroName.str();
353    std::string::size_type MacroDefLen = MacroDefStart.size();
354    llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
355      = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
356                         MacroDefStart);
357    for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
358      if (!ConflictPos->startswith(MacroDefStart)) {
359        // Different macro; we're done.
360        ConflictPos = CmdLineLines.end();
361        break;
362      }
363
364      assert(ConflictPos->size() > MacroDefLen &&
365             "Invalid #define in predefines buffer?");
366      if ((*ConflictPos)[MacroDefLen] != ' ' &&
367          (*ConflictPos)[MacroDefLen] != '(')
368        continue; // Longer macro name; keep trying.
369
370      // We found a conflicting macro definition.
371      break;
372    }
373
374    if (ConflictPos != CmdLineLines.end()) {
375      Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
376          << MacroName;
377
378      // Show the definition of this macro within the PCH file.
379      std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
380          FindMacro(Buffers, Missing);
381      assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
382      SourceLocation PCHMissingLoc =
383          SourceMgr.getLocForStartOfFile(MacroLoc.first)
384            .getFileLocWithOffset(MacroLoc.second);
385      Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
386
387      ConflictingDefines = true;
388      continue;
389    }
390
391    // If the macro doesn't conflict, then we'll just pick up the macro
392    // definition from the PCH file. Warn the user that they made a mistake.
393    if (ConflictingDefines)
394      continue; // Don't complain if there are already conflicting defs
395
396    if (!MissingDefines) {
397      Reader.Diag(diag::warn_cmdline_missing_macro_defs);
398      MissingDefines = true;
399    }
400
401    // Show the definition of this macro within the PCH file.
402    std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
403        FindMacro(Buffers, Missing);
404    assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
405    SourceLocation PCHMissingLoc =
406        SourceMgr.getLocForStartOfFile(MacroLoc.first)
407          .getFileLocWithOffset(MacroLoc.second);
408    Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
409  }
410
411  if (ConflictingDefines)
412    return true;
413
414  // Determine what predefines were introduced based on command-line
415  // parameters that were not present when building the PCH
416  // file. Extra #defines are okay, so long as the identifiers being
417  // defined were not used within the precompiled header.
418  std::vector<llvm::StringRef> ExtraPredefines;
419  std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
420                      PCHLines.begin(), PCHLines.end(),
421                      std::back_inserter(ExtraPredefines));
422  for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
423    llvm::StringRef &Extra = ExtraPredefines[I];
424    if (!Extra.startswith("#define ")) {
425      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
426      return true;
427    }
428
429    // This is an extra macro definition. Determine the name of the
430    // macro we're defining.
431    std::string::size_type StartOfMacroName = strlen("#define ");
432    std::string::size_type EndOfMacroName
433      = Extra.find_first_of("( \n\r", StartOfMacroName);
434    assert(EndOfMacroName != std::string::npos &&
435           "Couldn't find the end of the macro name");
436    llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
437
438    // Check whether this name was used somewhere in the PCH file. If
439    // so, defining it as a macro could change behavior, so we reject
440    // the PCH file.
441    if (IdentifierInfo *II = Reader.get(MacroName)) {
442      Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
443      return true;
444    }
445
446    // Add this definition to the suggested predefines buffer.
447    SuggestedPredefines += Extra;
448    SuggestedPredefines += '\n';
449  }
450
451  // If we get here, it's because the predefines buffer had compatible
452  // contents. Accept the PCH file.
453  return false;
454}
455
456void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
457                                      unsigned ID) {
458  PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
459  ++NumHeaderInfos;
460}
461
462void PCHValidator::ReadCounter(unsigned Value) {
463  PP.setCounterValue(Value);
464}
465
466//===----------------------------------------------------------------------===//
467// AST reader implementation
468//===----------------------------------------------------------------------===//
469
470void
471ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
472  DeserializationListener = Listener;
473}
474
475
476namespace {
477class ASTSelectorLookupTrait {
478  ASTReader &Reader;
479
480public:
481  struct data_type {
482    SelectorID ID;
483    ObjCMethodList Instance, Factory;
484  };
485
486  typedef Selector external_key_type;
487  typedef external_key_type internal_key_type;
488
489  explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { }
490
491  static bool EqualKey(const internal_key_type& a,
492                       const internal_key_type& b) {
493    return a == b;
494  }
495
496  static unsigned ComputeHash(Selector Sel) {
497    return serialization::ComputeHash(Sel);
498  }
499
500  // This hopefully will just get inlined and removed by the optimizer.
501  static const internal_key_type&
502  GetInternalKey(const external_key_type& x) { return x; }
503
504  static std::pair<unsigned, unsigned>
505  ReadKeyDataLength(const unsigned char*& d) {
506    using namespace clang::io;
507    unsigned KeyLen = ReadUnalignedLE16(d);
508    unsigned DataLen = ReadUnalignedLE16(d);
509    return std::make_pair(KeyLen, DataLen);
510  }
511
512  internal_key_type ReadKey(const unsigned char* d, unsigned) {
513    using namespace clang::io;
514    SelectorTable &SelTable = Reader.getContext()->Selectors;
515    unsigned N = ReadUnalignedLE16(d);
516    IdentifierInfo *FirstII
517      = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
518    if (N == 0)
519      return SelTable.getNullarySelector(FirstII);
520    else if (N == 1)
521      return SelTable.getUnarySelector(FirstII);
522
523    llvm::SmallVector<IdentifierInfo *, 16> Args;
524    Args.push_back(FirstII);
525    for (unsigned I = 1; I != N; ++I)
526      Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
527
528    return SelTable.getSelector(N, Args.data());
529  }
530
531  data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
532    using namespace clang::io;
533
534    data_type Result;
535
536    Result.ID = ReadUnalignedLE32(d);
537    unsigned NumInstanceMethods = ReadUnalignedLE16(d);
538    unsigned NumFactoryMethods = ReadUnalignedLE16(d);
539
540    // Load instance methods
541    ObjCMethodList *Prev = 0;
542    for (unsigned I = 0; I != NumInstanceMethods; ++I) {
543      ObjCMethodDecl *Method
544        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
545      if (!Result.Instance.Method) {
546        // This is the first method, which is the easy case.
547        Result.Instance.Method = Method;
548        Prev = &Result.Instance;
549        continue;
550      }
551
552      ObjCMethodList *Mem =
553        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
554      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
555      Prev = Prev->Next;
556    }
557
558    // Load factory methods
559    Prev = 0;
560    for (unsigned I = 0; I != NumFactoryMethods; ++I) {
561      ObjCMethodDecl *Method
562        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
563      if (!Result.Factory.Method) {
564        // This is the first method, which is the easy case.
565        Result.Factory.Method = Method;
566        Prev = &Result.Factory;
567        continue;
568      }
569
570      ObjCMethodList *Mem =
571        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
572      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
573      Prev = Prev->Next;
574    }
575
576    return Result;
577  }
578};
579
580} // end anonymous namespace
581
582/// \brief The on-disk hash table used for the global method pool.
583typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
584  ASTSelectorLookupTable;
585
586namespace clang {
587class ASTIdentifierLookupTrait {
588  ASTReader &Reader;
589  ASTReader::PerFileData &F;
590
591  // If we know the IdentifierInfo in advance, it is here and we will
592  // not build a new one. Used when deserializing information about an
593  // identifier that was constructed before the AST file was read.
594  IdentifierInfo *KnownII;
595
596public:
597  typedef IdentifierInfo * data_type;
598
599  typedef const std::pair<const char*, unsigned> external_key_type;
600
601  typedef external_key_type internal_key_type;
602
603  ASTIdentifierLookupTrait(ASTReader &Reader, ASTReader::PerFileData &F,
604                           IdentifierInfo *II = 0)
605    : Reader(Reader), F(F), KnownII(II) { }
606
607  static bool EqualKey(const internal_key_type& a,
608                       const internal_key_type& b) {
609    return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
610                                  : false;
611  }
612
613  static unsigned ComputeHash(const internal_key_type& a) {
614    return llvm::HashString(llvm::StringRef(a.first, a.second));
615  }
616
617  // This hopefully will just get inlined and removed by the optimizer.
618  static const internal_key_type&
619  GetInternalKey(const external_key_type& x) { return x; }
620
621  // This hopefully will just get inlined and removed by the optimizer.
622  static const external_key_type&
623  GetExternalKey(const internal_key_type& x) { return x; }
624
625  static std::pair<unsigned, unsigned>
626  ReadKeyDataLength(const unsigned char*& d) {
627    using namespace clang::io;
628    unsigned DataLen = ReadUnalignedLE16(d);
629    unsigned KeyLen = ReadUnalignedLE16(d);
630    return std::make_pair(KeyLen, DataLen);
631  }
632
633  static std::pair<const char*, unsigned>
634  ReadKey(const unsigned char* d, unsigned n) {
635    assert(n >= 2 && d[n-1] == '\0');
636    return std::make_pair((const char*) d, n-1);
637  }
638
639  IdentifierInfo *ReadData(const internal_key_type& k,
640                           const unsigned char* d,
641                           unsigned DataLen) {
642    using namespace clang::io;
643    IdentID ID = ReadUnalignedLE32(d);
644    bool IsInteresting = ID & 0x01;
645
646    // Wipe out the "is interesting" bit.
647    ID = ID >> 1;
648
649    if (!IsInteresting) {
650      // For uninteresting identifiers, just build the IdentifierInfo
651      // and associate it with the persistent ID.
652      IdentifierInfo *II = KnownII;
653      if (!II)
654        II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
655      Reader.SetIdentifierInfo(ID, II);
656      II->setIsFromAST();
657      return II;
658    }
659
660    unsigned Bits = ReadUnalignedLE16(d);
661    bool CPlusPlusOperatorKeyword = Bits & 0x01;
662    Bits >>= 1;
663    bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
664    Bits >>= 1;
665    bool Poisoned = Bits & 0x01;
666    Bits >>= 1;
667    bool ExtensionToken = Bits & 0x01;
668    Bits >>= 1;
669    bool hasMacroDefinition = Bits & 0x01;
670    Bits >>= 1;
671    unsigned ObjCOrBuiltinID = Bits & 0x3FF;
672    Bits >>= 10;
673
674    assert(Bits == 0 && "Extra bits in the identifier?");
675    DataLen -= 6;
676
677    // Build the IdentifierInfo itself and link the identifier ID with
678    // the new IdentifierInfo.
679    IdentifierInfo *II = KnownII;
680    if (!II)
681      II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
682    Reader.SetIdentifierInfo(ID, II);
683
684    // Set or check the various bits in the IdentifierInfo structure.
685    // Token IDs are read-only.
686    if (HasRevertedTokenIDToIdentifier)
687      II->RevertTokenIDToIdentifier();
688    II->setObjCOrBuiltinID(ObjCOrBuiltinID);
689    assert(II->isExtensionToken() == ExtensionToken &&
690           "Incorrect extension token flag");
691    (void)ExtensionToken;
692    II->setIsPoisoned(Poisoned);
693    assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
694           "Incorrect C++ operator keyword flag");
695    (void)CPlusPlusOperatorKeyword;
696
697    // If this identifier is a macro, deserialize the macro
698    // definition.
699    if (hasMacroDefinition) {
700      uint32_t Offset = ReadUnalignedLE32(d);
701      Reader.SetIdentifierIsMacro(II, F, Offset);
702      DataLen -= 4;
703    }
704
705    // Read all of the declarations visible at global scope with this
706    // name.
707    if (Reader.getContext() == 0) return II;
708    if (DataLen > 0) {
709      llvm::SmallVector<uint32_t, 4> DeclIDs;
710      for (; DataLen > 0; DataLen -= 4)
711        DeclIDs.push_back(ReadUnalignedLE32(d));
712      Reader.SetGloballyVisibleDecls(II, DeclIDs);
713    }
714
715    II->setIsFromAST();
716    return II;
717  }
718};
719
720} // end anonymous namespace
721
722/// \brief The on-disk hash table used to contain information about
723/// all of the identifiers in the program.
724typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
725  ASTIdentifierLookupTable;
726
727namespace {
728class ASTDeclContextNameLookupTrait {
729  ASTReader &Reader;
730
731public:
732  /// \brief Pair of begin/end iterators for DeclIDs.
733  typedef std::pair<DeclID *, DeclID *> data_type;
734
735  /// \brief Special internal key for declaration names.
736  /// The hash table creates keys for comparison; we do not create
737  /// a DeclarationName for the internal key to avoid deserializing types.
738  struct DeclNameKey {
739    DeclarationName::NameKind Kind;
740    uint64_t Data;
741    DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { }
742  };
743
744  typedef DeclarationName external_key_type;
745  typedef DeclNameKey internal_key_type;
746
747  explicit ASTDeclContextNameLookupTrait(ASTReader &Reader) : Reader(Reader) { }
748
749  static bool EqualKey(const internal_key_type& a,
750                       const internal_key_type& b) {
751    return a.Kind == b.Kind && a.Data == b.Data;
752  }
753
754  unsigned ComputeHash(const DeclNameKey &Key) const {
755    llvm::FoldingSetNodeID ID;
756    ID.AddInteger(Key.Kind);
757
758    switch (Key.Kind) {
759    case DeclarationName::Identifier:
760    case DeclarationName::CXXLiteralOperatorName:
761      ID.AddString(((IdentifierInfo*)Key.Data)->getName());
762      break;
763    case DeclarationName::ObjCZeroArgSelector:
764    case DeclarationName::ObjCOneArgSelector:
765    case DeclarationName::ObjCMultiArgSelector:
766      ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
767      break;
768    case DeclarationName::CXXConstructorName:
769    case DeclarationName::CXXDestructorName:
770    case DeclarationName::CXXConversionFunctionName:
771      ID.AddInteger((TypeID)Key.Data);
772      break;
773    case DeclarationName::CXXOperatorName:
774      ID.AddInteger((OverloadedOperatorKind)Key.Data);
775      break;
776    case DeclarationName::CXXUsingDirective:
777      break;
778    }
779
780    return ID.ComputeHash();
781  }
782
783  internal_key_type GetInternalKey(const external_key_type& Name) const {
784    DeclNameKey Key;
785    Key.Kind = Name.getNameKind();
786    switch (Name.getNameKind()) {
787    case DeclarationName::Identifier:
788      Key.Data = (uint64_t)Name.getAsIdentifierInfo();
789      break;
790    case DeclarationName::ObjCZeroArgSelector:
791    case DeclarationName::ObjCOneArgSelector:
792    case DeclarationName::ObjCMultiArgSelector:
793      Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
794      break;
795    case DeclarationName::CXXConstructorName:
796    case DeclarationName::CXXDestructorName:
797    case DeclarationName::CXXConversionFunctionName:
798      Key.Data = Reader.GetTypeID(Name.getCXXNameType());
799      break;
800    case DeclarationName::CXXOperatorName:
801      Key.Data = Name.getCXXOverloadedOperator();
802      break;
803    case DeclarationName::CXXLiteralOperatorName:
804      Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
805      break;
806    case DeclarationName::CXXUsingDirective:
807      break;
808    }
809
810    return Key;
811  }
812
813  external_key_type GetExternalKey(const internal_key_type& Key) const {
814    ASTContext *Context = Reader.getContext();
815    switch (Key.Kind) {
816    case DeclarationName::Identifier:
817      return DeclarationName((IdentifierInfo*)Key.Data);
818
819    case DeclarationName::ObjCZeroArgSelector:
820    case DeclarationName::ObjCOneArgSelector:
821    case DeclarationName::ObjCMultiArgSelector:
822      return DeclarationName(Selector(Key.Data));
823
824    case DeclarationName::CXXConstructorName:
825      return Context->DeclarationNames.getCXXConstructorName(
826                           Context->getCanonicalType(Reader.GetType(Key.Data)));
827
828    case DeclarationName::CXXDestructorName:
829      return Context->DeclarationNames.getCXXDestructorName(
830                           Context->getCanonicalType(Reader.GetType(Key.Data)));
831
832    case DeclarationName::CXXConversionFunctionName:
833      return Context->DeclarationNames.getCXXConversionFunctionName(
834                           Context->getCanonicalType(Reader.GetType(Key.Data)));
835
836    case DeclarationName::CXXOperatorName:
837      return Context->DeclarationNames.getCXXOperatorName(
838                                         (OverloadedOperatorKind)Key.Data);
839
840    case DeclarationName::CXXLiteralOperatorName:
841      return Context->DeclarationNames.getCXXLiteralOperatorName(
842                                                     (IdentifierInfo*)Key.Data);
843
844    case DeclarationName::CXXUsingDirective:
845      return DeclarationName::getUsingDirectiveName();
846    }
847
848    llvm_unreachable("Invalid Name Kind ?");
849  }
850
851  static std::pair<unsigned, unsigned>
852  ReadKeyDataLength(const unsigned char*& d) {
853    using namespace clang::io;
854    unsigned KeyLen = ReadUnalignedLE16(d);
855    unsigned DataLen = ReadUnalignedLE16(d);
856    return std::make_pair(KeyLen, DataLen);
857  }
858
859  internal_key_type ReadKey(const unsigned char* d, unsigned) {
860    using namespace clang::io;
861
862    DeclNameKey Key;
863    Key.Kind = (DeclarationName::NameKind)*d++;
864    switch (Key.Kind) {
865    case DeclarationName::Identifier:
866      Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
867      break;
868    case DeclarationName::ObjCZeroArgSelector:
869    case DeclarationName::ObjCOneArgSelector:
870    case DeclarationName::ObjCMultiArgSelector:
871      Key.Data =
872         (uint64_t)Reader.DecodeSelector(ReadUnalignedLE32(d)).getAsOpaquePtr();
873      break;
874    case DeclarationName::CXXConstructorName:
875    case DeclarationName::CXXDestructorName:
876    case DeclarationName::CXXConversionFunctionName:
877      Key.Data = ReadUnalignedLE32(d); // TypeID
878      break;
879    case DeclarationName::CXXOperatorName:
880      Key.Data = *d++; // OverloadedOperatorKind
881      break;
882    case DeclarationName::CXXLiteralOperatorName:
883      Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
884      break;
885    case DeclarationName::CXXUsingDirective:
886      break;
887    }
888
889    return Key;
890  }
891
892  data_type ReadData(internal_key_type, const unsigned char* d,
893                     unsigned DataLen) {
894    using namespace clang::io;
895    unsigned NumDecls = ReadUnalignedLE16(d);
896    DeclID *Start = (DeclID *)d;
897    return std::make_pair(Start, Start + NumDecls);
898  }
899};
900
901} // end anonymous namespace
902
903/// \brief The on-disk hash table used for the DeclContext's Name lookup table.
904typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
905  ASTDeclContextNameLookupTable;
906
907bool ASTReader::ReadDeclContextStorage(llvm::BitstreamCursor &Cursor,
908                                   const std::pair<uint64_t, uint64_t> &Offsets,
909                                       DeclContextInfo &Info) {
910  SavedStreamPosition SavedPosition(Cursor);
911  // First the lexical decls.
912  if (Offsets.first != 0) {
913    Cursor.JumpToBit(Offsets.first);
914
915    RecordData Record;
916    const char *Blob;
917    unsigned BlobLen;
918    unsigned Code = Cursor.ReadCode();
919    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
920    if (RecCode != DECL_CONTEXT_LEXICAL) {
921      Error("Expected lexical block");
922      return true;
923    }
924
925    Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
926    Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
927  } else {
928    Info.LexicalDecls = 0;
929    Info.NumLexicalDecls = 0;
930  }
931
932  // Now the lookup table.
933  if (Offsets.second != 0) {
934    Cursor.JumpToBit(Offsets.second);
935
936    RecordData Record;
937    const char *Blob;
938    unsigned BlobLen;
939    unsigned Code = Cursor.ReadCode();
940    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
941    if (RecCode != DECL_CONTEXT_VISIBLE) {
942      Error("Expected visible lookup table block");
943      return true;
944    }
945    Info.NameLookupTableData
946      = ASTDeclContextNameLookupTable::Create(
947                    (const unsigned char *)Blob + Record[0],
948                    (const unsigned char *)Blob,
949                    ASTDeclContextNameLookupTrait(*this));
950  } else {
951    Info.NameLookupTableData = 0;
952  }
953
954  return false;
955}
956
957void ASTReader::Error(const char *Msg) {
958  Diag(diag::err_fe_pch_malformed) << Msg;
959}
960
961/// \brief Tell the AST listener about the predefines buffers in the chain.
962bool ASTReader::CheckPredefinesBuffers() {
963  if (Listener)
964    return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
965                                          ActualOriginalFileName,
966                                          SuggestedPredefines,
967                                          FileMgr);
968  return false;
969}
970
971//===----------------------------------------------------------------------===//
972// Source Manager Deserialization
973//===----------------------------------------------------------------------===//
974
975/// \brief Read the line table in the source manager block.
976/// \returns true if there was an error.
977bool ASTReader::ParseLineTable(PerFileData &F,
978                               llvm::SmallVectorImpl<uint64_t> &Record) {
979  unsigned Idx = 0;
980  LineTableInfo &LineTable = SourceMgr.getLineTable();
981
982  // Parse the file names
983  std::map<int, int> FileIDs;
984  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
985    // Extract the file name
986    unsigned FilenameLen = Record[Idx++];
987    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
988    Idx += FilenameLen;
989    MaybeAddSystemRootToFilename(Filename);
990    FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
991                                                  Filename.size());
992  }
993
994  // Parse the line entries
995  std::vector<LineEntry> Entries;
996  while (Idx < Record.size()) {
997    int FID = Record[Idx++];
998
999    // Extract the line entries
1000    unsigned NumEntries = Record[Idx++];
1001    assert(NumEntries && "Numentries is 00000");
1002    Entries.clear();
1003    Entries.reserve(NumEntries);
1004    for (unsigned I = 0; I != NumEntries; ++I) {
1005      unsigned FileOffset = Record[Idx++];
1006      unsigned LineNo = Record[Idx++];
1007      int FilenameID = FileIDs[Record[Idx++]];
1008      SrcMgr::CharacteristicKind FileKind
1009        = (SrcMgr::CharacteristicKind)Record[Idx++];
1010      unsigned IncludeOffset = Record[Idx++];
1011      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1012                                       FileKind, IncludeOffset));
1013    }
1014    LineTable.AddEntry(FID, Entries);
1015  }
1016
1017  return false;
1018}
1019
1020namespace {
1021
1022class ASTStatData {
1023public:
1024  const ino_t ino;
1025  const dev_t dev;
1026  const mode_t mode;
1027  const time_t mtime;
1028  const off_t size;
1029
1030  ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
1031    : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
1032};
1033
1034class ASTStatLookupTrait {
1035 public:
1036  typedef const char *external_key_type;
1037  typedef const char *internal_key_type;
1038
1039  typedef ASTStatData data_type;
1040
1041  static unsigned ComputeHash(const char *path) {
1042    return llvm::HashString(path);
1043  }
1044
1045  static internal_key_type GetInternalKey(const char *path) { return path; }
1046
1047  static bool EqualKey(internal_key_type a, internal_key_type b) {
1048    return strcmp(a, b) == 0;
1049  }
1050
1051  static std::pair<unsigned, unsigned>
1052  ReadKeyDataLength(const unsigned char*& d) {
1053    unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1054    unsigned DataLen = (unsigned) *d++;
1055    return std::make_pair(KeyLen + 1, DataLen);
1056  }
1057
1058  static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1059    return (const char *)d;
1060  }
1061
1062  static data_type ReadData(const internal_key_type, const unsigned char *d,
1063                            unsigned /*DataLen*/) {
1064    using namespace clang::io;
1065
1066    ino_t ino = (ino_t) ReadUnalignedLE32(d);
1067    dev_t dev = (dev_t) ReadUnalignedLE32(d);
1068    mode_t mode = (mode_t) ReadUnalignedLE16(d);
1069    time_t mtime = (time_t) ReadUnalignedLE64(d);
1070    off_t size = (off_t) ReadUnalignedLE64(d);
1071    return data_type(ino, dev, mode, mtime, size);
1072  }
1073};
1074
1075/// \brief stat() cache for precompiled headers.
1076///
1077/// This cache is very similar to the stat cache used by pretokenized
1078/// headers.
1079class ASTStatCache : public FileSystemStatCache {
1080  typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
1081  CacheTy *Cache;
1082
1083  unsigned &NumStatHits, &NumStatMisses;
1084public:
1085  ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1086               unsigned &NumStatHits, unsigned &NumStatMisses)
1087    : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1088    Cache = CacheTy::Create(Buckets, Base);
1089  }
1090
1091  ~ASTStatCache() { delete Cache; }
1092
1093  LookupResult getStat(const char *Path, struct stat &StatBuf,
1094                       int *FileDescriptor) {
1095    // Do the lookup for the file's data in the AST file.
1096    CacheTy::iterator I = Cache->find(Path);
1097
1098    // If we don't get a hit in the AST file just forward to 'stat'.
1099    if (I == Cache->end()) {
1100      ++NumStatMisses;
1101      return statChained(Path, StatBuf, FileDescriptor);
1102    }
1103
1104    ++NumStatHits;
1105    ASTStatData Data = *I;
1106
1107    StatBuf.st_ino = Data.ino;
1108    StatBuf.st_dev = Data.dev;
1109    StatBuf.st_mtime = Data.mtime;
1110    StatBuf.st_mode = Data.mode;
1111    StatBuf.st_size = Data.size;
1112    return CacheExists;
1113  }
1114};
1115} // end anonymous namespace
1116
1117
1118/// \brief Read a source manager block
1119ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) {
1120  using namespace SrcMgr;
1121
1122  llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1123
1124  // Set the source-location entry cursor to the current position in
1125  // the stream. This cursor will be used to read the contents of the
1126  // source manager block initially, and then lazily read
1127  // source-location entries as needed.
1128  SLocEntryCursor = F.Stream;
1129
1130  // The stream itself is going to skip over the source manager block.
1131  if (F.Stream.SkipBlock()) {
1132    Error("malformed block record in AST file");
1133    return Failure;
1134  }
1135
1136  // Enter the source manager block.
1137  if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1138    Error("malformed source manager block record in AST file");
1139    return Failure;
1140  }
1141
1142  RecordData Record;
1143  while (true) {
1144    unsigned Code = SLocEntryCursor.ReadCode();
1145    if (Code == llvm::bitc::END_BLOCK) {
1146      if (SLocEntryCursor.ReadBlockEnd()) {
1147        Error("error at end of Source Manager block in AST file");
1148        return Failure;
1149      }
1150      return Success;
1151    }
1152
1153    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1154      // No known subblocks, always skip them.
1155      SLocEntryCursor.ReadSubBlockID();
1156      if (SLocEntryCursor.SkipBlock()) {
1157        Error("malformed block record in AST file");
1158        return Failure;
1159      }
1160      continue;
1161    }
1162
1163    if (Code == llvm::bitc::DEFINE_ABBREV) {
1164      SLocEntryCursor.ReadAbbrevRecord();
1165      continue;
1166    }
1167
1168    // Read a record.
1169    const char *BlobStart;
1170    unsigned BlobLen;
1171    Record.clear();
1172    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1173    default:  // Default behavior: ignore.
1174      break;
1175
1176    case SM_LINE_TABLE:
1177      if (ParseLineTable(F, Record))
1178        return Failure;
1179      break;
1180
1181    case SM_SLOC_FILE_ENTRY:
1182    case SM_SLOC_BUFFER_ENTRY:
1183    case SM_SLOC_INSTANTIATION_ENTRY:
1184      // Once we hit one of the source location entries, we're done.
1185      return Success;
1186    }
1187  }
1188}
1189
1190/// \brief If a header file is not found at the path that we expect it to be
1191/// and the PCH file was moved from its original location, try to resolve the
1192/// file by assuming that header+PCH were moved together and the header is in
1193/// the same place relative to the PCH.
1194static std::string
1195resolveFileRelativeToOriginalDir(const std::string &Filename,
1196                                 const std::string &OriginalDir,
1197                                 const std::string &CurrDir) {
1198  assert(OriginalDir != CurrDir &&
1199         "No point trying to resolve the file if the PCH dir didn't change");
1200  using namespace llvm::sys;
1201  llvm::SmallString<128> filePath(Filename);
1202  fs::make_absolute(filePath);
1203  assert(path::is_absolute(OriginalDir));
1204  llvm::SmallString<128> currPCHPath(CurrDir);
1205
1206  path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1207                       fileDirE = path::end(path::parent_path(filePath));
1208  path::const_iterator origDirI = path::begin(OriginalDir),
1209                       origDirE = path::end(OriginalDir);
1210  // Skip the common path components from filePath and OriginalDir.
1211  while (fileDirI != fileDirE && origDirI != origDirE &&
1212         *fileDirI == *origDirI) {
1213    ++fileDirI;
1214    ++origDirI;
1215  }
1216  for (; origDirI != origDirE; ++origDirI)
1217    path::append(currPCHPath, "..");
1218  path::append(currPCHPath, fileDirI, fileDirE);
1219  path::append(currPCHPath, path::filename(Filename));
1220  return currPCHPath.str();
1221}
1222
1223/// \brief Get a cursor that's correctly positioned for reading the source
1224/// location entry with the given ID.
1225ASTReader::PerFileData *ASTReader::SLocCursorForID(unsigned ID) {
1226  assert(ID != 0 && ID <= TotalNumSLocEntries &&
1227         "SLocCursorForID should only be called for real IDs.");
1228
1229  ID -= 1;
1230  PerFileData *F = 0;
1231  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1232    F = Chain[N - I - 1];
1233    if (ID < F->LocalNumSLocEntries)
1234      break;
1235    ID -= F->LocalNumSLocEntries;
1236  }
1237  assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
1238
1239  F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
1240  return F;
1241}
1242
1243/// \brief Read in the source location entry with the given ID.
1244ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(unsigned ID) {
1245  if (ID == 0)
1246    return Success;
1247
1248  if (ID > TotalNumSLocEntries) {
1249    Error("source location entry ID out-of-range for AST file");
1250    return Failure;
1251  }
1252
1253  PerFileData *F = SLocCursorForID(ID);
1254  llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1255
1256  ++NumSLocEntriesRead;
1257  unsigned Code = SLocEntryCursor.ReadCode();
1258  if (Code == llvm::bitc::END_BLOCK ||
1259      Code == llvm::bitc::ENTER_SUBBLOCK ||
1260      Code == llvm::bitc::DEFINE_ABBREV) {
1261    Error("incorrectly-formatted source location entry in AST file");
1262    return Failure;
1263  }
1264
1265  RecordData Record;
1266  const char *BlobStart;
1267  unsigned BlobLen;
1268  switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1269  default:
1270    Error("incorrectly-formatted source location entry in AST file");
1271    return Failure;
1272
1273  case SM_SLOC_FILE_ENTRY: {
1274    std::string Filename(BlobStart, BlobStart + BlobLen);
1275    MaybeAddSystemRootToFilename(Filename);
1276    const FileEntry *File = FileMgr.getFile(Filename);
1277    if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1278        OriginalDir != CurrentDir) {
1279      std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1280                                                              OriginalDir,
1281                                                              CurrentDir);
1282      if (!resolved.empty())
1283        File = FileMgr.getFile(resolved);
1284    }
1285    if (File == 0)
1286      File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1287                                    (time_t)Record[5]);
1288    if (File == 0) {
1289      std::string ErrorStr = "could not find file '";
1290      ErrorStr += Filename;
1291      ErrorStr += "' referenced by AST file";
1292      Error(ErrorStr.c_str());
1293      return Failure;
1294    }
1295
1296    if (Record.size() < 6) {
1297      Error("source location entry is incorrect");
1298      return Failure;
1299    }
1300
1301    if (!DisableValidation &&
1302        ((off_t)Record[4] != File->getSize()
1303#if !defined(LLVM_ON_WIN32)
1304        // In our regression testing, the Windows file system seems to
1305        // have inconsistent modification times that sometimes
1306        // erroneously trigger this error-handling path.
1307         || (time_t)Record[5] != File->getModificationTime()
1308#endif
1309        )) {
1310      Diag(diag::err_fe_pch_file_modified)
1311        << Filename;
1312      return Failure;
1313    }
1314
1315    FileID FID = SourceMgr.createFileID(File, ReadSourceLocation(*F, Record[1]),
1316                                        (SrcMgr::CharacteristicKind)Record[2],
1317                                        ID, Record[0]);
1318    if (Record[3])
1319      const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1320        .setHasLineDirectives();
1321
1322    break;
1323  }
1324
1325  case SM_SLOC_BUFFER_ENTRY: {
1326    const char *Name = BlobStart;
1327    unsigned Offset = Record[0];
1328    unsigned Code = SLocEntryCursor.ReadCode();
1329    Record.clear();
1330    unsigned RecCode
1331      = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1332
1333    if (RecCode != SM_SLOC_BUFFER_BLOB) {
1334      Error("AST record has invalid code");
1335      return Failure;
1336    }
1337
1338    llvm::MemoryBuffer *Buffer
1339    = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1340                                       Name);
1341    FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
1342
1343    if (strcmp(Name, "<built-in>") == 0) {
1344      PCHPredefinesBlock Block = {
1345        BufferID,
1346        llvm::StringRef(BlobStart, BlobLen - 1)
1347      };
1348      PCHPredefinesBuffers.push_back(Block);
1349    }
1350
1351    break;
1352  }
1353
1354  case SM_SLOC_INSTANTIATION_ENTRY: {
1355    SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1356    SourceMgr.createInstantiationLoc(SpellingLoc,
1357                                     ReadSourceLocation(*F, Record[2]),
1358                                     ReadSourceLocation(*F, Record[3]),
1359                                     Record[4],
1360                                     ID,
1361                                     Record[0]);
1362    break;
1363  }
1364  }
1365
1366  return Success;
1367}
1368
1369/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1370/// specified cursor.  Read the abbreviations that are at the top of the block
1371/// and then leave the cursor pointing into the block.
1372bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1373                                 unsigned BlockID) {
1374  if (Cursor.EnterSubBlock(BlockID)) {
1375    Error("malformed block record in AST file");
1376    return Failure;
1377  }
1378
1379  while (true) {
1380    uint64_t Offset = Cursor.GetCurrentBitNo();
1381    unsigned Code = Cursor.ReadCode();
1382
1383    // We expect all abbrevs to be at the start of the block.
1384    if (Code != llvm::bitc::DEFINE_ABBREV) {
1385      Cursor.JumpToBit(Offset);
1386      return false;
1387    }
1388    Cursor.ReadAbbrevRecord();
1389  }
1390}
1391
1392PreprocessedEntity *ASTReader::ReadMacroRecord(PerFileData &F, uint64_t Offset) {
1393  assert(PP && "Forgot to set Preprocessor ?");
1394  llvm::BitstreamCursor &Stream = F.MacroCursor;
1395
1396  // Keep track of where we are in the stream, then jump back there
1397  // after reading this macro.
1398  SavedStreamPosition SavedPosition(Stream);
1399
1400  Stream.JumpToBit(Offset);
1401  RecordData Record;
1402  llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1403  MacroInfo *Macro = 0;
1404
1405  while (true) {
1406    unsigned Code = Stream.ReadCode();
1407    switch (Code) {
1408    case llvm::bitc::END_BLOCK:
1409      return 0;
1410
1411    case llvm::bitc::ENTER_SUBBLOCK:
1412      // No known subblocks, always skip them.
1413      Stream.ReadSubBlockID();
1414      if (Stream.SkipBlock()) {
1415        Error("malformed block record in AST file");
1416        return 0;
1417      }
1418      continue;
1419
1420    case llvm::bitc::DEFINE_ABBREV:
1421      Stream.ReadAbbrevRecord();
1422      continue;
1423    default: break;
1424    }
1425
1426    // Read a record.
1427    const char *BlobStart = 0;
1428    unsigned BlobLen = 0;
1429    Record.clear();
1430    PreprocessorRecordTypes RecType =
1431      (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1432                                                 BlobLen);
1433    switch (RecType) {
1434    case PP_MACRO_OBJECT_LIKE:
1435    case PP_MACRO_FUNCTION_LIKE: {
1436      // If we already have a macro, that means that we've hit the end
1437      // of the definition of the macro we were looking for. We're
1438      // done.
1439      if (Macro)
1440        return 0;
1441
1442      IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1443      if (II == 0) {
1444        Error("macro must have a name in AST file");
1445        return 0;
1446      }
1447      SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1448      bool isUsed = Record[2];
1449
1450      MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1451      MI->setIsUsed(isUsed);
1452      MI->setIsFromAST();
1453
1454      unsigned NextIndex = 3;
1455      if (RecType == PP_MACRO_FUNCTION_LIKE) {
1456        // Decode function-like macro info.
1457        bool isC99VarArgs = Record[3];
1458        bool isGNUVarArgs = Record[4];
1459        MacroArgs.clear();
1460        unsigned NumArgs = Record[5];
1461        NextIndex = 6 + NumArgs;
1462        for (unsigned i = 0; i != NumArgs; ++i)
1463          MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1464
1465        // Install function-like macro info.
1466        MI->setIsFunctionLike();
1467        if (isC99VarArgs) MI->setIsC99Varargs();
1468        if (isGNUVarArgs) MI->setIsGNUVarargs();
1469        MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1470                            PP->getPreprocessorAllocator());
1471      }
1472
1473      // Finally, install the macro.
1474      PP->setMacroInfo(II, MI);
1475
1476      // Remember that we saw this macro last so that we add the tokens that
1477      // form its body to it.
1478      Macro = MI;
1479
1480      if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1481        // We have a macro definition. Load it now.
1482        PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1483                                        getMacroDefinition(Record[NextIndex]));
1484      }
1485
1486      ++NumMacrosRead;
1487      break;
1488    }
1489
1490    case PP_TOKEN: {
1491      // If we see a TOKEN before a PP_MACRO_*, then the file is
1492      // erroneous, just pretend we didn't see this.
1493      if (Macro == 0) break;
1494
1495      Token Tok;
1496      Tok.startToken();
1497      Tok.setLocation(ReadSourceLocation(F, Record[0]));
1498      Tok.setLength(Record[1]);
1499      if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1500        Tok.setIdentifierInfo(II);
1501      Tok.setKind((tok::TokenKind)Record[3]);
1502      Tok.setFlag((Token::TokenFlags)Record[4]);
1503      Macro->AddTokenToBody(Tok);
1504      break;
1505    }
1506  }
1507  }
1508
1509  return 0;
1510}
1511
1512PreprocessedEntity *ASTReader::LoadPreprocessedEntity(PerFileData &F) {
1513  assert(PP && "Forgot to set Preprocessor ?");
1514  unsigned Code = F.PreprocessorDetailCursor.ReadCode();
1515  switch (Code) {
1516  case llvm::bitc::END_BLOCK:
1517    return 0;
1518
1519  case llvm::bitc::ENTER_SUBBLOCK:
1520    Error("unexpected subblock record in preprocessor detail block");
1521    return 0;
1522
1523  case llvm::bitc::DEFINE_ABBREV:
1524    Error("unexpected abbrevation record in preprocessor detail block");
1525    return 0;
1526
1527  default:
1528    break;
1529  }
1530
1531  if (!PP->getPreprocessingRecord()) {
1532    Error("no preprocessing record");
1533    return 0;
1534  }
1535
1536  // Read the record.
1537  PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1538  const char *BlobStart = 0;
1539  unsigned BlobLen = 0;
1540  RecordData Record;
1541  PreprocessorDetailRecordTypes RecType =
1542    (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord(
1543                                             Code, Record, BlobStart, BlobLen);
1544  switch (RecType) {
1545  case PPD_MACRO_INSTANTIATION: {
1546    if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1547      return PE;
1548
1549    MacroInstantiation *MI
1550      = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1551                                 SourceRange(ReadSourceLocation(F, Record[1]),
1552                                             ReadSourceLocation(F, Record[2])),
1553                                       getMacroDefinition(Record[4]));
1554    PPRec.SetPreallocatedEntity(Record[0], MI);
1555    return MI;
1556  }
1557
1558  case PPD_MACRO_DEFINITION: {
1559    if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1560      return PE;
1561
1562    if (Record[1] > MacroDefinitionsLoaded.size()) {
1563      Error("out-of-bounds macro definition record");
1564      return 0;
1565    }
1566
1567    // Decode the identifier info and then check again; if the macro is
1568    // still defined and associated with the identifier,
1569    IdentifierInfo *II = DecodeIdentifierInfo(Record[4]);
1570    if (!MacroDefinitionsLoaded[Record[1] - 1]) {
1571      MacroDefinition *MD
1572        = new (PPRec) MacroDefinition(II,
1573                                      ReadSourceLocation(F, Record[5]),
1574                                      SourceRange(
1575                                            ReadSourceLocation(F, Record[2]),
1576                                            ReadSourceLocation(F, Record[3])));
1577
1578      PPRec.SetPreallocatedEntity(Record[0], MD);
1579      MacroDefinitionsLoaded[Record[1] - 1] = MD;
1580
1581      if (DeserializationListener)
1582        DeserializationListener->MacroDefinitionRead(Record[1], MD);
1583    }
1584
1585    return MacroDefinitionsLoaded[Record[1] - 1];
1586  }
1587
1588  case PPD_INCLUSION_DIRECTIVE: {
1589    if (PreprocessedEntity *PE = PPRec.getPreprocessedEntity(Record[0]))
1590      return PE;
1591
1592    const char *FullFileNameStart = BlobStart + Record[3];
1593    const FileEntry *File
1594      = PP->getFileManager().getFile(llvm::StringRef(FullFileNameStart,
1595                                                     BlobLen - Record[3]));
1596
1597    // FIXME: Stable encoding
1598    InclusionDirective::InclusionKind Kind
1599      = static_cast<InclusionDirective::InclusionKind>(Record[5]);
1600    InclusionDirective *ID
1601      = new (PPRec) InclusionDirective(PPRec, Kind,
1602                                       llvm::StringRef(BlobStart, Record[3]),
1603                                       Record[4],
1604                                       File,
1605                                 SourceRange(ReadSourceLocation(F, Record[1]),
1606                                             ReadSourceLocation(F, Record[2])));
1607    PPRec.SetPreallocatedEntity(Record[0], ID);
1608    return ID;
1609  }
1610  }
1611
1612  Error("invalid offset in preprocessor detail block");
1613  return 0;
1614}
1615
1616namespace {
1617  /// \brief Trait class used to search the on-disk hash table containing all of
1618  /// the header search information.
1619  ///
1620  /// The on-disk hash table contains a mapping from each header path to
1621  /// information about that header (how many times it has been included, its
1622  /// controlling macro, etc.). Note that we actually hash based on the
1623  /// filename, and support "deep" comparisons of file names based on current
1624  /// inode numbers, so that the search can cope with non-normalized path names
1625  /// and symlinks.
1626  class HeaderFileInfoTrait {
1627    const char *SearchPath;
1628    struct stat SearchPathStatBuf;
1629    llvm::Optional<int> SearchPathStatResult;
1630
1631    int StatSimpleCache(const char *Path, struct stat *StatBuf) {
1632      if (Path == SearchPath) {
1633        if (!SearchPathStatResult)
1634          SearchPathStatResult = stat(Path, &SearchPathStatBuf);
1635
1636        *StatBuf = SearchPathStatBuf;
1637        return *SearchPathStatResult;
1638      }
1639
1640      return stat(Path, StatBuf);
1641    }
1642
1643  public:
1644    typedef const char *external_key_type;
1645    typedef const char *internal_key_type;
1646
1647    typedef HeaderFileInfo data_type;
1648
1649    HeaderFileInfoTrait(const char *SearchPath = 0) : SearchPath(SearchPath) { }
1650
1651    static unsigned ComputeHash(const char *path) {
1652      return llvm::HashString(llvm::sys::path::filename(path));
1653    }
1654
1655    static internal_key_type GetInternalKey(const char *path) { return path; }
1656
1657    bool EqualKey(internal_key_type a, internal_key_type b) {
1658      if (strcmp(a, b) == 0)
1659        return true;
1660
1661      if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1662        return false;
1663
1664      // The file names match, but the path names don't. stat() the files to
1665      // see if they are the same.
1666      struct stat StatBufA, StatBufB;
1667      if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1668        return false;
1669
1670      return StatBufA.st_ino == StatBufB.st_ino;
1671    }
1672
1673    static std::pair<unsigned, unsigned>
1674    ReadKeyDataLength(const unsigned char*& d) {
1675      unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1676      unsigned DataLen = (unsigned) *d++;
1677      return std::make_pair(KeyLen + 1, DataLen);
1678    }
1679
1680    static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1681      return (const char *)d;
1682    }
1683
1684    static data_type ReadData(const internal_key_type, const unsigned char *d,
1685                              unsigned DataLen) {
1686      const unsigned char *End = d + DataLen;
1687      using namespace clang::io;
1688      HeaderFileInfo HFI;
1689      unsigned Flags = *d++;
1690      HFI.isImport = (Flags >> 3) & 0x01;
1691      HFI.DirInfo = (Flags >> 1) & 0x03;
1692      HFI.Resolved = Flags & 0x01;
1693      HFI.NumIncludes = ReadUnalignedLE16(d);
1694      HFI.ControllingMacroID = ReadUnalignedLE32(d);
1695      assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1696      (void)End;
1697
1698      // This HeaderFileInfo was externally loaded.
1699      HFI.External = true;
1700      return HFI;
1701    }
1702  };
1703}
1704
1705/// \brief The on-disk hash table used for the global method pool.
1706typedef OnDiskChainedHashTable<HeaderFileInfoTrait>
1707  HeaderFileInfoLookupTable;
1708
1709void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, PerFileData &F,
1710                                     uint64_t Offset) {
1711  // Note that this identifier has a macro definition.
1712  II->setHasMacroDefinition(true);
1713
1714  // Adjust the offset based on our position in the chain.
1715  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1716    if (Chain[I] == &F)
1717      break;
1718
1719    Offset += Chain[I]->SizeInBits;
1720  }
1721
1722  UnreadMacroRecordOffsets[II] = Offset;
1723}
1724
1725void ASTReader::ReadDefinedMacros() {
1726  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1727    PerFileData &F = *Chain[N - I - 1];
1728    llvm::BitstreamCursor &MacroCursor = F.MacroCursor;
1729
1730    // If there was no preprocessor block, skip this file.
1731    if (!MacroCursor.getBitStreamReader())
1732      continue;
1733
1734    llvm::BitstreamCursor Cursor = MacroCursor;
1735    Cursor.JumpToBit(F.MacroStartOffset);
1736
1737    RecordData Record;
1738    while (true) {
1739      unsigned Code = Cursor.ReadCode();
1740      if (Code == llvm::bitc::END_BLOCK)
1741        break;
1742
1743      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1744        // No known subblocks, always skip them.
1745        Cursor.ReadSubBlockID();
1746        if (Cursor.SkipBlock()) {
1747          Error("malformed block record in AST file");
1748          return;
1749        }
1750        continue;
1751      }
1752
1753      if (Code == llvm::bitc::DEFINE_ABBREV) {
1754        Cursor.ReadAbbrevRecord();
1755        continue;
1756      }
1757
1758      // Read a record.
1759      const char *BlobStart;
1760      unsigned BlobLen;
1761      Record.clear();
1762      switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1763      default:  // Default behavior: ignore.
1764        break;
1765
1766      case PP_MACRO_OBJECT_LIKE:
1767      case PP_MACRO_FUNCTION_LIKE:
1768        DecodeIdentifierInfo(Record[0]);
1769        break;
1770
1771      case PP_TOKEN:
1772        // Ignore tokens.
1773        break;
1774      }
1775    }
1776  }
1777
1778  // Drain the unread macro-record offsets map.
1779  while (!UnreadMacroRecordOffsets.empty())
1780    LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1781}
1782
1783void ASTReader::LoadMacroDefinition(
1784                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1785  assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1786  PerFileData *F = 0;
1787  uint64_t Offset = Pos->second;
1788  UnreadMacroRecordOffsets.erase(Pos);
1789
1790  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1791    if (Offset < Chain[I]->SizeInBits) {
1792      F = Chain[I];
1793      break;
1794    }
1795
1796    Offset -= Chain[I]->SizeInBits;
1797  }
1798  if (!F) {
1799    Error("Malformed macro record offset");
1800    return;
1801  }
1802
1803  ReadMacroRecord(*F, Offset);
1804}
1805
1806void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1807  llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1808    = UnreadMacroRecordOffsets.find(II);
1809  LoadMacroDefinition(Pos);
1810}
1811
1812MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
1813  if (ID == 0 || ID > MacroDefinitionsLoaded.size())
1814    return 0;
1815
1816  if (!MacroDefinitionsLoaded[ID - 1]) {
1817    unsigned Index = ID - 1;
1818    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1819      PerFileData &F = *Chain[N - I - 1];
1820      if (Index < F.LocalNumMacroDefinitions) {
1821        SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
1822        F.PreprocessorDetailCursor.JumpToBit(F.MacroDefinitionOffsets[Index]);
1823        LoadPreprocessedEntity(F);
1824        break;
1825      }
1826      Index -= F.LocalNumMacroDefinitions;
1827    }
1828    assert(MacroDefinitionsLoaded[ID - 1] && "Broken chain");
1829  }
1830
1831  return MacroDefinitionsLoaded[ID - 1];
1832}
1833
1834/// \brief If we are loading a relocatable PCH file, and the filename is
1835/// not an absolute path, add the system root to the beginning of the file
1836/// name.
1837void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1838  // If this is not a relocatable PCH file, there's nothing to do.
1839  if (!RelocatablePCH)
1840    return;
1841
1842  if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1843    return;
1844
1845  if (isysroot == 0) {
1846    // If no system root was given, default to '/'
1847    Filename.insert(Filename.begin(), '/');
1848    return;
1849  }
1850
1851  unsigned Length = strlen(isysroot);
1852  if (isysroot[Length - 1] != '/')
1853    Filename.insert(Filename.begin(), '/');
1854
1855  Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1856}
1857
1858ASTReader::ASTReadResult
1859ASTReader::ReadASTBlock(PerFileData &F) {
1860  llvm::BitstreamCursor &Stream = F.Stream;
1861
1862  if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1863    Error("malformed block record in AST file");
1864    return Failure;
1865  }
1866
1867  // Read all of the records and blocks for the ASt file.
1868  RecordData Record;
1869  bool First = true;
1870  while (!Stream.AtEndOfStream()) {
1871    unsigned Code = Stream.ReadCode();
1872    if (Code == llvm::bitc::END_BLOCK) {
1873      if (Stream.ReadBlockEnd()) {
1874        Error("error at end of module block in AST file");
1875        return Failure;
1876      }
1877
1878      return Success;
1879    }
1880
1881    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1882      switch (Stream.ReadSubBlockID()) {
1883      case DECLTYPES_BLOCK_ID:
1884        // We lazily load the decls block, but we want to set up the
1885        // DeclsCursor cursor to point into it.  Clone our current bitcode
1886        // cursor to it, enter the block and read the abbrevs in that block.
1887        // With the main cursor, we just skip over it.
1888        F.DeclsCursor = Stream;
1889        if (Stream.SkipBlock() ||  // Skip with the main cursor.
1890            // Read the abbrevs.
1891            ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1892          Error("malformed block record in AST file");
1893          return Failure;
1894        }
1895        break;
1896
1897      case DECL_UPDATES_BLOCK_ID:
1898        if (Stream.SkipBlock()) {
1899          Error("malformed block record in AST file");
1900          return Failure;
1901        }
1902        break;
1903
1904      case PREPROCESSOR_BLOCK_ID:
1905        F.MacroCursor = Stream;
1906        if (PP)
1907          PP->setExternalSource(this);
1908
1909        if (Stream.SkipBlock() ||
1910            ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1911          Error("malformed block record in AST file");
1912          return Failure;
1913        }
1914        F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1915        break;
1916
1917      case PREPROCESSOR_DETAIL_BLOCK_ID:
1918        F.PreprocessorDetailCursor = Stream;
1919        if (Stream.SkipBlock() ||
1920            ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1921                             PREPROCESSOR_DETAIL_BLOCK_ID)) {
1922          Error("malformed preprocessor detail record in AST file");
1923          return Failure;
1924        }
1925        F.PreprocessorDetailStartOffset
1926          = F.PreprocessorDetailCursor.GetCurrentBitNo();
1927        break;
1928
1929      case SOURCE_MANAGER_BLOCK_ID:
1930        switch (ReadSourceManagerBlock(F)) {
1931        case Success:
1932          break;
1933
1934        case Failure:
1935          Error("malformed source manager block in AST file");
1936          return Failure;
1937
1938        case IgnorePCH:
1939          return IgnorePCH;
1940        }
1941        break;
1942      }
1943      First = false;
1944      continue;
1945    }
1946
1947    if (Code == llvm::bitc::DEFINE_ABBREV) {
1948      Stream.ReadAbbrevRecord();
1949      continue;
1950    }
1951
1952    // Read and process a record.
1953    Record.clear();
1954    const char *BlobStart = 0;
1955    unsigned BlobLen = 0;
1956    switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1957                                              &BlobStart, &BlobLen)) {
1958    default:  // Default behavior: ignore.
1959      break;
1960
1961    case METADATA: {
1962      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1963        Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1964                                           : diag::warn_pch_version_too_new);
1965        return IgnorePCH;
1966      }
1967
1968      RelocatablePCH = Record[4];
1969      if (Listener) {
1970        std::string TargetTriple(BlobStart, BlobLen);
1971        if (Listener->ReadTargetTriple(TargetTriple))
1972          return IgnorePCH;
1973      }
1974      break;
1975    }
1976
1977    case CHAINED_METADATA: {
1978      if (!First) {
1979        Error("CHAINED_METADATA is not first record in block");
1980        return Failure;
1981      }
1982      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1983        Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1984                                           : diag::warn_pch_version_too_new);
1985        return IgnorePCH;
1986      }
1987
1988      // Load the chained file, which is always a PCH file.
1989      switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen), PCH)) {
1990      case Failure: return Failure;
1991        // If we have to ignore the dependency, we'll have to ignore this too.
1992      case IgnorePCH: return IgnorePCH;
1993      case Success: break;
1994      }
1995      break;
1996    }
1997
1998    case TYPE_OFFSET:
1999      if (F.LocalNumTypes != 0) {
2000        Error("duplicate TYPE_OFFSET record in AST file");
2001        return Failure;
2002      }
2003      F.TypeOffsets = (const uint32_t *)BlobStart;
2004      F.LocalNumTypes = Record[0];
2005      break;
2006
2007    case DECL_OFFSET:
2008      if (F.LocalNumDecls != 0) {
2009        Error("duplicate DECL_OFFSET record in AST file");
2010        return Failure;
2011      }
2012      F.DeclOffsets = (const uint32_t *)BlobStart;
2013      F.LocalNumDecls = Record[0];
2014      break;
2015
2016    case TU_UPDATE_LEXICAL: {
2017      DeclContextInfo Info = {
2018        /* No visible information */ 0,
2019        reinterpret_cast<const KindDeclIDPair *>(BlobStart),
2020        BlobLen / sizeof(KindDeclIDPair)
2021      };
2022      DeclContextOffsets[Context ? Context->getTranslationUnitDecl() : 0]
2023        .push_back(Info);
2024      break;
2025    }
2026
2027    case UPDATE_VISIBLE: {
2028      serialization::DeclID ID = Record[0];
2029      void *Table = ASTDeclContextNameLookupTable::Create(
2030                        (const unsigned char *)BlobStart + Record[1],
2031                        (const unsigned char *)BlobStart,
2032                        ASTDeclContextNameLookupTrait(*this));
2033      if (ID == 1 && Context) { // Is it the TU?
2034        DeclContextInfo Info = {
2035          Table, /* No lexical inforamtion */ 0, 0
2036        };
2037        DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
2038      } else
2039        PendingVisibleUpdates[ID].push_back(Table);
2040      break;
2041    }
2042
2043    case REDECLS_UPDATE_LATEST: {
2044      assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
2045      for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
2046        DeclID First = Record[i], Latest = Record[i+1];
2047        assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
2048                Latest > FirstLatestDeclIDs[First]) &&
2049               "The new latest is supposed to come after the previous latest");
2050        FirstLatestDeclIDs[First] = Latest;
2051      }
2052      break;
2053    }
2054
2055    case LANGUAGE_OPTIONS:
2056      if (ParseLanguageOptions(Record) && !DisableValidation)
2057        return IgnorePCH;
2058      break;
2059
2060    case IDENTIFIER_TABLE:
2061      F.IdentifierTableData = BlobStart;
2062      if (Record[0]) {
2063        F.IdentifierLookupTable
2064          = ASTIdentifierLookupTable::Create(
2065                       (const unsigned char *)F.IdentifierTableData + Record[0],
2066                       (const unsigned char *)F.IdentifierTableData,
2067                       ASTIdentifierLookupTrait(*this, F));
2068        if (PP)
2069          PP->getIdentifierTable().setExternalIdentifierLookup(this);
2070      }
2071      break;
2072
2073    case IDENTIFIER_OFFSET:
2074      if (F.LocalNumIdentifiers != 0) {
2075        Error("duplicate IDENTIFIER_OFFSET record in AST file");
2076        return Failure;
2077      }
2078      F.IdentifierOffsets = (const uint32_t *)BlobStart;
2079      F.LocalNumIdentifiers = Record[0];
2080      break;
2081
2082    case EXTERNAL_DEFINITIONS:
2083      // Optimization for the first block.
2084      if (ExternalDefinitions.empty())
2085        ExternalDefinitions.swap(Record);
2086      else
2087        ExternalDefinitions.insert(ExternalDefinitions.end(),
2088                                   Record.begin(), Record.end());
2089      break;
2090
2091    case SPECIAL_TYPES:
2092      // Optimization for the first block
2093      if (SpecialTypes.empty())
2094        SpecialTypes.swap(Record);
2095      else
2096        SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
2097      break;
2098
2099    case STATISTICS:
2100      TotalNumStatements += Record[0];
2101      TotalNumMacros += Record[1];
2102      TotalLexicalDeclContexts += Record[2];
2103      TotalVisibleDeclContexts += Record[3];
2104      break;
2105
2106    case TENTATIVE_DEFINITIONS:
2107      // Optimization for the first block.
2108      if (TentativeDefinitions.empty())
2109        TentativeDefinitions.swap(Record);
2110      else
2111        TentativeDefinitions.insert(TentativeDefinitions.end(),
2112                                    Record.begin(), Record.end());
2113      break;
2114
2115    case UNUSED_FILESCOPED_DECLS:
2116      // Optimization for the first block.
2117      if (UnusedFileScopedDecls.empty())
2118        UnusedFileScopedDecls.swap(Record);
2119      else
2120        UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(),
2121                                     Record.begin(), Record.end());
2122      break;
2123
2124    case WEAK_UNDECLARED_IDENTIFIERS:
2125      // Later blocks overwrite earlier ones.
2126      WeakUndeclaredIdentifiers.swap(Record);
2127      break;
2128
2129    case LOCALLY_SCOPED_EXTERNAL_DECLS:
2130      // Optimization for the first block.
2131      if (LocallyScopedExternalDecls.empty())
2132        LocallyScopedExternalDecls.swap(Record);
2133      else
2134        LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
2135                                          Record.begin(), Record.end());
2136      break;
2137
2138    case SELECTOR_OFFSETS:
2139      F.SelectorOffsets = (const uint32_t *)BlobStart;
2140      F.LocalNumSelectors = Record[0];
2141      break;
2142
2143    case METHOD_POOL:
2144      F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2145      if (Record[0])
2146        F.SelectorLookupTable
2147          = ASTSelectorLookupTable::Create(
2148                        F.SelectorLookupTableData + Record[0],
2149                        F.SelectorLookupTableData,
2150                        ASTSelectorLookupTrait(*this));
2151      TotalNumMethodPoolEntries += Record[1];
2152      break;
2153
2154    case REFERENCED_SELECTOR_POOL:
2155      F.ReferencedSelectorsData.swap(Record);
2156      break;
2157
2158    case PP_COUNTER_VALUE:
2159      if (!Record.empty() && Listener)
2160        Listener->ReadCounter(Record[0]);
2161      break;
2162
2163    case SOURCE_LOCATION_OFFSETS:
2164      F.SLocOffsets = (const uint32_t *)BlobStart;
2165      F.LocalNumSLocEntries = Record[0];
2166      F.LocalSLocSize = Record[1];
2167      break;
2168
2169    case SOURCE_LOCATION_PRELOADS:
2170      if (PreloadSLocEntries.empty())
2171        PreloadSLocEntries.swap(Record);
2172      else
2173        PreloadSLocEntries.insert(PreloadSLocEntries.end(),
2174            Record.begin(), Record.end());
2175      break;
2176
2177    case STAT_CACHE: {
2178      if (!DisableStatCache) {
2179        ASTStatCache *MyStatCache =
2180          new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2181                           (const unsigned char *)BlobStart,
2182                           NumStatHits, NumStatMisses);
2183        FileMgr.addStatCache(MyStatCache);
2184        F.StatCache = MyStatCache;
2185      }
2186      break;
2187    }
2188
2189    case EXT_VECTOR_DECLS:
2190      // Optimization for the first block.
2191      if (ExtVectorDecls.empty())
2192        ExtVectorDecls.swap(Record);
2193      else
2194        ExtVectorDecls.insert(ExtVectorDecls.end(),
2195                              Record.begin(), Record.end());
2196      break;
2197
2198    case VTABLE_USES:
2199      // Later tables overwrite earlier ones.
2200      VTableUses.swap(Record);
2201      break;
2202
2203    case DYNAMIC_CLASSES:
2204      // Optimization for the first block.
2205      if (DynamicClasses.empty())
2206        DynamicClasses.swap(Record);
2207      else
2208        DynamicClasses.insert(DynamicClasses.end(),
2209                              Record.begin(), Record.end());
2210      break;
2211
2212    case PENDING_IMPLICIT_INSTANTIATIONS:
2213      F.PendingInstantiations.swap(Record);
2214      break;
2215
2216    case SEMA_DECL_REFS:
2217      // Later tables overwrite earlier ones.
2218      SemaDeclRefs.swap(Record);
2219      break;
2220
2221    case ORIGINAL_FILE_NAME:
2222      // The primary AST will be the last to get here, so it will be the one
2223      // that's used.
2224      ActualOriginalFileName.assign(BlobStart, BlobLen);
2225      OriginalFileName = ActualOriginalFileName;
2226      MaybeAddSystemRootToFilename(OriginalFileName);
2227      break;
2228
2229    case ORIGINAL_PCH_DIR:
2230      // The primary AST will be the last to get here, so it will be the one
2231      // that's used.
2232      OriginalDir.assign(BlobStart, BlobLen);
2233      break;
2234
2235    case VERSION_CONTROL_BRANCH_REVISION: {
2236      const std::string &CurBranch = getClangFullRepositoryVersion();
2237      llvm::StringRef ASTBranch(BlobStart, BlobLen);
2238      if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2239        Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2240        return IgnorePCH;
2241      }
2242      break;
2243    }
2244
2245    case MACRO_DEFINITION_OFFSETS:
2246      F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
2247      F.NumPreallocatedPreprocessingEntities = Record[0];
2248      F.LocalNumMacroDefinitions = Record[1];
2249      break;
2250
2251    case DECL_UPDATE_OFFSETS: {
2252      if (Record.size() % 2 != 0) {
2253        Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2254        return Failure;
2255      }
2256      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2257        DeclUpdateOffsets[static_cast<DeclID>(Record[I])]
2258            .push_back(std::make_pair(&F, Record[I+1]));
2259      break;
2260    }
2261
2262    case DECL_REPLACEMENTS: {
2263      if (Record.size() % 2 != 0) {
2264        Error("invalid DECL_REPLACEMENTS block in AST file");
2265        return Failure;
2266      }
2267      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2268        ReplacedDecls[static_cast<DeclID>(Record[I])] =
2269            std::make_pair(&F, Record[I+1]);
2270      break;
2271    }
2272
2273    case CXX_BASE_SPECIFIER_OFFSETS: {
2274      if (F.LocalNumCXXBaseSpecifiers != 0) {
2275        Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2276        return Failure;
2277      }
2278
2279      F.LocalNumCXXBaseSpecifiers = Record[0];
2280      F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2281      break;
2282    }
2283
2284    case DIAG_PRAGMA_MAPPINGS:
2285      if (Record.size() % 2 != 0) {
2286        Error("invalid DIAG_USER_MAPPINGS block in AST file");
2287        return Failure;
2288      }
2289      if (PragmaDiagMappings.empty())
2290        PragmaDiagMappings.swap(Record);
2291      else
2292        PragmaDiagMappings.insert(PragmaDiagMappings.end(),
2293                                Record.begin(), Record.end());
2294      break;
2295
2296    case CUDA_SPECIAL_DECL_REFS:
2297      // Later tables overwrite earlier ones.
2298      CUDASpecialDeclRefs.swap(Record);
2299      break;
2300
2301    case HEADER_SEARCH_TABLE:
2302      F.HeaderFileInfoTableData = BlobStart;
2303      F.LocalNumHeaderFileInfos = Record[1];
2304      if (Record[0]) {
2305        F.HeaderFileInfoTable
2306          = HeaderFileInfoLookupTable::Create(
2307                   (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2308                   (const unsigned char *)F.HeaderFileInfoTableData);
2309        if (PP)
2310          PP->getHeaderSearchInfo().SetExternalSource(this);
2311      }
2312      break;
2313
2314    case FP_PRAGMA_OPTIONS:
2315      // Later tables overwrite earlier ones.
2316      FPPragmaOptions.swap(Record);
2317      break;
2318
2319    case OPENCL_EXTENSIONS:
2320      // Later tables overwrite earlier ones.
2321      OpenCLExtensions.swap(Record);
2322      break;
2323    }
2324    First = false;
2325  }
2326  Error("premature end of bitstream in AST file");
2327  return Failure;
2328}
2329
2330ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2331                                            ASTFileType Type) {
2332  switch(ReadASTCore(FileName, Type)) {
2333  case Failure: return Failure;
2334  case IgnorePCH: return IgnorePCH;
2335  case Success: break;
2336  }
2337
2338  // Here comes stuff that we only do once the entire chain is loaded.
2339
2340  // Allocate space for loaded slocentries, identifiers, decls and types.
2341  unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
2342           TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
2343           TotalNumSelectors = 0;
2344  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2345    TotalNumSLocEntries += Chain[I]->LocalNumSLocEntries;
2346    NextSLocOffset += Chain[I]->LocalSLocSize;
2347    TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
2348    TotalNumTypes += Chain[I]->LocalNumTypes;
2349    TotalNumDecls += Chain[I]->LocalNumDecls;
2350    TotalNumPreallocatedPreprocessingEntities +=
2351        Chain[I]->NumPreallocatedPreprocessingEntities;
2352    TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
2353    TotalNumSelectors += Chain[I]->LocalNumSelectors;
2354  }
2355  SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, NextSLocOffset);
2356  IdentifiersLoaded.resize(TotalNumIdentifiers);
2357  TypesLoaded.resize(TotalNumTypes);
2358  DeclsLoaded.resize(TotalNumDecls);
2359  MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
2360  if (PP) {
2361    if (TotalNumIdentifiers > 0)
2362      PP->getHeaderSearchInfo().SetExternalLookup(this);
2363    if (TotalNumPreallocatedPreprocessingEntities > 0) {
2364      if (!PP->getPreprocessingRecord())
2365        PP->createPreprocessingRecord();
2366      PP->getPreprocessingRecord()->SetExternalSource(*this,
2367                                     TotalNumPreallocatedPreprocessingEntities);
2368    }
2369  }
2370  SelectorsLoaded.resize(TotalNumSelectors);
2371  // Preload SLocEntries.
2372  for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) {
2373    ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]);
2374    if (Result != Success)
2375      return Result;
2376  }
2377
2378  // Check the predefines buffers.
2379  if (!DisableValidation && CheckPredefinesBuffers())
2380    return IgnorePCH;
2381
2382  if (PP) {
2383    // Initialization of keywords and pragmas occurs before the
2384    // AST file is read, so there may be some identifiers that were
2385    // loaded into the IdentifierTable before we intercepted the
2386    // creation of identifiers. Iterate through the list of known
2387    // identifiers and determine whether we have to establish
2388    // preprocessor definitions or top-level identifier declaration
2389    // chains for those identifiers.
2390    //
2391    // We copy the IdentifierInfo pointers to a small vector first,
2392    // since de-serializing declarations or macro definitions can add
2393    // new entries into the identifier table, invalidating the
2394    // iterators.
2395    llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
2396    for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
2397                                IdEnd = PP->getIdentifierTable().end();
2398         Id != IdEnd; ++Id)
2399      Identifiers.push_back(Id->second);
2400    // We need to search the tables in all files.
2401    for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
2402      ASTIdentifierLookupTable *IdTable
2403        = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
2404      // Not all AST files necessarily have identifier tables, only the useful
2405      // ones.
2406      if (!IdTable)
2407        continue;
2408      for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2409        IdentifierInfo *II = Identifiers[I];
2410        // Look in the on-disk hash tables for an entry for this identifier
2411        ASTIdentifierLookupTrait Info(*this, *Chain[J], II);
2412        std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
2413        ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
2414        if (Pos == IdTable->end())
2415          continue;
2416
2417        // Dereferencing the iterator has the effect of populating the
2418        // IdentifierInfo node with the various declarations it needs.
2419        (void)*Pos;
2420      }
2421    }
2422  }
2423
2424  if (Context)
2425    InitializeContext(*Context);
2426
2427  if (DeserializationListener)
2428    DeserializationListener->ReaderInitialized(this);
2429
2430  // If this AST file is a precompiled preamble, then set the main file ID of
2431  // the source manager to the file source file from which the preamble was
2432  // built. This is the only valid way to use a precompiled preamble.
2433  if (Type == Preamble) {
2434    SourceLocation Loc
2435      = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1);
2436    if (Loc.isValid()) {
2437      std::pair<FileID, unsigned> Decomposed = SourceMgr.getDecomposedLoc(Loc);
2438      SourceMgr.SetPreambleFileID(Decomposed.first);
2439    }
2440  }
2441
2442  return Success;
2443}
2444
2445ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName,
2446                                                ASTFileType Type) {
2447  PerFileData *Prev = Chain.empty() ? 0 : Chain.back();
2448  Chain.push_back(new PerFileData(Type));
2449  PerFileData &F = *Chain.back();
2450  if (Prev)
2451    Prev->NextInSource = &F;
2452  else
2453    FirstInSource = &F;
2454  F.Loaders.push_back(Prev);
2455
2456  // Set the AST file name.
2457  F.FileName = FileName;
2458
2459  if (FileName != "-") {
2460    CurrentDir = llvm::sys::path::parent_path(FileName);
2461    if (CurrentDir.empty()) CurrentDir = ".";
2462  }
2463
2464  // Open the AST file.
2465  //
2466  // FIXME: This shouldn't be here, we should just take a raw_ostream.
2467  std::string ErrStr;
2468  llvm::error_code ec;
2469  if (FileName == "-") {
2470    ec = llvm::MemoryBuffer::getSTDIN(F.Buffer);
2471    if (ec)
2472      ErrStr = ec.message();
2473  } else
2474    F.Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrStr));
2475  if (!F.Buffer) {
2476    Error(ErrStr.c_str());
2477    return IgnorePCH;
2478  }
2479
2480  // Initialize the stream
2481  F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
2482                    (const unsigned char *)F.Buffer->getBufferEnd());
2483  llvm::BitstreamCursor &Stream = F.Stream;
2484  Stream.init(F.StreamFile);
2485  F.SizeInBits = F.Buffer->getBufferSize() * 8;
2486
2487  // Sniff for the signature.
2488  if (Stream.Read(8) != 'C' ||
2489      Stream.Read(8) != 'P' ||
2490      Stream.Read(8) != 'C' ||
2491      Stream.Read(8) != 'H') {
2492    Diag(diag::err_not_a_pch_file) << FileName;
2493    return Failure;
2494  }
2495
2496  while (!Stream.AtEndOfStream()) {
2497    unsigned Code = Stream.ReadCode();
2498
2499    if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2500      Error("invalid record at top-level of AST file");
2501      return Failure;
2502    }
2503
2504    unsigned BlockID = Stream.ReadSubBlockID();
2505
2506    // We only know the AST subblock ID.
2507    switch (BlockID) {
2508    case llvm::bitc::BLOCKINFO_BLOCK_ID:
2509      if (Stream.ReadBlockInfoBlock()) {
2510        Error("malformed BlockInfoBlock in AST file");
2511        return Failure;
2512      }
2513      break;
2514    case AST_BLOCK_ID:
2515      switch (ReadASTBlock(F)) {
2516      case Success:
2517        break;
2518
2519      case Failure:
2520        return Failure;
2521
2522      case IgnorePCH:
2523        // FIXME: We could consider reading through to the end of this
2524        // AST block, skipping subblocks, to see if there are other
2525        // AST blocks elsewhere.
2526
2527        // Clear out any preallocated source location entries, so that
2528        // the source manager does not try to resolve them later.
2529        SourceMgr.ClearPreallocatedSLocEntries();
2530
2531        // Remove the stat cache.
2532        if (F.StatCache)
2533          FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2534
2535        return IgnorePCH;
2536      }
2537      break;
2538    default:
2539      if (Stream.SkipBlock()) {
2540        Error("malformed block record in AST file");
2541        return Failure;
2542      }
2543      break;
2544    }
2545  }
2546
2547  return Success;
2548}
2549
2550void ASTReader::setPreprocessor(Preprocessor &pp) {
2551  PP = &pp;
2552
2553  unsigned TotalNum = 0;
2554  for (unsigned I = 0, N = Chain.size(); I != N; ++I)
2555    TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
2556  if (TotalNum) {
2557    if (!PP->getPreprocessingRecord())
2558      PP->createPreprocessingRecord();
2559    PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
2560  }
2561}
2562
2563void ASTReader::InitializeContext(ASTContext &Ctx) {
2564  Context = &Ctx;
2565  assert(Context && "Passed null context!");
2566
2567  assert(PP && "Forgot to set Preprocessor ?");
2568  PP->getIdentifierTable().setExternalIdentifierLookup(this);
2569  PP->getHeaderSearchInfo().SetExternalLookup(this);
2570  PP->setExternalSource(this);
2571  PP->getHeaderSearchInfo().SetExternalSource(this);
2572
2573  // If we have an update block for the TU waiting, we have to add it before
2574  // deserializing the decl.
2575  DeclContextOffsetsMap::iterator DCU = DeclContextOffsets.find(0);
2576  if (DCU != DeclContextOffsets.end()) {
2577    // Insertion could invalidate map, so grab vector.
2578    DeclContextInfos T;
2579    T.swap(DCU->second);
2580    DeclContextOffsets.erase(DCU);
2581    DeclContextOffsets[Ctx.getTranslationUnitDecl()].swap(T);
2582  }
2583
2584  // Load the translation unit declaration
2585  GetTranslationUnitDecl();
2586
2587  // Load the special types.
2588  Context->setBuiltinVaListType(
2589    GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2590  if (unsigned Id = SpecialTypes[SPECIAL_TYPE_OBJC_ID])
2591    Context->setObjCIdType(GetType(Id));
2592  if (unsigned Sel = SpecialTypes[SPECIAL_TYPE_OBJC_SELECTOR])
2593    Context->setObjCSelType(GetType(Sel));
2594  if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL])
2595    Context->setObjCProtoType(GetType(Proto));
2596  if (unsigned Class = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS])
2597    Context->setObjCClassType(GetType(Class));
2598
2599  if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING])
2600    Context->setCFConstantStringType(GetType(String));
2601  if (unsigned FastEnum
2602        = SpecialTypes[SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2603    Context->setObjCFastEnumerationStateType(GetType(FastEnum));
2604  if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2605    QualType FileType = GetType(File);
2606    if (FileType.isNull()) {
2607      Error("FILE type is NULL");
2608      return;
2609    }
2610    if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2611      Context->setFILEDecl(Typedef->getDecl());
2612    else {
2613      const TagType *Tag = FileType->getAs<TagType>();
2614      if (!Tag) {
2615        Error("Invalid FILE type in AST file");
2616        return;
2617      }
2618      Context->setFILEDecl(Tag->getDecl());
2619    }
2620  }
2621  if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2622    QualType Jmp_bufType = GetType(Jmp_buf);
2623    if (Jmp_bufType.isNull()) {
2624      Error("jmp_bug type is NULL");
2625      return;
2626    }
2627    if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2628      Context->setjmp_bufDecl(Typedef->getDecl());
2629    else {
2630      const TagType *Tag = Jmp_bufType->getAs<TagType>();
2631      if (!Tag) {
2632        Error("Invalid jmp_buf type in AST file");
2633        return;
2634      }
2635      Context->setjmp_bufDecl(Tag->getDecl());
2636    }
2637  }
2638  if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2639    QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2640    if (Sigjmp_bufType.isNull()) {
2641      Error("sigjmp_buf type is NULL");
2642      return;
2643    }
2644    if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2645      Context->setsigjmp_bufDecl(Typedef->getDecl());
2646    else {
2647      const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2648      assert(Tag && "Invalid sigjmp_buf type in AST file");
2649      Context->setsigjmp_bufDecl(Tag->getDecl());
2650    }
2651  }
2652  if (unsigned ObjCIdRedef
2653        = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2654    Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2655  if (unsigned ObjCClassRedef
2656      = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2657    Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2658  if (unsigned String = SpecialTypes[SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2659    Context->setBlockDescriptorType(GetType(String));
2660  if (unsigned String
2661      = SpecialTypes[SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2662    Context->setBlockDescriptorExtendedType(GetType(String));
2663  if (unsigned ObjCSelRedef
2664      = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2665    Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2666  if (unsigned String = SpecialTypes[SPECIAL_TYPE_NS_CONSTANT_STRING])
2667    Context->setNSConstantStringType(GetType(String));
2668
2669  if (SpecialTypes[SPECIAL_TYPE_INT128_INSTALLED])
2670    Context->setInt128Installed();
2671
2672  ReadPragmaDiagnosticMappings(Context->getDiagnostics());
2673
2674  // If there were any CUDA special declarations, deserialize them.
2675  if (!CUDASpecialDeclRefs.empty()) {
2676    assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2677    Context->setcudaConfigureCallDecl(
2678                           cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2679  }
2680}
2681
2682/// \brief Retrieve the name of the original source file name
2683/// directly from the AST file, without actually loading the AST
2684/// file.
2685std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2686                                             FileManager &FileMgr,
2687                                             Diagnostic &Diags) {
2688  // Open the AST file.
2689  std::string ErrStr;
2690  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2691  Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2692  if (!Buffer) {
2693    Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2694    return std::string();
2695  }
2696
2697  // Initialize the stream
2698  llvm::BitstreamReader StreamFile;
2699  llvm::BitstreamCursor Stream;
2700  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2701                  (const unsigned char *)Buffer->getBufferEnd());
2702  Stream.init(StreamFile);
2703
2704  // Sniff for the signature.
2705  if (Stream.Read(8) != 'C' ||
2706      Stream.Read(8) != 'P' ||
2707      Stream.Read(8) != 'C' ||
2708      Stream.Read(8) != 'H') {
2709    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2710    return std::string();
2711  }
2712
2713  RecordData Record;
2714  while (!Stream.AtEndOfStream()) {
2715    unsigned Code = Stream.ReadCode();
2716
2717    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2718      unsigned BlockID = Stream.ReadSubBlockID();
2719
2720      // We only know the AST subblock ID.
2721      switch (BlockID) {
2722      case AST_BLOCK_ID:
2723        if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2724          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2725          return std::string();
2726        }
2727        break;
2728
2729      default:
2730        if (Stream.SkipBlock()) {
2731          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2732          return std::string();
2733        }
2734        break;
2735      }
2736      continue;
2737    }
2738
2739    if (Code == llvm::bitc::END_BLOCK) {
2740      if (Stream.ReadBlockEnd()) {
2741        Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2742        return std::string();
2743      }
2744      continue;
2745    }
2746
2747    if (Code == llvm::bitc::DEFINE_ABBREV) {
2748      Stream.ReadAbbrevRecord();
2749      continue;
2750    }
2751
2752    Record.clear();
2753    const char *BlobStart = 0;
2754    unsigned BlobLen = 0;
2755    if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2756          == ORIGINAL_FILE_NAME)
2757      return std::string(BlobStart, BlobLen);
2758  }
2759
2760  return std::string();
2761}
2762
2763/// \brief Parse the record that corresponds to a LangOptions data
2764/// structure.
2765///
2766/// This routine parses the language options from the AST file and then gives
2767/// them to the AST listener if one is set.
2768///
2769/// \returns true if the listener deems the file unacceptable, false otherwise.
2770bool ASTReader::ParseLanguageOptions(
2771                             const llvm::SmallVectorImpl<uint64_t> &Record) {
2772  if (Listener) {
2773    LangOptions LangOpts;
2774
2775  #define PARSE_LANGOPT(Option)                  \
2776      LangOpts.Option = Record[Idx];             \
2777      ++Idx
2778
2779    unsigned Idx = 0;
2780    PARSE_LANGOPT(Trigraphs);
2781    PARSE_LANGOPT(BCPLComment);
2782    PARSE_LANGOPT(DollarIdents);
2783    PARSE_LANGOPT(AsmPreprocessor);
2784    PARSE_LANGOPT(GNUMode);
2785    PARSE_LANGOPT(GNUKeywords);
2786    PARSE_LANGOPT(ImplicitInt);
2787    PARSE_LANGOPT(Digraphs);
2788    PARSE_LANGOPT(HexFloats);
2789    PARSE_LANGOPT(C99);
2790    PARSE_LANGOPT(Microsoft);
2791    PARSE_LANGOPT(CPlusPlus);
2792    PARSE_LANGOPT(CPlusPlus0x);
2793    PARSE_LANGOPT(CXXOperatorNames);
2794    PARSE_LANGOPT(ObjC1);
2795    PARSE_LANGOPT(ObjC2);
2796    PARSE_LANGOPT(ObjCNonFragileABI);
2797    PARSE_LANGOPT(ObjCNonFragileABI2);
2798    PARSE_LANGOPT(AppleKext);
2799    PARSE_LANGOPT(ObjCDefaultSynthProperties);
2800    PARSE_LANGOPT(NoConstantCFStrings);
2801    PARSE_LANGOPT(PascalStrings);
2802    PARSE_LANGOPT(WritableStrings);
2803    PARSE_LANGOPT(LaxVectorConversions);
2804    PARSE_LANGOPT(AltiVec);
2805    PARSE_LANGOPT(Exceptions);
2806    PARSE_LANGOPT(ObjCExceptions);
2807    PARSE_LANGOPT(CXXExceptions);
2808    PARSE_LANGOPT(SjLjExceptions);
2809    PARSE_LANGOPT(MSBitfields);
2810    PARSE_LANGOPT(NeXTRuntime);
2811    PARSE_LANGOPT(Freestanding);
2812    PARSE_LANGOPT(NoBuiltin);
2813    PARSE_LANGOPT(ThreadsafeStatics);
2814    PARSE_LANGOPT(POSIXThreads);
2815    PARSE_LANGOPT(Blocks);
2816    PARSE_LANGOPT(EmitAllDecls);
2817    PARSE_LANGOPT(MathErrno);
2818    LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2819                                       Record[Idx++]);
2820    PARSE_LANGOPT(HeinousExtensions);
2821    PARSE_LANGOPT(Optimize);
2822    PARSE_LANGOPT(OptimizeSize);
2823    PARSE_LANGOPT(Static);
2824    PARSE_LANGOPT(PICLevel);
2825    PARSE_LANGOPT(GNUInline);
2826    PARSE_LANGOPT(NoInline);
2827    PARSE_LANGOPT(AccessControl);
2828    PARSE_LANGOPT(CharIsSigned);
2829    PARSE_LANGOPT(ShortWChar);
2830    PARSE_LANGOPT(ShortEnums);
2831    LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2832    LangOpts.setVisibilityMode((Visibility)Record[Idx++]);
2833    LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
2834                                   Record[Idx++]);
2835    PARSE_LANGOPT(InstantiationDepth);
2836    PARSE_LANGOPT(OpenCL);
2837    PARSE_LANGOPT(CUDA);
2838    PARSE_LANGOPT(CatchUndefined);
2839    PARSE_LANGOPT(DefaultFPContract);
2840    PARSE_LANGOPT(ElideConstructors);
2841    PARSE_LANGOPT(SpellChecking);
2842    PARSE_LANGOPT(MRTD);
2843  #undef PARSE_LANGOPT
2844
2845    return Listener->ReadLanguageOptions(LangOpts);
2846  }
2847
2848  return false;
2849}
2850
2851void ASTReader::ReadPreprocessedEntities() {
2852  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2853    PerFileData &F = *Chain[I];
2854    if (!F.PreprocessorDetailCursor.getBitStreamReader())
2855      continue;
2856
2857    SavedStreamPosition SavedPosition(F.PreprocessorDetailCursor);
2858    F.PreprocessorDetailCursor.JumpToBit(F.PreprocessorDetailStartOffset);
2859    while (LoadPreprocessedEntity(F)) { }
2860  }
2861}
2862
2863PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) {
2864  PerFileData *F = 0;
2865  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2866    if (Offset < Chain[I]->SizeInBits) {
2867      F = Chain[I];
2868      break;
2869    }
2870
2871    Offset -= Chain[I]->SizeInBits;
2872  }
2873
2874  if (!F) {
2875    Error("Malformed preprocessed entity offset");
2876    return 0;
2877  }
2878
2879  // Keep track of where we are in the stream, then jump back there
2880  // after reading this entity.
2881  SavedStreamPosition SavedPosition(F->PreprocessorDetailCursor);
2882  F->PreprocessorDetailCursor.JumpToBit(Offset);
2883  return LoadPreprocessedEntity(*F);
2884}
2885
2886HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
2887  HeaderFileInfoTrait Trait(FE->getName());
2888  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2889    PerFileData &F = *Chain[I];
2890    HeaderFileInfoLookupTable *Table
2891      = static_cast<HeaderFileInfoLookupTable *>(F.HeaderFileInfoTable);
2892    if (!Table)
2893      continue;
2894
2895    // Look in the on-disk hash table for an entry for this file name.
2896    HeaderFileInfoLookupTable::iterator Pos = Table->find(FE->getName(),
2897                                                          &Trait);
2898    if (Pos == Table->end())
2899      continue;
2900
2901    HeaderFileInfo HFI = *Pos;
2902    if (Listener)
2903      Listener->ReadHeaderFileInfo(HFI, FE->getUID());
2904
2905    return HFI;
2906  }
2907
2908  return HeaderFileInfo();
2909}
2910
2911void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) {
2912  unsigned Idx = 0;
2913  while (Idx < PragmaDiagMappings.size()) {
2914    SourceLocation
2915      Loc = SourceLocation::getFromRawEncoding(PragmaDiagMappings[Idx++]);
2916    while (1) {
2917      assert(Idx < PragmaDiagMappings.size() &&
2918             "Invalid data, didn't find '-1' marking end of diag/map pairs");
2919      if (Idx >= PragmaDiagMappings.size())
2920        break; // Something is messed up but at least avoid infinite loop in
2921               // release build.
2922      unsigned DiagID = PragmaDiagMappings[Idx++];
2923      if (DiagID == (unsigned)-1)
2924        break; // no more diag/map pairs for this location.
2925      diag::Mapping Map = (diag::Mapping)PragmaDiagMappings[Idx++];
2926      Diag.setDiagnosticMapping(DiagID, Map, Loc);
2927    }
2928  }
2929}
2930
2931/// \brief Get the correct cursor and offset for loading a type.
2932ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
2933  PerFileData *F = 0;
2934  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2935    F = Chain[N - I - 1];
2936    if (Index < F->LocalNumTypes)
2937      break;
2938    Index -= F->LocalNumTypes;
2939  }
2940  assert(F && F->LocalNumTypes > Index && "Broken chain");
2941  return RecordLocation(F, F->TypeOffsets[Index]);
2942}
2943
2944/// \brief Read and return the type with the given index..
2945///
2946/// The index is the type ID, shifted and minus the number of predefs. This
2947/// routine actually reads the record corresponding to the type at the given
2948/// location. It is a helper routine for GetType, which deals with reading type
2949/// IDs.
2950QualType ASTReader::ReadTypeRecord(unsigned Index) {
2951  RecordLocation Loc = TypeCursorForIndex(Index);
2952  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2953
2954  // Keep track of where we are in the stream, then jump back there
2955  // after reading this type.
2956  SavedStreamPosition SavedPosition(DeclsCursor);
2957
2958  ReadingKindTracker ReadingKind(Read_Type, *this);
2959
2960  // Note that we are loading a type record.
2961  Deserializing AType(this);
2962
2963  DeclsCursor.JumpToBit(Loc.Offset);
2964  RecordData Record;
2965  unsigned Code = DeclsCursor.ReadCode();
2966  switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
2967  case TYPE_EXT_QUAL: {
2968    if (Record.size() != 2) {
2969      Error("Incorrect encoding of extended qualifier type");
2970      return QualType();
2971    }
2972    QualType Base = GetType(Record[0]);
2973    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2974    return Context->getQualifiedType(Base, Quals);
2975  }
2976
2977  case TYPE_COMPLEX: {
2978    if (Record.size() != 1) {
2979      Error("Incorrect encoding of complex type");
2980      return QualType();
2981    }
2982    QualType ElemType = GetType(Record[0]);
2983    return Context->getComplexType(ElemType);
2984  }
2985
2986  case TYPE_POINTER: {
2987    if (Record.size() != 1) {
2988      Error("Incorrect encoding of pointer type");
2989      return QualType();
2990    }
2991    QualType PointeeType = GetType(Record[0]);
2992    return Context->getPointerType(PointeeType);
2993  }
2994
2995  case TYPE_BLOCK_POINTER: {
2996    if (Record.size() != 1) {
2997      Error("Incorrect encoding of block pointer type");
2998      return QualType();
2999    }
3000    QualType PointeeType = GetType(Record[0]);
3001    return Context->getBlockPointerType(PointeeType);
3002  }
3003
3004  case TYPE_LVALUE_REFERENCE: {
3005    if (Record.size() != 1) {
3006      Error("Incorrect encoding of lvalue reference type");
3007      return QualType();
3008    }
3009    QualType PointeeType = GetType(Record[0]);
3010    return Context->getLValueReferenceType(PointeeType);
3011  }
3012
3013  case TYPE_RVALUE_REFERENCE: {
3014    if (Record.size() != 1) {
3015      Error("Incorrect encoding of rvalue reference type");
3016      return QualType();
3017    }
3018    QualType PointeeType = GetType(Record[0]);
3019    return Context->getRValueReferenceType(PointeeType);
3020  }
3021
3022  case TYPE_MEMBER_POINTER: {
3023    if (Record.size() != 2) {
3024      Error("Incorrect encoding of member pointer type");
3025      return QualType();
3026    }
3027    QualType PointeeType = GetType(Record[0]);
3028    QualType ClassType = GetType(Record[1]);
3029    if (PointeeType.isNull() || ClassType.isNull())
3030      return QualType();
3031
3032    return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
3033  }
3034
3035  case TYPE_CONSTANT_ARRAY: {
3036    QualType ElementType = GetType(Record[0]);
3037    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3038    unsigned IndexTypeQuals = Record[2];
3039    unsigned Idx = 3;
3040    llvm::APInt Size = ReadAPInt(Record, Idx);
3041    return Context->getConstantArrayType(ElementType, Size,
3042                                         ASM, IndexTypeQuals);
3043  }
3044
3045  case TYPE_INCOMPLETE_ARRAY: {
3046    QualType ElementType = GetType(Record[0]);
3047    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3048    unsigned IndexTypeQuals = Record[2];
3049    return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3050  }
3051
3052  case TYPE_VARIABLE_ARRAY: {
3053    QualType ElementType = GetType(Record[0]);
3054    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3055    unsigned IndexTypeQuals = Record[2];
3056    SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3057    SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3058    return Context->getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3059                                         ASM, IndexTypeQuals,
3060                                         SourceRange(LBLoc, RBLoc));
3061  }
3062
3063  case TYPE_VECTOR: {
3064    if (Record.size() != 3) {
3065      Error("incorrect encoding of vector type in AST file");
3066      return QualType();
3067    }
3068
3069    QualType ElementType = GetType(Record[0]);
3070    unsigned NumElements = Record[1];
3071    unsigned VecKind = Record[2];
3072    return Context->getVectorType(ElementType, NumElements,
3073                                  (VectorType::VectorKind)VecKind);
3074  }
3075
3076  case TYPE_EXT_VECTOR: {
3077    if (Record.size() != 3) {
3078      Error("incorrect encoding of extended vector type in AST file");
3079      return QualType();
3080    }
3081
3082    QualType ElementType = GetType(Record[0]);
3083    unsigned NumElements = Record[1];
3084    return Context->getExtVectorType(ElementType, NumElements);
3085  }
3086
3087  case TYPE_FUNCTION_NO_PROTO: {
3088    if (Record.size() != 4) {
3089      Error("incorrect encoding of no-proto function type");
3090      return QualType();
3091    }
3092    QualType ResultType = GetType(Record[0]);
3093    FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
3094    return Context->getFunctionNoProtoType(ResultType, Info);
3095  }
3096
3097  case TYPE_FUNCTION_PROTO: {
3098    QualType ResultType = GetType(Record[0]);
3099
3100    FunctionProtoType::ExtProtoInfo EPI;
3101    EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3102                                        /*regparm*/ Record[2],
3103                                        static_cast<CallingConv>(Record[3]));
3104
3105    unsigned Idx = 4;
3106    unsigned NumParams = Record[Idx++];
3107    llvm::SmallVector<QualType, 16> ParamTypes;
3108    for (unsigned I = 0; I != NumParams; ++I)
3109      ParamTypes.push_back(GetType(Record[Idx++]));
3110
3111    EPI.Variadic = Record[Idx++];
3112    EPI.TypeQuals = Record[Idx++];
3113    EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3114    bool HasExceptionSpec = Record[Idx++];
3115    bool HasAnyExceptionSpec = Record[Idx++];
3116    EPI.ExceptionSpecType = HasExceptionSpec ?
3117        (HasAnyExceptionSpec ? EST_DynamicAny : EST_Dynamic) : EST_None;
3118    EPI.NumExceptions = Record[Idx++];
3119    llvm::SmallVector<QualType, 2> Exceptions;
3120    for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3121      Exceptions.push_back(GetType(Record[Idx++]));
3122    EPI.Exceptions = Exceptions.data();
3123    return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
3124                                    EPI);
3125  }
3126
3127  case TYPE_UNRESOLVED_USING:
3128    return Context->getTypeDeclType(
3129             cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
3130
3131  case TYPE_TYPEDEF: {
3132    if (Record.size() != 2) {
3133      Error("incorrect encoding of typedef type");
3134      return QualType();
3135    }
3136    TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
3137    QualType Canonical = GetType(Record[1]);
3138    if (!Canonical.isNull())
3139      Canonical = Context->getCanonicalType(Canonical);
3140    return Context->getTypedefType(Decl, Canonical);
3141  }
3142
3143  case TYPE_TYPEOF_EXPR:
3144    return Context->getTypeOfExprType(ReadExpr(*Loc.F));
3145
3146  case TYPE_TYPEOF: {
3147    if (Record.size() != 1) {
3148      Error("incorrect encoding of typeof(type) in AST file");
3149      return QualType();
3150    }
3151    QualType UnderlyingType = GetType(Record[0]);
3152    return Context->getTypeOfType(UnderlyingType);
3153  }
3154
3155  case TYPE_DECLTYPE:
3156    return Context->getDecltypeType(ReadExpr(*Loc.F));
3157
3158  case TYPE_AUTO:
3159    return Context->getAutoType(GetType(Record[0]));
3160
3161  case TYPE_RECORD: {
3162    if (Record.size() != 2) {
3163      Error("incorrect encoding of record type");
3164      return QualType();
3165    }
3166    bool IsDependent = Record[0];
3167    QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
3168    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3169    return T;
3170  }
3171
3172  case TYPE_ENUM: {
3173    if (Record.size() != 2) {
3174      Error("incorrect encoding of enum type");
3175      return QualType();
3176    }
3177    bool IsDependent = Record[0];
3178    QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
3179    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3180    return T;
3181  }
3182
3183  case TYPE_ATTRIBUTED: {
3184    if (Record.size() != 3) {
3185      Error("incorrect encoding of attributed type");
3186      return QualType();
3187    }
3188    QualType modifiedType = GetType(Record[0]);
3189    QualType equivalentType = GetType(Record[1]);
3190    AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3191    return Context->getAttributedType(kind, modifiedType, equivalentType);
3192  }
3193
3194  case TYPE_PAREN: {
3195    if (Record.size() != 1) {
3196      Error("incorrect encoding of paren type");
3197      return QualType();
3198    }
3199    QualType InnerType = GetType(Record[0]);
3200    return Context->getParenType(InnerType);
3201  }
3202
3203  case TYPE_PACK_EXPANSION: {
3204    if (Record.size() != 2) {
3205      Error("incorrect encoding of pack expansion type");
3206      return QualType();
3207    }
3208    QualType Pattern = GetType(Record[0]);
3209    if (Pattern.isNull())
3210      return QualType();
3211    llvm::Optional<unsigned> NumExpansions;
3212    if (Record[1])
3213      NumExpansions = Record[1] - 1;
3214    return Context->getPackExpansionType(Pattern, NumExpansions);
3215  }
3216
3217  case TYPE_ELABORATED: {
3218    unsigned Idx = 0;
3219    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3220    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3221    QualType NamedType = GetType(Record[Idx++]);
3222    return Context->getElaboratedType(Keyword, NNS, NamedType);
3223  }
3224
3225  case TYPE_OBJC_INTERFACE: {
3226    unsigned Idx = 0;
3227    ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
3228    return Context->getObjCInterfaceType(ItfD);
3229  }
3230
3231  case TYPE_OBJC_OBJECT: {
3232    unsigned Idx = 0;
3233    QualType Base = GetType(Record[Idx++]);
3234    unsigned NumProtos = Record[Idx++];
3235    llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
3236    for (unsigned I = 0; I != NumProtos; ++I)
3237      Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
3238    return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
3239  }
3240
3241  case TYPE_OBJC_OBJECT_POINTER: {
3242    unsigned Idx = 0;
3243    QualType Pointee = GetType(Record[Idx++]);
3244    return Context->getObjCObjectPointerType(Pointee);
3245  }
3246
3247  case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3248    unsigned Idx = 0;
3249    QualType Parm = GetType(Record[Idx++]);
3250    QualType Replacement = GetType(Record[Idx++]);
3251    return
3252      Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3253                                            Replacement);
3254  }
3255
3256  case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3257    unsigned Idx = 0;
3258    QualType Parm = GetType(Record[Idx++]);
3259    TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3260    return Context->getSubstTemplateTypeParmPackType(
3261                                               cast<TemplateTypeParmType>(Parm),
3262                                                     ArgPack);
3263  }
3264
3265  case TYPE_INJECTED_CLASS_NAME: {
3266    CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
3267    QualType TST = GetType(Record[1]); // probably derivable
3268    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3269    // for AST reading, too much interdependencies.
3270    return
3271      QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3272  }
3273
3274  case TYPE_TEMPLATE_TYPE_PARM: {
3275    unsigned Idx = 0;
3276    unsigned Depth = Record[Idx++];
3277    unsigned Index = Record[Idx++];
3278    bool Pack = Record[Idx++];
3279    IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
3280    return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
3281  }
3282
3283  case TYPE_DEPENDENT_NAME: {
3284    unsigned Idx = 0;
3285    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3286    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3287    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3288    QualType Canon = GetType(Record[Idx++]);
3289    if (!Canon.isNull())
3290      Canon = Context->getCanonicalType(Canon);
3291    return Context->getDependentNameType(Keyword, NNS, Name, Canon);
3292  }
3293
3294  case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3295    unsigned Idx = 0;
3296    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3297    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3298    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
3299    unsigned NumArgs = Record[Idx++];
3300    llvm::SmallVector<TemplateArgument, 8> Args;
3301    Args.reserve(NumArgs);
3302    while (NumArgs--)
3303      Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3304    return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
3305                                                      Args.size(), Args.data());
3306  }
3307
3308  case TYPE_DEPENDENT_SIZED_ARRAY: {
3309    unsigned Idx = 0;
3310
3311    // ArrayType
3312    QualType ElementType = GetType(Record[Idx++]);
3313    ArrayType::ArraySizeModifier ASM
3314      = (ArrayType::ArraySizeModifier)Record[Idx++];
3315    unsigned IndexTypeQuals = Record[Idx++];
3316
3317    // DependentSizedArrayType
3318    Expr *NumElts = ReadExpr(*Loc.F);
3319    SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3320
3321    return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
3322                                               IndexTypeQuals, Brackets);
3323  }
3324
3325  case TYPE_TEMPLATE_SPECIALIZATION: {
3326    unsigned Idx = 0;
3327    bool IsDependent = Record[Idx++];
3328    TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3329    llvm::SmallVector<TemplateArgument, 8> Args;
3330    ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3331    QualType Canon = GetType(Record[Idx++]);
3332    QualType T;
3333    if (Canon.isNull())
3334      T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
3335                                                          Args.size());
3336    else
3337      T = Context->getTemplateSpecializationType(Name, Args.data(),
3338                                                 Args.size(), Canon);
3339    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3340    return T;
3341  }
3342  }
3343  // Suppress a GCC warning
3344  return QualType();
3345}
3346
3347class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3348  ASTReader &Reader;
3349  ASTReader::PerFileData &F;
3350  llvm::BitstreamCursor &DeclsCursor;
3351  const ASTReader::RecordData &Record;
3352  unsigned &Idx;
3353
3354  SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3355                                    unsigned &I) {
3356    return Reader.ReadSourceLocation(F, R, I);
3357  }
3358
3359public:
3360  TypeLocReader(ASTReader &Reader, ASTReader::PerFileData &F,
3361                const ASTReader::RecordData &Record, unsigned &Idx)
3362    : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3363  { }
3364
3365  // We want compile-time assurance that we've enumerated all of
3366  // these, so unfortunately we have to declare them first, then
3367  // define them out-of-line.
3368#define ABSTRACT_TYPELOC(CLASS, PARENT)
3369#define TYPELOC(CLASS, PARENT) \
3370  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3371#include "clang/AST/TypeLocNodes.def"
3372
3373  void VisitFunctionTypeLoc(FunctionTypeLoc);
3374  void VisitArrayTypeLoc(ArrayTypeLoc);
3375};
3376
3377void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3378  // nothing to do
3379}
3380void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3381  TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3382  if (TL.needsExtraLocalData()) {
3383    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3384    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3385    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3386    TL.setModeAttr(Record[Idx++]);
3387  }
3388}
3389void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3390  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3391}
3392void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3393  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3394}
3395void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3396  TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3397}
3398void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3399  TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3400}
3401void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3402  TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3403}
3404void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3405  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3406  TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3407}
3408void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3409  TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3410  TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3411  if (Record[Idx++])
3412    TL.setSizeExpr(Reader.ReadExpr(F));
3413  else
3414    TL.setSizeExpr(0);
3415}
3416void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3417  VisitArrayTypeLoc(TL);
3418}
3419void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3420  VisitArrayTypeLoc(TL);
3421}
3422void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3423  VisitArrayTypeLoc(TL);
3424}
3425void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3426                                            DependentSizedArrayTypeLoc TL) {
3427  VisitArrayTypeLoc(TL);
3428}
3429void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3430                                        DependentSizedExtVectorTypeLoc TL) {
3431  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3432}
3433void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3434  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3435}
3436void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3437  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3438}
3439void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3440  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3441  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3442  TL.setTrailingReturn(Record[Idx++]);
3443  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3444    TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
3445  }
3446}
3447void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3448  VisitFunctionTypeLoc(TL);
3449}
3450void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3451  VisitFunctionTypeLoc(TL);
3452}
3453void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3454  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3455}
3456void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3457  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3458}
3459void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3460  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3461  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3462  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3463}
3464void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3465  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3466  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3467  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3468  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3469}
3470void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3471  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3472}
3473void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3474  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3475}
3476void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3477  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3478}
3479void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3480  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3481}
3482void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3483  TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3484  if (TL.hasAttrOperand()) {
3485    SourceRange range;
3486    range.setBegin(ReadSourceLocation(Record, Idx));
3487    range.setEnd(ReadSourceLocation(Record, Idx));
3488    TL.setAttrOperandParensRange(range);
3489  }
3490  if (TL.hasAttrExprOperand()) {
3491    if (Record[Idx++])
3492      TL.setAttrExprOperand(Reader.ReadExpr(F));
3493    else
3494      TL.setAttrExprOperand(0);
3495  } else if (TL.hasAttrEnumOperand())
3496    TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3497}
3498void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3499  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3500}
3501void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3502                                            SubstTemplateTypeParmTypeLoc TL) {
3503  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3504}
3505void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3506                                          SubstTemplateTypeParmPackTypeLoc TL) {
3507  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3508}
3509void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3510                                           TemplateSpecializationTypeLoc TL) {
3511  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3512  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3513  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3514  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3515    TL.setArgLocInfo(i,
3516        Reader.GetTemplateArgumentLocInfo(F,
3517                                          TL.getTypePtr()->getArg(i).getKind(),
3518                                          Record, Idx));
3519}
3520void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3521  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3522  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3523}
3524void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3525  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3526  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3527}
3528void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3529  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3530}
3531void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3532  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3533  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3534  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3535}
3536void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3537       DependentTemplateSpecializationTypeLoc TL) {
3538  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3539  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3540  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3541  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3542  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3543  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3544    TL.setArgLocInfo(I,
3545        Reader.GetTemplateArgumentLocInfo(F,
3546                                          TL.getTypePtr()->getArg(I).getKind(),
3547                                          Record, Idx));
3548}
3549void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3550  TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3551}
3552void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3553  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3554}
3555void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3556  TL.setHasBaseTypeAsWritten(Record[Idx++]);
3557  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3558  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3559  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3560    TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3561}
3562void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3563  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3564}
3565
3566TypeSourceInfo *ASTReader::GetTypeSourceInfo(PerFileData &F,
3567                                             const RecordData &Record,
3568                                             unsigned &Idx) {
3569  QualType InfoTy = GetType(Record[Idx++]);
3570  if (InfoTy.isNull())
3571    return 0;
3572
3573  TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
3574  TypeLocReader TLR(*this, F, Record, Idx);
3575  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3576    TLR.Visit(TL);
3577  return TInfo;
3578}
3579
3580QualType ASTReader::GetType(TypeID ID) {
3581  unsigned FastQuals = ID & Qualifiers::FastMask;
3582  unsigned Index = ID >> Qualifiers::FastWidth;
3583
3584  if (Index < NUM_PREDEF_TYPE_IDS) {
3585    QualType T;
3586    switch ((PredefinedTypeIDs)Index) {
3587    case PREDEF_TYPE_NULL_ID: return QualType();
3588    case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
3589    case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
3590
3591    case PREDEF_TYPE_CHAR_U_ID:
3592    case PREDEF_TYPE_CHAR_S_ID:
3593      // FIXME: Check that the signedness of CharTy is correct!
3594      T = Context->CharTy;
3595      break;
3596
3597    case PREDEF_TYPE_UCHAR_ID:      T = Context->UnsignedCharTy;     break;
3598    case PREDEF_TYPE_USHORT_ID:     T = Context->UnsignedShortTy;    break;
3599    case PREDEF_TYPE_UINT_ID:       T = Context->UnsignedIntTy;      break;
3600    case PREDEF_TYPE_ULONG_ID:      T = Context->UnsignedLongTy;     break;
3601    case PREDEF_TYPE_ULONGLONG_ID:  T = Context->UnsignedLongLongTy; break;
3602    case PREDEF_TYPE_UINT128_ID:    T = Context->UnsignedInt128Ty;   break;
3603    case PREDEF_TYPE_SCHAR_ID:      T = Context->SignedCharTy;       break;
3604    case PREDEF_TYPE_WCHAR_ID:      T = Context->WCharTy;            break;
3605    case PREDEF_TYPE_SHORT_ID:      T = Context->ShortTy;            break;
3606    case PREDEF_TYPE_INT_ID:        T = Context->IntTy;              break;
3607    case PREDEF_TYPE_LONG_ID:       T = Context->LongTy;             break;
3608    case PREDEF_TYPE_LONGLONG_ID:   T = Context->LongLongTy;         break;
3609    case PREDEF_TYPE_INT128_ID:     T = Context->Int128Ty;           break;
3610    case PREDEF_TYPE_FLOAT_ID:      T = Context->FloatTy;            break;
3611    case PREDEF_TYPE_DOUBLE_ID:     T = Context->DoubleTy;           break;
3612    case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy;       break;
3613    case PREDEF_TYPE_OVERLOAD_ID:   T = Context->OverloadTy;         break;
3614    case PREDEF_TYPE_DEPENDENT_ID:  T = Context->DependentTy;        break;
3615    case PREDEF_TYPE_NULLPTR_ID:    T = Context->NullPtrTy;          break;
3616    case PREDEF_TYPE_CHAR16_ID:     T = Context->Char16Ty;           break;
3617    case PREDEF_TYPE_CHAR32_ID:     T = Context->Char32Ty;           break;
3618    case PREDEF_TYPE_OBJC_ID:       T = Context->ObjCBuiltinIdTy;    break;
3619    case PREDEF_TYPE_OBJC_CLASS:    T = Context->ObjCBuiltinClassTy; break;
3620    case PREDEF_TYPE_OBJC_SEL:      T = Context->ObjCBuiltinSelTy;   break;
3621    }
3622
3623    assert(!T.isNull() && "Unknown predefined type");
3624    return T.withFastQualifiers(FastQuals);
3625  }
3626
3627  Index -= NUM_PREDEF_TYPE_IDS;
3628  assert(Index < TypesLoaded.size() && "Type index out-of-range");
3629  if (TypesLoaded[Index].isNull()) {
3630    TypesLoaded[Index] = ReadTypeRecord(Index);
3631    if (TypesLoaded[Index].isNull())
3632      return QualType();
3633
3634    TypesLoaded[Index]->setFromAST();
3635    TypeIdxs[TypesLoaded[Index]] = TypeIdx::fromTypeID(ID);
3636    if (DeserializationListener)
3637      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3638                                        TypesLoaded[Index]);
3639  }
3640
3641  return TypesLoaded[Index].withFastQualifiers(FastQuals);
3642}
3643
3644TypeID ASTReader::GetTypeID(QualType T) const {
3645  return MakeTypeID(T,
3646              std::bind1st(std::mem_fun(&ASTReader::GetTypeIdx), this));
3647}
3648
3649TypeIdx ASTReader::GetTypeIdx(QualType T) const {
3650  if (T.isNull())
3651    return TypeIdx();
3652  assert(!T.getLocalFastQualifiers());
3653
3654  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3655  // GetTypeIdx is mostly used for computing the hash of DeclarationNames and
3656  // comparing keys of ASTDeclContextNameLookupTable.
3657  // If the type didn't come from the AST file use a specially marked index
3658  // so that any hash/key comparison fail since no such index is stored
3659  // in a AST file.
3660  if (I == TypeIdxs.end())
3661    return TypeIdx(-1);
3662  return I->second;
3663}
3664
3665unsigned ASTReader::getTotalNumCXXBaseSpecifiers() const {
3666  unsigned Result = 0;
3667  for (unsigned I = 0, N = Chain.size(); I != N; ++I)
3668    Result += Chain[I]->LocalNumCXXBaseSpecifiers;
3669
3670  return Result;
3671}
3672
3673TemplateArgumentLocInfo
3674ASTReader::GetTemplateArgumentLocInfo(PerFileData &F,
3675                                      TemplateArgument::ArgKind Kind,
3676                                      const RecordData &Record,
3677                                      unsigned &Index) {
3678  switch (Kind) {
3679  case TemplateArgument::Expression:
3680    return ReadExpr(F);
3681  case TemplateArgument::Type:
3682    return GetTypeSourceInfo(F, Record, Index);
3683  case TemplateArgument::Template: {
3684    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3685                                                                     Index);
3686    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3687    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3688                                   SourceLocation());
3689  }
3690  case TemplateArgument::TemplateExpansion: {
3691    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3692                                                                     Index);
3693    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3694    SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3695    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3696                                   EllipsisLoc);
3697  }
3698  case TemplateArgument::Null:
3699  case TemplateArgument::Integral:
3700  case TemplateArgument::Declaration:
3701  case TemplateArgument::Pack:
3702    return TemplateArgumentLocInfo();
3703  }
3704  llvm_unreachable("unexpected template argument loc");
3705  return TemplateArgumentLocInfo();
3706}
3707
3708TemplateArgumentLoc
3709ASTReader::ReadTemplateArgumentLoc(PerFileData &F,
3710                                   const RecordData &Record, unsigned &Index) {
3711  TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
3712
3713  if (Arg.getKind() == TemplateArgument::Expression) {
3714    if (Record[Index++]) // bool InfoHasSameExpr.
3715      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
3716  }
3717  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
3718                                                             Record, Index));
3719}
3720
3721Decl *ASTReader::GetExternalDecl(uint32_t ID) {
3722  return GetDecl(ID);
3723}
3724
3725uint64_t
3726ASTReader::GetCXXBaseSpecifiersOffset(serialization::CXXBaseSpecifiersID ID) {
3727  if (ID == 0)
3728    return 0;
3729
3730  --ID;
3731  uint64_t Offset = 0;
3732  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3733    if (ID < Chain[I]->LocalNumCXXBaseSpecifiers)
3734      return Offset + Chain[I]->CXXBaseSpecifiersOffsets[ID];
3735
3736    ID -= Chain[I]->LocalNumCXXBaseSpecifiers;
3737    Offset += Chain[I]->SizeInBits;
3738  }
3739
3740  assert(false && "CXXBaseSpecifiers not found");
3741  return 0;
3742}
3743
3744CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
3745  // Figure out which AST file contains this offset.
3746  PerFileData *F = 0;
3747  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3748    if (Offset < Chain[I]->SizeInBits) {
3749      F = Chain[I];
3750      break;
3751    }
3752
3753    Offset -= Chain[I]->SizeInBits;
3754  }
3755
3756  if (!F) {
3757    Error("Malformed AST file: C++ base specifiers at impossible offset");
3758    return 0;
3759  }
3760
3761  llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3762  SavedStreamPosition SavedPosition(Cursor);
3763  Cursor.JumpToBit(Offset);
3764  ReadingKindTracker ReadingKind(Read_Decl, *this);
3765  RecordData Record;
3766  unsigned Code = Cursor.ReadCode();
3767  unsigned RecCode = Cursor.ReadRecord(Code, Record);
3768  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
3769    Error("Malformed AST file: missing C++ base specifiers");
3770    return 0;
3771  }
3772
3773  unsigned Idx = 0;
3774  unsigned NumBases = Record[Idx++];
3775  void *Mem = Context->Allocate(sizeof(CXXBaseSpecifier) * NumBases);
3776  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
3777  for (unsigned I = 0; I != NumBases; ++I)
3778    Bases[I] = ReadCXXBaseSpecifier(*F, Record, Idx);
3779  return Bases;
3780}
3781
3782TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() {
3783  if (!DeclsLoaded[0]) {
3784    ReadDeclRecord(0, 1);
3785    if (DeserializationListener)
3786      DeserializationListener->DeclRead(1, DeclsLoaded[0]);
3787  }
3788
3789  return cast<TranslationUnitDecl>(DeclsLoaded[0]);
3790}
3791
3792Decl *ASTReader::GetDecl(DeclID ID) {
3793  if (ID == 0)
3794    return 0;
3795
3796  if (ID > DeclsLoaded.size()) {
3797    Error("declaration ID out-of-range for AST file");
3798    return 0;
3799  }
3800
3801  unsigned Index = ID - 1;
3802  if (!DeclsLoaded[Index]) {
3803    ReadDeclRecord(Index, ID);
3804    if (DeserializationListener)
3805      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
3806  }
3807
3808  return DeclsLoaded[Index];
3809}
3810
3811/// \brief Resolve the offset of a statement into a statement.
3812///
3813/// This operation will read a new statement from the external
3814/// source each time it is called, and is meant to be used via a
3815/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
3816Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
3817  // Switch case IDs are per Decl.
3818  ClearSwitchCaseIDs();
3819
3820  // Offset here is a global offset across the entire chain.
3821  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3822    PerFileData &F = *Chain[N - I - 1];
3823    if (Offset < F.SizeInBits) {
3824      // Since we know that this statement is part of a decl, make sure to use
3825      // the decl cursor to read it.
3826      F.DeclsCursor.JumpToBit(Offset);
3827      return ReadStmtFromStream(F);
3828    }
3829    Offset -= F.SizeInBits;
3830  }
3831  llvm_unreachable("Broken chain");
3832}
3833
3834bool ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
3835                                         bool (*isKindWeWant)(Decl::Kind),
3836                                         llvm::SmallVectorImpl<Decl*> &Decls) {
3837  assert(DC->hasExternalLexicalStorage() &&
3838         "DeclContext has no lexical decls in storage");
3839
3840  // There might be lexical decls in multiple parts of the chain, for the TU
3841  // at least.
3842  // DeclContextOffsets might reallocate as we load additional decls below,
3843  // so make a copy of the vector.
3844  DeclContextInfos Infos = DeclContextOffsets[DC];
3845  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3846       I != E; ++I) {
3847    // IDs can be 0 if this context doesn't contain declarations.
3848    if (!I->LexicalDecls)
3849      continue;
3850
3851    // Load all of the declaration IDs
3852    for (const KindDeclIDPair *ID = I->LexicalDecls,
3853                              *IDE = ID + I->NumLexicalDecls; ID != IDE; ++ID) {
3854      if (isKindWeWant && !isKindWeWant((Decl::Kind)ID->first))
3855        continue;
3856
3857      Decl *D = GetDecl(ID->second);
3858      assert(D && "Null decl in lexical decls");
3859      Decls.push_back(D);
3860    }
3861  }
3862
3863  ++NumLexicalDeclContextsRead;
3864  return false;
3865}
3866
3867DeclContext::lookup_result
3868ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
3869                                          DeclarationName Name) {
3870  assert(DC->hasExternalVisibleStorage() &&
3871         "DeclContext has no visible decls in storage");
3872  if (!Name)
3873    return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
3874                                      DeclContext::lookup_iterator(0));
3875
3876  llvm::SmallVector<NamedDecl *, 64> Decls;
3877  // There might be visible decls in multiple parts of the chain, for the TU
3878  // and namespaces. For any given name, the last available results replace
3879  // all earlier ones. For this reason, we walk in reverse.
3880  DeclContextInfos &Infos = DeclContextOffsets[DC];
3881  for (DeclContextInfos::reverse_iterator I = Infos.rbegin(), E = Infos.rend();
3882       I != E; ++I) {
3883    if (!I->NameLookupTableData)
3884      continue;
3885
3886    ASTDeclContextNameLookupTable *LookupTable =
3887        (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3888    ASTDeclContextNameLookupTable::iterator Pos = LookupTable->find(Name);
3889    if (Pos == LookupTable->end())
3890      continue;
3891
3892    ASTDeclContextNameLookupTrait::data_type Data = *Pos;
3893    for (; Data.first != Data.second; ++Data.first)
3894      Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3895    break;
3896  }
3897
3898  ++NumVisibleDeclContextsRead;
3899
3900  SetExternalVisibleDeclsForName(DC, Name, Decls);
3901  return const_cast<DeclContext*>(DC)->lookup(Name);
3902}
3903
3904void ASTReader::MaterializeVisibleDecls(const DeclContext *DC) {
3905  assert(DC->hasExternalVisibleStorage() &&
3906         "DeclContext has no visible decls in storage");
3907
3908  llvm::SmallVector<NamedDecl *, 64> Decls;
3909  // There might be visible decls in multiple parts of the chain, for the TU
3910  // and namespaces.
3911  DeclContextInfos &Infos = DeclContextOffsets[DC];
3912  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3913       I != E; ++I) {
3914    if (!I->NameLookupTableData)
3915      continue;
3916
3917    ASTDeclContextNameLookupTable *LookupTable =
3918        (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3919    for (ASTDeclContextNameLookupTable::item_iterator
3920           ItemI = LookupTable->item_begin(),
3921           ItemEnd = LookupTable->item_end() ; ItemI != ItemEnd; ++ItemI) {
3922      ASTDeclContextNameLookupTable::item_iterator::value_type Val
3923          = *ItemI;
3924      ASTDeclContextNameLookupTrait::data_type Data = Val.second;
3925      Decls.clear();
3926      for (; Data.first != Data.second; ++Data.first)
3927        Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3928      MaterializeVisibleDeclsForName(DC, Val.first, Decls);
3929    }
3930  }
3931}
3932
3933void ASTReader::PassInterestingDeclsToConsumer() {
3934  assert(Consumer);
3935  while (!InterestingDecls.empty()) {
3936    DeclGroupRef DG(InterestingDecls.front());
3937    InterestingDecls.pop_front();
3938    Consumer->HandleInterestingDecl(DG);
3939  }
3940}
3941
3942void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
3943  this->Consumer = Consumer;
3944
3945  if (!Consumer)
3946    return;
3947
3948  for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
3949    // Force deserialization of this decl, which will cause it to be queued for
3950    // passing to the consumer.
3951    GetDecl(ExternalDefinitions[I]);
3952  }
3953
3954  PassInterestingDeclsToConsumer();
3955}
3956
3957void ASTReader::PrintStats() {
3958  std::fprintf(stderr, "*** AST File Statistics:\n");
3959
3960  unsigned NumTypesLoaded
3961    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
3962                                      QualType());
3963  unsigned NumDeclsLoaded
3964    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3965                                      (Decl *)0);
3966  unsigned NumIdentifiersLoaded
3967    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3968                                            IdentifiersLoaded.end(),
3969                                            (IdentifierInfo *)0);
3970  unsigned NumSelectorsLoaded
3971    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3972                                          SelectorsLoaded.end(),
3973                                          Selector());
3974
3975  std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
3976  std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
3977  if (TotalNumSLocEntries)
3978    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
3979                 NumSLocEntriesRead, TotalNumSLocEntries,
3980                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
3981  if (!TypesLoaded.empty())
3982    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
3983                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3984                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3985  if (!DeclsLoaded.empty())
3986    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
3987                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3988                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
3989  if (!IdentifiersLoaded.empty())
3990    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
3991                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3992                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
3993  if (!SelectorsLoaded.empty())
3994    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
3995                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3996                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
3997  if (TotalNumStatements)
3998    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
3999                 NumStatementsRead, TotalNumStatements,
4000                 ((float)NumStatementsRead/TotalNumStatements * 100));
4001  if (TotalNumMacros)
4002    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
4003                 NumMacrosRead, TotalNumMacros,
4004                 ((float)NumMacrosRead/TotalNumMacros * 100));
4005  if (TotalLexicalDeclContexts)
4006    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
4007                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4008                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4009                  * 100));
4010  if (TotalVisibleDeclContexts)
4011    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
4012                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4013                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4014                  * 100));
4015  if (TotalNumMethodPoolEntries) {
4016    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
4017                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4018                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
4019                  * 100));
4020    std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
4021  }
4022  std::fprintf(stderr, "\n");
4023}
4024
4025void ASTReader::InitializeSema(Sema &S) {
4026  SemaObj = &S;
4027  S.ExternalSource = this;
4028
4029  // Makes sure any declarations that were deserialized "too early"
4030  // still get added to the identifier's declaration chains.
4031  for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4032    if (SemaObj->TUScope)
4033      SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
4034
4035    SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
4036  }
4037  PreloadedDecls.clear();
4038
4039  // If there were any tentative definitions, deserialize them and add
4040  // them to Sema's list of tentative definitions.
4041  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4042    VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
4043    SemaObj->TentativeDefinitions.push_back(Var);
4044  }
4045
4046  // If there were any unused file scoped decls, deserialize them and add to
4047  // Sema's list of unused file scoped decls.
4048  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4049    DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4050    SemaObj->UnusedFileScopedDecls.push_back(D);
4051  }
4052
4053  // If there were any locally-scoped external declarations,
4054  // deserialize them and add them to Sema's table of locally-scoped
4055  // external declarations.
4056  for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4057    NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4058    SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
4059  }
4060
4061  // If there were any ext_vector type declarations, deserialize them
4062  // and add them to Sema's vector of such declarations.
4063  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
4064    SemaObj->ExtVectorDecls.push_back(
4065                               cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
4066
4067  // FIXME: Do VTable uses and dynamic classes deserialize too much ?
4068  // Can we cut them down before writing them ?
4069
4070  // If there were any dynamic classes declarations, deserialize them
4071  // and add them to Sema's vector of such declarations.
4072  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
4073    SemaObj->DynamicClasses.push_back(
4074                               cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
4075
4076  // Load the offsets of the declarations that Sema references.
4077  // They will be lazily deserialized when needed.
4078  if (!SemaDeclRefs.empty()) {
4079    assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4080    SemaObj->StdNamespace = SemaDeclRefs[0];
4081    SemaObj->StdBadAlloc = SemaDeclRefs[1];
4082  }
4083
4084  for (PerFileData *F = FirstInSource; F; F = F->NextInSource) {
4085
4086    // If there are @selector references added them to its pool. This is for
4087    // implementation of -Wselector.
4088    if (!F->ReferencedSelectorsData.empty()) {
4089      unsigned int DataSize = F->ReferencedSelectorsData.size()-1;
4090      unsigned I = 0;
4091      while (I < DataSize) {
4092        Selector Sel = DecodeSelector(F->ReferencedSelectorsData[I++]);
4093        SourceLocation SelLoc = ReadSourceLocation(
4094                                    *F, F->ReferencedSelectorsData, I);
4095        SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
4096      }
4097    }
4098
4099    // If there were any pending implicit instantiations, deserialize them
4100    // and add them to Sema's queue of such instantiations.
4101    assert(F->PendingInstantiations.size() % 2 == 0 &&
4102           "Expected pairs of entries");
4103    for (unsigned Idx = 0, N = F->PendingInstantiations.size(); Idx < N;) {
4104      ValueDecl *D=cast<ValueDecl>(GetDecl(F->PendingInstantiations[Idx++]));
4105      SourceLocation Loc = ReadSourceLocation(*F, F->PendingInstantiations,Idx);
4106      SemaObj->PendingInstantiations.push_back(std::make_pair(D, Loc));
4107    }
4108  }
4109
4110  // The two special data sets below always come from the most recent PCH,
4111  // which is at the front of the chain.
4112  PerFileData &F = *Chain.front();
4113
4114  // If there were any weak undeclared identifiers, deserialize them and add to
4115  // Sema's list of weak undeclared identifiers.
4116  if (!WeakUndeclaredIdentifiers.empty()) {
4117    unsigned Idx = 0;
4118    for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
4119      IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4120      IdentifierInfo *AliasId= GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
4121      SourceLocation Loc = ReadSourceLocation(F, WeakUndeclaredIdentifiers,Idx);
4122      bool Used = WeakUndeclaredIdentifiers[Idx++];
4123      Sema::WeakInfo WI(AliasId, Loc);
4124      WI.setUsed(Used);
4125      SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
4126    }
4127  }
4128
4129  // If there were any VTable uses, deserialize the information and add it
4130  // to Sema's vector and map of VTable uses.
4131  if (!VTableUses.empty()) {
4132    unsigned Idx = 0;
4133    for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
4134      CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4135      SourceLocation Loc = ReadSourceLocation(F, VTableUses, Idx);
4136      bool DefinitionRequired = VTableUses[Idx++];
4137      SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
4138      SemaObj->VTablesUsed[Class] = DefinitionRequired;
4139    }
4140  }
4141
4142  if (!FPPragmaOptions.empty()) {
4143    assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4144    SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4145  }
4146
4147  if (!OpenCLExtensions.empty()) {
4148    unsigned I = 0;
4149#define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4150#include "clang/Basic/OpenCLExtensions.def"
4151
4152    assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4153  }
4154}
4155
4156IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4157  // Try to find this name within our on-disk hash tables. We start with the
4158  // most recent one, since that one contains the most up-to-date info.
4159  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4160    ASTIdentifierLookupTable *IdTable
4161        = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
4162    if (!IdTable)
4163      continue;
4164    std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
4165    ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
4166    if (Pos == IdTable->end())
4167      continue;
4168
4169    // Dereferencing the iterator has the effect of building the
4170    // IdentifierInfo node and populating it with the various
4171    // declarations it needs.
4172    return *Pos;
4173  }
4174  return 0;
4175}
4176
4177namespace clang {
4178  /// \brief An identifier-lookup iterator that enumerates all of the
4179  /// identifiers stored within a set of AST files.
4180  class ASTIdentifierIterator : public IdentifierIterator {
4181    /// \brief The AST reader whose identifiers are being enumerated.
4182    const ASTReader &Reader;
4183
4184    /// \brief The current index into the chain of AST files stored in
4185    /// the AST reader.
4186    unsigned Index;
4187
4188    /// \brief The current position within the identifier lookup table
4189    /// of the current AST file.
4190    ASTIdentifierLookupTable::key_iterator Current;
4191
4192    /// \brief The end position within the identifier lookup table of
4193    /// the current AST file.
4194    ASTIdentifierLookupTable::key_iterator End;
4195
4196  public:
4197    explicit ASTIdentifierIterator(const ASTReader &Reader);
4198
4199    virtual llvm::StringRef Next();
4200  };
4201}
4202
4203ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4204  : Reader(Reader), Index(Reader.Chain.size() - 1) {
4205  ASTIdentifierLookupTable *IdTable
4206    = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4207  Current = IdTable->key_begin();
4208  End = IdTable->key_end();
4209}
4210
4211llvm::StringRef ASTIdentifierIterator::Next() {
4212  while (Current == End) {
4213    // If we have exhausted all of our AST files, we're done.
4214    if (Index == 0)
4215      return llvm::StringRef();
4216
4217    --Index;
4218    ASTIdentifierLookupTable *IdTable
4219      = (ASTIdentifierLookupTable *)Reader.Chain[Index]->IdentifierLookupTable;
4220    Current = IdTable->key_begin();
4221    End = IdTable->key_end();
4222  }
4223
4224  // We have any identifiers remaining in the current AST file; return
4225  // the next one.
4226  std::pair<const char*, unsigned> Key = *Current;
4227  ++Current;
4228  return llvm::StringRef(Key.first, Key.second);
4229}
4230
4231IdentifierIterator *ASTReader::getIdentifiers() const {
4232  return new ASTIdentifierIterator(*this);
4233}
4234
4235std::pair<ObjCMethodList, ObjCMethodList>
4236ASTReader::ReadMethodPool(Selector Sel) {
4237  // Find this selector in a hash table. We want to find the most recent entry.
4238  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4239    PerFileData &F = *Chain[I];
4240    if (!F.SelectorLookupTable)
4241      continue;
4242
4243    ASTSelectorLookupTable *PoolTable
4244      = (ASTSelectorLookupTable*)F.SelectorLookupTable;
4245    ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
4246    if (Pos != PoolTable->end()) {
4247      ++NumSelectorsRead;
4248      // FIXME: Not quite happy with the statistics here. We probably should
4249      // disable this tracking when called via LoadSelector.
4250      // Also, should entries without methods count as misses?
4251      ++NumMethodPoolEntriesRead;
4252      ASTSelectorLookupTrait::data_type Data = *Pos;
4253      if (DeserializationListener)
4254        DeserializationListener->SelectorRead(Data.ID, Sel);
4255      return std::make_pair(Data.Instance, Data.Factory);
4256    }
4257  }
4258
4259  ++NumMethodPoolMisses;
4260  return std::pair<ObjCMethodList, ObjCMethodList>();
4261}
4262
4263void ASTReader::LoadSelector(Selector Sel) {
4264  // It would be complicated to avoid reading the methods anyway. So don't.
4265  ReadMethodPool(Sel);
4266}
4267
4268void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
4269  assert(ID && "Non-zero identifier ID required");
4270  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4271  IdentifiersLoaded[ID - 1] = II;
4272  if (DeserializationListener)
4273    DeserializationListener->IdentifierRead(ID, II);
4274}
4275
4276/// \brief Set the globally-visible declarations associated with the given
4277/// identifier.
4278///
4279/// If the AST reader is currently in a state where the given declaration IDs
4280/// cannot safely be resolved, they are queued until it is safe to resolve
4281/// them.
4282///
4283/// \param II an IdentifierInfo that refers to one or more globally-visible
4284/// declarations.
4285///
4286/// \param DeclIDs the set of declaration IDs with the name @p II that are
4287/// visible at global scope.
4288///
4289/// \param Nonrecursive should be true to indicate that the caller knows that
4290/// this call is non-recursive, and therefore the globally-visible declarations
4291/// will not be placed onto the pending queue.
4292void
4293ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4294                              const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
4295                                   bool Nonrecursive) {
4296  if (NumCurrentElementsDeserializing && !Nonrecursive) {
4297    PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4298    PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4299    PII.II = II;
4300    PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4301    return;
4302  }
4303
4304  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4305    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4306    if (SemaObj) {
4307      if (SemaObj->TUScope) {
4308        // Introduce this declaration into the translation-unit scope
4309        // and add it to the declaration chain for this identifier, so
4310        // that (unqualified) name lookup will find it.
4311        SemaObj->TUScope->AddDecl(D);
4312      }
4313      SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
4314    } else {
4315      // Queue this declaration so that it will be added to the
4316      // translation unit scope and identifier's declaration chain
4317      // once a Sema object is known.
4318      PreloadedDecls.push_back(D);
4319    }
4320  }
4321}
4322
4323IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) {
4324  if (ID == 0)
4325    return 0;
4326
4327  if (IdentifiersLoaded.empty()) {
4328    Error("no identifier table in AST file");
4329    return 0;
4330  }
4331
4332  assert(PP && "Forgot to set Preprocessor ?");
4333  ID -= 1;
4334  if (!IdentifiersLoaded[ID]) {
4335    unsigned Index = ID;
4336    const char *Str = 0;
4337    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4338      PerFileData *F = Chain[N - I - 1];
4339      if (Index < F->LocalNumIdentifiers) {
4340         uint32_t Offset = F->IdentifierOffsets[Index];
4341         Str = F->IdentifierTableData + Offset;
4342         break;
4343      }
4344      Index -= F->LocalNumIdentifiers;
4345    }
4346    assert(Str && "Broken Chain");
4347
4348    // All of the strings in the AST file are preceded by a 16-bit length.
4349    // Extract that 16-bit length to avoid having to execute strlen().
4350    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4351    //  unsigned integers.  This is important to avoid integer overflow when
4352    //  we cast them to 'unsigned'.
4353    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4354    unsigned StrLen = (((unsigned) StrLenPtr[0])
4355                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4356    IdentifiersLoaded[ID]
4357      = &PP->getIdentifierTable().get(Str, StrLen);
4358    if (DeserializationListener)
4359      DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4360  }
4361
4362  return IdentifiersLoaded[ID];
4363}
4364
4365void ASTReader::ReadSLocEntry(unsigned ID) {
4366  ReadSLocEntryRecord(ID);
4367}
4368
4369Selector ASTReader::DecodeSelector(unsigned ID) {
4370  if (ID == 0)
4371    return Selector();
4372
4373  if (ID > SelectorsLoaded.size()) {
4374    Error("selector ID out of range in AST file");
4375    return Selector();
4376  }
4377
4378  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4379    // Load this selector from the selector table.
4380    unsigned Idx = ID - 1;
4381    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
4382      PerFileData &F = *Chain[N - I - 1];
4383      if (Idx < F.LocalNumSelectors) {
4384        ASTSelectorLookupTrait Trait(*this);
4385        SelectorsLoaded[ID - 1] =
4386           Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
4387        if (DeserializationListener)
4388          DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
4389        break;
4390      }
4391      Idx -= F.LocalNumSelectors;
4392    }
4393  }
4394
4395  return SelectorsLoaded[ID - 1];
4396}
4397
4398Selector ASTReader::GetExternalSelector(uint32_t ID) {
4399  return DecodeSelector(ID);
4400}
4401
4402uint32_t ASTReader::GetNumExternalSelectors() {
4403  // ID 0 (the null selector) is considered an external selector.
4404  return getTotalNumSelectors() + 1;
4405}
4406
4407DeclarationName
4408ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
4409  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
4410  switch (Kind) {
4411  case DeclarationName::Identifier:
4412    return DeclarationName(GetIdentifierInfo(Record, Idx));
4413
4414  case DeclarationName::ObjCZeroArgSelector:
4415  case DeclarationName::ObjCOneArgSelector:
4416  case DeclarationName::ObjCMultiArgSelector:
4417    return DeclarationName(GetSelector(Record, Idx));
4418
4419  case DeclarationName::CXXConstructorName:
4420    return Context->DeclarationNames.getCXXConstructorName(
4421                          Context->getCanonicalType(GetType(Record[Idx++])));
4422
4423  case DeclarationName::CXXDestructorName:
4424    return Context->DeclarationNames.getCXXDestructorName(
4425                          Context->getCanonicalType(GetType(Record[Idx++])));
4426
4427  case DeclarationName::CXXConversionFunctionName:
4428    return Context->DeclarationNames.getCXXConversionFunctionName(
4429                          Context->getCanonicalType(GetType(Record[Idx++])));
4430
4431  case DeclarationName::CXXOperatorName:
4432    return Context->DeclarationNames.getCXXOperatorName(
4433                                       (OverloadedOperatorKind)Record[Idx++]);
4434
4435  case DeclarationName::CXXLiteralOperatorName:
4436    return Context->DeclarationNames.getCXXLiteralOperatorName(
4437                                       GetIdentifierInfo(Record, Idx));
4438
4439  case DeclarationName::CXXUsingDirective:
4440    return DeclarationName::getUsingDirectiveName();
4441  }
4442
4443  // Required to silence GCC warning
4444  return DeclarationName();
4445}
4446
4447void ASTReader::ReadDeclarationNameLoc(PerFileData &F,
4448                                       DeclarationNameLoc &DNLoc,
4449                                       DeclarationName Name,
4450                                      const RecordData &Record, unsigned &Idx) {
4451  switch (Name.getNameKind()) {
4452  case DeclarationName::CXXConstructorName:
4453  case DeclarationName::CXXDestructorName:
4454  case DeclarationName::CXXConversionFunctionName:
4455    DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
4456    break;
4457
4458  case DeclarationName::CXXOperatorName:
4459    DNLoc.CXXOperatorName.BeginOpNameLoc
4460        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4461    DNLoc.CXXOperatorName.EndOpNameLoc
4462        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4463    break;
4464
4465  case DeclarationName::CXXLiteralOperatorName:
4466    DNLoc.CXXLiteralOperatorName.OpNameLoc
4467        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4468    break;
4469
4470  case DeclarationName::Identifier:
4471  case DeclarationName::ObjCZeroArgSelector:
4472  case DeclarationName::ObjCOneArgSelector:
4473  case DeclarationName::ObjCMultiArgSelector:
4474  case DeclarationName::CXXUsingDirective:
4475    break;
4476  }
4477}
4478
4479void ASTReader::ReadDeclarationNameInfo(PerFileData &F,
4480                                        DeclarationNameInfo &NameInfo,
4481                                      const RecordData &Record, unsigned &Idx) {
4482  NameInfo.setName(ReadDeclarationName(Record, Idx));
4483  NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
4484  DeclarationNameLoc DNLoc;
4485  ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
4486  NameInfo.setInfo(DNLoc);
4487}
4488
4489void ASTReader::ReadQualifierInfo(PerFileData &F, QualifierInfo &Info,
4490                                  const RecordData &Record, unsigned &Idx) {
4491  Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
4492  unsigned NumTPLists = Record[Idx++];
4493  Info.NumTemplParamLists = NumTPLists;
4494  if (NumTPLists) {
4495    Info.TemplParamLists = new (*Context) TemplateParameterList*[NumTPLists];
4496    for (unsigned i=0; i != NumTPLists; ++i)
4497      Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
4498  }
4499}
4500
4501TemplateName
4502ASTReader::ReadTemplateName(PerFileData &F, const RecordData &Record,
4503                            unsigned &Idx) {
4504  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
4505  switch (Kind) {
4506  case TemplateName::Template:
4507    return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
4508
4509  case TemplateName::OverloadedTemplate: {
4510    unsigned size = Record[Idx++];
4511    UnresolvedSet<8> Decls;
4512    while (size--)
4513      Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
4514
4515    return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
4516  }
4517
4518  case TemplateName::QualifiedTemplate: {
4519    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4520    bool hasTemplKeyword = Record[Idx++];
4521    TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
4522    return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
4523  }
4524
4525  case TemplateName::DependentTemplate: {
4526    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
4527    if (Record[Idx++])  // isIdentifier
4528      return Context->getDependentTemplateName(NNS,
4529                                               GetIdentifierInfo(Record, Idx));
4530    return Context->getDependentTemplateName(NNS,
4531                                         (OverloadedOperatorKind)Record[Idx++]);
4532  }
4533
4534  case TemplateName::SubstTemplateTemplateParmPack: {
4535    TemplateTemplateParmDecl *Param
4536      = cast_or_null<TemplateTemplateParmDecl>(GetDecl(Record[Idx++]));
4537    if (!Param)
4538      return TemplateName();
4539
4540    TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
4541    if (ArgPack.getKind() != TemplateArgument::Pack)
4542      return TemplateName();
4543
4544    return Context->getSubstTemplateTemplateParmPack(Param, ArgPack);
4545  }
4546  }
4547
4548  assert(0 && "Unhandled template name kind!");
4549  return TemplateName();
4550}
4551
4552TemplateArgument
4553ASTReader::ReadTemplateArgument(PerFileData &F,
4554                                const RecordData &Record, unsigned &Idx) {
4555  TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
4556  switch (Kind) {
4557  case TemplateArgument::Null:
4558    return TemplateArgument();
4559  case TemplateArgument::Type:
4560    return TemplateArgument(GetType(Record[Idx++]));
4561  case TemplateArgument::Declaration:
4562    return TemplateArgument(GetDecl(Record[Idx++]));
4563  case TemplateArgument::Integral: {
4564    llvm::APSInt Value = ReadAPSInt(Record, Idx);
4565    QualType T = GetType(Record[Idx++]);
4566    return TemplateArgument(Value, T);
4567  }
4568  case TemplateArgument::Template:
4569    return TemplateArgument(ReadTemplateName(F, Record, Idx));
4570  case TemplateArgument::TemplateExpansion: {
4571    TemplateName Name = ReadTemplateName(F, Record, Idx);
4572    llvm::Optional<unsigned> NumTemplateExpansions;
4573    if (unsigned NumExpansions = Record[Idx++])
4574      NumTemplateExpansions = NumExpansions - 1;
4575    return TemplateArgument(Name, NumTemplateExpansions);
4576  }
4577  case TemplateArgument::Expression:
4578    return TemplateArgument(ReadExpr(F));
4579  case TemplateArgument::Pack: {
4580    unsigned NumArgs = Record[Idx++];
4581    TemplateArgument *Args = new (*Context) TemplateArgument[NumArgs];
4582    for (unsigned I = 0; I != NumArgs; ++I)
4583      Args[I] = ReadTemplateArgument(F, Record, Idx);
4584    return TemplateArgument(Args, NumArgs);
4585  }
4586  }
4587
4588  assert(0 && "Unhandled template argument kind!");
4589  return TemplateArgument();
4590}
4591
4592TemplateParameterList *
4593ASTReader::ReadTemplateParameterList(PerFileData &F,
4594                                     const RecordData &Record, unsigned &Idx) {
4595  SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
4596  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
4597  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
4598
4599  unsigned NumParams = Record[Idx++];
4600  llvm::SmallVector<NamedDecl *, 16> Params;
4601  Params.reserve(NumParams);
4602  while (NumParams--)
4603    Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
4604
4605  TemplateParameterList* TemplateParams =
4606    TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
4607                                  Params.data(), Params.size(), RAngleLoc);
4608  return TemplateParams;
4609}
4610
4611void
4612ASTReader::
4613ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
4614                         PerFileData &F, const RecordData &Record,
4615                         unsigned &Idx) {
4616  unsigned NumTemplateArgs = Record[Idx++];
4617  TemplArgs.reserve(NumTemplateArgs);
4618  while (NumTemplateArgs--)
4619    TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
4620}
4621
4622/// \brief Read a UnresolvedSet structure.
4623void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
4624                                  const RecordData &Record, unsigned &Idx) {
4625  unsigned NumDecls = Record[Idx++];
4626  while (NumDecls--) {
4627    NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
4628    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
4629    Set.addDecl(D, AS);
4630  }
4631}
4632
4633CXXBaseSpecifier
4634ASTReader::ReadCXXBaseSpecifier(PerFileData &F,
4635                                const RecordData &Record, unsigned &Idx) {
4636  bool isVirtual = static_cast<bool>(Record[Idx++]);
4637  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
4638  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
4639  bool inheritConstructors = static_cast<bool>(Record[Idx++]);
4640  TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
4641  SourceRange Range = ReadSourceRange(F, Record, Idx);
4642  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
4643  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
4644                          EllipsisLoc);
4645  Result.setInheritConstructors(inheritConstructors);
4646  return Result;
4647}
4648
4649std::pair<CXXCtorInitializer **, unsigned>
4650ASTReader::ReadCXXCtorInitializers(PerFileData &F, const RecordData &Record,
4651                                   unsigned &Idx) {
4652  CXXCtorInitializer **CtorInitializers = 0;
4653  unsigned NumInitializers = Record[Idx++];
4654  if (NumInitializers) {
4655    ASTContext &C = *getContext();
4656
4657    CtorInitializers
4658        = new (C) CXXCtorInitializer*[NumInitializers];
4659    for (unsigned i=0; i != NumInitializers; ++i) {
4660      TypeSourceInfo *BaseClassInfo = 0;
4661      bool IsBaseVirtual = false;
4662      FieldDecl *Member = 0;
4663      IndirectFieldDecl *IndirectMember = 0;
4664
4665      bool IsBaseInitializer = Record[Idx++];
4666      if (IsBaseInitializer) {
4667        BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
4668        IsBaseVirtual = Record[Idx++];
4669      } else {
4670        bool IsIndirectMemberInitializer = Record[Idx++];
4671        if (IsIndirectMemberInitializer)
4672          IndirectMember = cast<IndirectFieldDecl>(GetDecl(Record[Idx++]));
4673        else
4674          Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
4675      }
4676      SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
4677      Expr *Init = ReadExpr(F);
4678      SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
4679      SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
4680      bool IsWritten = Record[Idx++];
4681      unsigned SourceOrderOrNumArrayIndices;
4682      llvm::SmallVector<VarDecl *, 8> Indices;
4683      if (IsWritten) {
4684        SourceOrderOrNumArrayIndices = Record[Idx++];
4685      } else {
4686        SourceOrderOrNumArrayIndices = Record[Idx++];
4687        Indices.reserve(SourceOrderOrNumArrayIndices);
4688        for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
4689          Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
4690      }
4691
4692      CXXCtorInitializer *BOMInit;
4693      if (IsBaseInitializer) {
4694        BOMInit = new (C) CXXCtorInitializer(C, BaseClassInfo, IsBaseVirtual,
4695                                             LParenLoc, Init, RParenLoc,
4696                                             MemberOrEllipsisLoc);
4697      } else if (IsWritten) {
4698        if (Member)
4699          BOMInit = new (C) CXXCtorInitializer(C, Member, MemberOrEllipsisLoc,
4700                                               LParenLoc, Init, RParenLoc);
4701        else
4702          BOMInit = new (C) CXXCtorInitializer(C, IndirectMember,
4703                                               MemberOrEllipsisLoc, LParenLoc,
4704                                               Init, RParenLoc);
4705      } else {
4706        BOMInit = CXXCtorInitializer::Create(C, Member, MemberOrEllipsisLoc,
4707                                             LParenLoc, Init, RParenLoc,
4708                                             Indices.data(), Indices.size());
4709      }
4710
4711      if (IsWritten)
4712        BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
4713      CtorInitializers[i] = BOMInit;
4714    }
4715  }
4716
4717  return std::make_pair(CtorInitializers, NumInitializers);
4718}
4719
4720NestedNameSpecifier *
4721ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
4722  unsigned N = Record[Idx++];
4723  NestedNameSpecifier *NNS = 0, *Prev = 0;
4724  for (unsigned I = 0; I != N; ++I) {
4725    NestedNameSpecifier::SpecifierKind Kind
4726      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
4727    switch (Kind) {
4728    case NestedNameSpecifier::Identifier: {
4729      IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
4730      NNS = NestedNameSpecifier::Create(*Context, Prev, II);
4731      break;
4732    }
4733
4734    case NestedNameSpecifier::Namespace: {
4735      NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
4736      NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
4737      break;
4738    }
4739
4740    case NestedNameSpecifier::NamespaceAlias: {
4741      NamespaceAliasDecl *Alias
4742        = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++]));
4743      NNS = NestedNameSpecifier::Create(*Context, Prev, Alias);
4744      break;
4745    }
4746
4747    case NestedNameSpecifier::TypeSpec:
4748    case NestedNameSpecifier::TypeSpecWithTemplate: {
4749      const Type *T = GetType(Record[Idx++]).getTypePtrOrNull();
4750      if (!T)
4751        return 0;
4752
4753      bool Template = Record[Idx++];
4754      NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
4755      break;
4756    }
4757
4758    case NestedNameSpecifier::Global: {
4759      NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
4760      // No associated value, and there can't be a prefix.
4761      break;
4762    }
4763    }
4764    Prev = NNS;
4765  }
4766  return NNS;
4767}
4768
4769NestedNameSpecifierLoc
4770ASTReader::ReadNestedNameSpecifierLoc(PerFileData &F, const RecordData &Record,
4771                                      unsigned &Idx) {
4772  unsigned N = Record[Idx++];
4773  NestedNameSpecifierLocBuilder Builder;
4774  for (unsigned I = 0; I != N; ++I) {
4775    NestedNameSpecifier::SpecifierKind Kind
4776      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
4777    switch (Kind) {
4778    case NestedNameSpecifier::Identifier: {
4779      IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
4780      SourceRange Range = ReadSourceRange(F, Record, Idx);
4781      Builder.Extend(*Context, II, Range.getBegin(), Range.getEnd());
4782      break;
4783    }
4784
4785    case NestedNameSpecifier::Namespace: {
4786      NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
4787      SourceRange Range = ReadSourceRange(F, Record, Idx);
4788      Builder.Extend(*Context, NS, Range.getBegin(), Range.getEnd());
4789      break;
4790    }
4791
4792    case NestedNameSpecifier::NamespaceAlias: {
4793      NamespaceAliasDecl *Alias
4794        = cast<NamespaceAliasDecl>(GetDecl(Record[Idx++]));
4795      SourceRange Range = ReadSourceRange(F, Record, Idx);
4796      Builder.Extend(*Context, Alias, Range.getBegin(), Range.getEnd());
4797      break;
4798    }
4799
4800    case NestedNameSpecifier::TypeSpec:
4801    case NestedNameSpecifier::TypeSpecWithTemplate: {
4802      bool Template = Record[Idx++];
4803      TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
4804      if (!T)
4805        return NestedNameSpecifierLoc();
4806      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
4807
4808      // FIXME: 'template' keyword location not saved anywhere, so we fake it.
4809      Builder.Extend(*Context,
4810                     Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
4811                     T->getTypeLoc(), ColonColonLoc);
4812      break;
4813    }
4814
4815    case NestedNameSpecifier::Global: {
4816      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
4817      Builder.MakeGlobal(*Context, ColonColonLoc);
4818      break;
4819    }
4820    }
4821  }
4822
4823  return Builder.getWithLocInContext(*Context);
4824}
4825
4826SourceRange
4827ASTReader::ReadSourceRange(PerFileData &F, const RecordData &Record,
4828                           unsigned &Idx) {
4829  SourceLocation beg = ReadSourceLocation(F, Record, Idx);
4830  SourceLocation end = ReadSourceLocation(F, Record, Idx);
4831  return SourceRange(beg, end);
4832}
4833
4834/// \brief Read an integral value
4835llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
4836  unsigned BitWidth = Record[Idx++];
4837  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
4838  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
4839  Idx += NumWords;
4840  return Result;
4841}
4842
4843/// \brief Read a signed integral value
4844llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
4845  bool isUnsigned = Record[Idx++];
4846  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
4847}
4848
4849/// \brief Read a floating-point value
4850llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
4851  return llvm::APFloat(ReadAPInt(Record, Idx));
4852}
4853
4854// \brief Read a string
4855std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
4856  unsigned Len = Record[Idx++];
4857  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
4858  Idx += Len;
4859  return Result;
4860}
4861
4862CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record,
4863                                          unsigned &Idx) {
4864  CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
4865  return CXXTemporary::Create(*Context, Decl);
4866}
4867
4868DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
4869  return Diag(SourceLocation(), DiagID);
4870}
4871
4872DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
4873  return Diags.Report(Loc, DiagID);
4874}
4875
4876/// \brief Retrieve the identifier table associated with the
4877/// preprocessor.
4878IdentifierTable &ASTReader::getIdentifierTable() {
4879  assert(PP && "Forgot to set Preprocessor ?");
4880  return PP->getIdentifierTable();
4881}
4882
4883/// \brief Record that the given ID maps to the given switch-case
4884/// statement.
4885void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
4886  assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
4887  SwitchCaseStmts[ID] = SC;
4888}
4889
4890/// \brief Retrieve the switch-case statement with the given ID.
4891SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
4892  assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
4893  return SwitchCaseStmts[ID];
4894}
4895
4896void ASTReader::ClearSwitchCaseIDs() {
4897  SwitchCaseStmts.clear();
4898}
4899
4900void ASTReader::FinishedDeserializing() {
4901  assert(NumCurrentElementsDeserializing &&
4902         "FinishedDeserializing not paired with StartedDeserializing");
4903  if (NumCurrentElementsDeserializing == 1) {
4904    // If any identifiers with corresponding top-level declarations have
4905    // been loaded, load those declarations now.
4906    while (!PendingIdentifierInfos.empty()) {
4907      SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
4908                              PendingIdentifierInfos.front().DeclIDs, true);
4909      PendingIdentifierInfos.pop_front();
4910    }
4911
4912    // Ready to load previous declarations of Decls that were delayed.
4913    while (!PendingPreviousDecls.empty()) {
4914      loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
4915                                PendingPreviousDecls.front().second);
4916      PendingPreviousDecls.pop_front();
4917    }
4918
4919    // We are not in recursive loading, so it's safe to pass the "interesting"
4920    // decls to the consumer.
4921    if (Consumer)
4922      PassInterestingDeclsToConsumer();
4923
4924    assert(PendingForwardRefs.size() == 0 &&
4925           "Some forward refs did not get linked to the definition!");
4926  }
4927  --NumCurrentElementsDeserializing;
4928}
4929
4930ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
4931                     const char *isysroot, bool DisableValidation,
4932                     bool DisableStatCache)
4933  : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
4934    SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
4935    Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
4936    Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
4937    DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
4938    NumSLocEntriesRead(0), TotalNumSLocEntries(0), NextSLocOffset(0),
4939    NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
4940    TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
4941    NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
4942    NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
4943    NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
4944    NumCurrentElementsDeserializing(0)
4945{
4946  RelocatablePCH = false;
4947}
4948
4949ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
4950                     Diagnostic &Diags, const char *isysroot,
4951                     bool DisableValidation, bool DisableStatCache)
4952  : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
4953    Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
4954    isysroot(isysroot), DisableValidation(DisableValidation),
4955    DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
4956    NumSLocEntriesRead(0), TotalNumSLocEntries(0),
4957    NextSLocOffset(0), NumStatementsRead(0), TotalNumStatements(0),
4958    NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
4959    NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
4960    TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
4961    TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
4962    TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
4963  RelocatablePCH = false;
4964}
4965
4966ASTReader::~ASTReader() {
4967  for (unsigned i = 0, e = Chain.size(); i != e; ++i)
4968    delete Chain[e - i - 1];
4969  // Delete all visible decl lookup tables
4970  for (DeclContextOffsetsMap::iterator I = DeclContextOffsets.begin(),
4971                                       E = DeclContextOffsets.end();
4972       I != E; ++I) {
4973    for (DeclContextInfos::iterator J = I->second.begin(), F = I->second.end();
4974         J != F; ++J) {
4975      if (J->NameLookupTableData)
4976        delete static_cast<ASTDeclContextNameLookupTable*>(
4977            J->NameLookupTableData);
4978    }
4979  }
4980  for (DeclContextVisibleUpdatesPending::iterator
4981           I = PendingVisibleUpdates.begin(),
4982           E = PendingVisibleUpdates.end();
4983       I != E; ++I) {
4984    for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
4985                                             F = I->second.end();
4986         J != F; ++J)
4987      delete static_cast<ASTDeclContextNameLookupTable*>(*J);
4988  }
4989}
4990
4991ASTReader::PerFileData::PerFileData(ASTFileType Ty)
4992  : Type(Ty), SizeInBits(0), LocalNumSLocEntries(0), SLocOffsets(0), LocalSLocSize(0),
4993    LocalNumIdentifiers(0), IdentifierOffsets(0), IdentifierTableData(0),
4994    IdentifierLookupTable(0), LocalNumMacroDefinitions(0),
4995    MacroDefinitionOffsets(0),
4996    LocalNumHeaderFileInfos(0), HeaderFileInfoTableData(0),
4997    HeaderFileInfoTable(0),
4998    LocalNumSelectors(0), SelectorOffsets(0),
4999    SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
5000    DeclOffsets(0), LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0),
5001    LocalNumTypes(0), TypeOffsets(0), StatCache(0),
5002    NumPreallocatedPreprocessingEntities(0), NextInSource(0)
5003{}
5004
5005ASTReader::PerFileData::~PerFileData() {
5006  delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable);
5007  delete static_cast<HeaderFileInfoLookupTable *>(HeaderFileInfoTable);
5008  delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable);
5009}
5010