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