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