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