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