]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Frontend/PCHReader.cpp
Update clang to r94309.
[FreeBSD/FreeBSD.git] / lib / Frontend / PCHReader.cpp
1 //===--- PCHReader.cpp - Precompiled Headers 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 PCHReader class, which reads a precompiled header.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Frontend/PCHReader.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/Type.h"
22 #include "clang/AST/TypeLocVisitor.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Lex/HeaderSearch.h"
26 #include "clang/Basic/OnDiskHashTable.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/SourceManagerInternals.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/Version.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Bitcode/BitstreamReader.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/System/Path.h"
37 #include <algorithm>
38 #include <iterator>
39 #include <cstdio>
40 #include <sys/stat.h>
41 using namespace clang;
42
43 //===----------------------------------------------------------------------===//
44 // PCH reader validator implementation
45 //===----------------------------------------------------------------------===//
46
47 PCHReaderListener::~PCHReaderListener() {}
48
49 bool
50 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
51   const LangOptions &PPLangOpts = PP.getLangOptions();
52 #define PARSE_LANGOPT_BENIGN(Option)
53 #define PARSE_LANGOPT_IMPORTANT(Option, DiagID)                    \
54   if (PPLangOpts.Option != LangOpts.Option) {                      \
55     Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option;   \
56     return true;                                                   \
57   }
58
59   PARSE_LANGOPT_BENIGN(Trigraphs);
60   PARSE_LANGOPT_BENIGN(BCPLComment);
61   PARSE_LANGOPT_BENIGN(DollarIdents);
62   PARSE_LANGOPT_BENIGN(AsmPreprocessor);
63   PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
64   PARSE_LANGOPT_BENIGN(ImplicitInt);
65   PARSE_LANGOPT_BENIGN(Digraphs);
66   PARSE_LANGOPT_BENIGN(HexFloats);
67   PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
68   PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
69   PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
70   PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
71   PARSE_LANGOPT_BENIGN(CXXOperatorName);
72   PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
73   PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
74   PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
75   PARSE_LANGOPT_BENIGN(PascalStrings);
76   PARSE_LANGOPT_BENIGN(WritableStrings);
77   PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
78                           diag::warn_pch_lax_vector_conversions);
79   PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
80   PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
81   PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
82   PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
83   PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
84   PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
85                           diag::warn_pch_thread_safe_statics);
86   PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
87   PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
88   PARSE_LANGOPT_BENIGN(EmitAllDecls);
89   PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
90   PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
91   PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
92                           diag::warn_pch_heinous_extensions);
93   // FIXME: Most of the options below are benign if the macro wasn't
94   // used. Unfortunately, this means that a PCH compiled without
95   // optimization can't be used with optimization turned on, even
96   // though the only thing that changes is whether __OPTIMIZE__ was
97   // defined... but if __OPTIMIZE__ never showed up in the header, it
98   // doesn't matter. We could consider making this some special kind
99   // of check.
100   PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
101   PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
102   PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
103   PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
104   PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
105   PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
106   PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
107   PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
108   PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
109   if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
110     Reader.Diag(diag::warn_pch_gc_mode)
111       << LangOpts.getGCMode() << PPLangOpts.getGCMode();
112     return true;
113   }
114   PARSE_LANGOPT_BENIGN(getVisibilityMode());
115   PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
116                           diag::warn_pch_stack_protector);
117   PARSE_LANGOPT_BENIGN(InstantiationDepth);
118   PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
119   PARSE_LANGOPT_BENIGN(CatchUndefined);
120   PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
121 #undef PARSE_LANGOPT_IRRELEVANT
122 #undef PARSE_LANGOPT_BENIGN
123
124   return false;
125 }
126
127 bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
128   if (Triple == PP.getTargetInfo().getTriple().str())
129     return false;
130
131   Reader.Diag(diag::warn_pch_target_triple)
132     << Triple << PP.getTargetInfo().getTriple().str();
133   return true;
134 }
135
136 bool PCHValidator::ReadPredefinesBuffer(llvm::StringRef PCHPredef,
137                                         FileID PCHBufferID,
138                                         llvm::StringRef OriginalFileName,
139                                         std::string &SuggestedPredefines) {
140   // We are in the context of an implicit include, so the predefines buffer will
141   // have a #include entry for the PCH file itself (as normalized by the
142   // preprocessor initialization). Find it and skip over it in the checking
143   // below.
144   llvm::SmallString<256> PCHInclude;
145   PCHInclude += "#include \"";
146   PCHInclude += NormalizeDashIncludePath(OriginalFileName);
147   PCHInclude += "\"\n";
148   std::pair<llvm::StringRef,llvm::StringRef> Split =
149     llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
150   llvm::StringRef Left =  Split.first, Right = Split.second;
151   assert(Left != PP.getPredefines() && "Missing PCH include entry!");
152
153   // If the predefines is equal to the joined left and right halves, we're done!
154   if (Left.size() + Right.size() == PCHPredef.size() &&
155       PCHPredef.startswith(Left) && PCHPredef.endswith(Right))
156     return false;
157
158   SourceManager &SourceMgr = PP.getSourceManager();
159
160   // The predefines buffers are different. Determine what the differences are,
161   // and whether they require us to reject the PCH file.
162   llvm::SmallVector<llvm::StringRef, 8> PCHLines;
163   PCHPredef.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
164
165   llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
166   Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
167   Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
168
169   // Sort both sets of predefined buffer lines, since we allow some extra
170   // definitions and they may appear at any point in the output.
171   std::sort(CmdLineLines.begin(), CmdLineLines.end());
172   std::sort(PCHLines.begin(), PCHLines.end());
173
174   // Determine which predefines that were used to build the PCH file are missing
175   // from the command line.
176   std::vector<llvm::StringRef> MissingPredefines;
177   std::set_difference(PCHLines.begin(), PCHLines.end(),
178                       CmdLineLines.begin(), CmdLineLines.end(),
179                       std::back_inserter(MissingPredefines));
180
181   bool MissingDefines = false;
182   bool ConflictingDefines = false;
183   for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
184     llvm::StringRef Missing = MissingPredefines[I];
185     if (!Missing.startswith("#define ")) {
186       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
187       return true;
188     }
189
190     // This is a macro definition. Determine the name of the macro we're
191     // defining.
192     std::string::size_type StartOfMacroName = strlen("#define ");
193     std::string::size_type EndOfMacroName
194       = Missing.find_first_of("( \n\r", StartOfMacroName);
195     assert(EndOfMacroName != std::string::npos &&
196            "Couldn't find the end of the macro name");
197     llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
198
199     // Determine whether this macro was given a different definition on the
200     // command line.
201     std::string MacroDefStart = "#define " + MacroName.str();
202     std::string::size_type MacroDefLen = MacroDefStart.size();
203     llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
204       = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
205                          MacroDefStart);
206     for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
207       if (!ConflictPos->startswith(MacroDefStart)) {
208         // Different macro; we're done.
209         ConflictPos = CmdLineLines.end();
210         break;
211       }
212
213       assert(ConflictPos->size() > MacroDefLen &&
214              "Invalid #define in predefines buffer?");
215       if ((*ConflictPos)[MacroDefLen] != ' ' &&
216           (*ConflictPos)[MacroDefLen] != '(')
217         continue; // Longer macro name; keep trying.
218
219       // We found a conflicting macro definition.
220       break;
221     }
222
223     if (ConflictPos != CmdLineLines.end()) {
224       Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
225           << MacroName;
226
227       // Show the definition of this macro within the PCH file.
228       llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
229       assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
230       SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
231         .getFileLocWithOffset(Offset);
232       Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
233
234       ConflictingDefines = true;
235       continue;
236     }
237
238     // If the macro doesn't conflict, then we'll just pick up the macro
239     // definition from the PCH file. Warn the user that they made a mistake.
240     if (ConflictingDefines)
241       continue; // Don't complain if there are already conflicting defs
242
243     if (!MissingDefines) {
244       Reader.Diag(diag::warn_cmdline_missing_macro_defs);
245       MissingDefines = true;
246     }
247
248     // Show the definition of this macro within the PCH file.
249     llvm::StringRef::size_type Offset = PCHPredef.find(Missing);
250     assert(Offset != llvm::StringRef::npos && "Unable to find macro!");
251     SourceLocation PCHMissingLoc = SourceMgr.getLocForStartOfFile(PCHBufferID)
252       .getFileLocWithOffset(Offset);
253     Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
254   }
255
256   if (ConflictingDefines)
257     return true;
258
259   // Determine what predefines were introduced based on command-line
260   // parameters that were not present when building the PCH
261   // file. Extra #defines are okay, so long as the identifiers being
262   // defined were not used within the precompiled header.
263   std::vector<llvm::StringRef> ExtraPredefines;
264   std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
265                       PCHLines.begin(), PCHLines.end(),
266                       std::back_inserter(ExtraPredefines));
267   for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
268     llvm::StringRef &Extra = ExtraPredefines[I];
269     if (!Extra.startswith("#define ")) {
270       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
271       return true;
272     }
273
274     // This is an extra macro definition. Determine the name of the
275     // macro we're defining.
276     std::string::size_type StartOfMacroName = strlen("#define ");
277     std::string::size_type EndOfMacroName
278       = Extra.find_first_of("( \n\r", StartOfMacroName);
279     assert(EndOfMacroName != std::string::npos &&
280            "Couldn't find the end of the macro name");
281     llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
282
283     // Check whether this name was used somewhere in the PCH file. If
284     // so, defining it as a macro could change behavior, so we reject
285     // the PCH file.
286     if (IdentifierInfo *II = Reader.get(MacroName)) {
287       Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
288       return true;
289     }
290
291     // Add this definition to the suggested predefines buffer.
292     SuggestedPredefines += Extra;
293     SuggestedPredefines += '\n';
294   }
295
296   // If we get here, it's because the predefines buffer had compatible
297   // contents. Accept the PCH file.
298   return false;
299 }
300
301 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
302   PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
303 }
304
305 void PCHValidator::ReadCounter(unsigned Value) {
306   PP.setCounterValue(Value);
307 }
308
309 //===----------------------------------------------------------------------===//
310 // PCH reader implementation
311 //===----------------------------------------------------------------------===//
312
313 PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
314                      const char *isysroot)
315   : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
316     FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
317     SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
318     IdentifierTableData(0), IdentifierLookupTable(0),
319     IdentifierOffsets(0),
320     MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
321     TotalSelectorsInMethodPool(0), SelectorOffsets(0),
322     TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
323     NumStatHits(0), NumStatMisses(0),
324     NumSLocEntriesRead(0), NumStatementsRead(0),
325     NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
326     NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
327     CurrentlyLoadingTypeOrDecl(0) {
328   RelocatablePCH = false;
329 }
330
331 PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
332                      Diagnostic &Diags, const char *isysroot)
333   : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
334     SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
335     IdentifierTableData(0), IdentifierLookupTable(0),
336     IdentifierOffsets(0),
337     MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
338     TotalSelectorsInMethodPool(0), SelectorOffsets(0),
339     TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
340     NumStatHits(0), NumStatMisses(0),
341     NumSLocEntriesRead(0), NumStatementsRead(0),
342     NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
343     NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
344     CurrentlyLoadingTypeOrDecl(0) {
345   RelocatablePCH = false;
346 }
347
348 PCHReader::~PCHReader() {}
349
350 Expr *PCHReader::ReadDeclExpr() {
351   return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
352 }
353
354 Expr *PCHReader::ReadTypeExpr() {
355   return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
356 }
357
358
359 namespace {
360 class PCHMethodPoolLookupTrait {
361   PCHReader &Reader;
362
363 public:
364   typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
365
366   typedef Selector external_key_type;
367   typedef external_key_type internal_key_type;
368
369   explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
370
371   static bool EqualKey(const internal_key_type& a,
372                        const internal_key_type& b) {
373     return a == b;
374   }
375
376   static unsigned ComputeHash(Selector Sel) {
377     unsigned N = Sel.getNumArgs();
378     if (N == 0)
379       ++N;
380     unsigned R = 5381;
381     for (unsigned I = 0; I != N; ++I)
382       if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
383         R = llvm::HashString(II->getName(), R);
384     return R;
385   }
386
387   // This hopefully will just get inlined and removed by the optimizer.
388   static const internal_key_type&
389   GetInternalKey(const external_key_type& x) { return x; }
390
391   static std::pair<unsigned, unsigned>
392   ReadKeyDataLength(const unsigned char*& d) {
393     using namespace clang::io;
394     unsigned KeyLen = ReadUnalignedLE16(d);
395     unsigned DataLen = ReadUnalignedLE16(d);
396     return std::make_pair(KeyLen, DataLen);
397   }
398
399   internal_key_type ReadKey(const unsigned char* d, unsigned) {
400     using namespace clang::io;
401     SelectorTable &SelTable = Reader.getContext()->Selectors;
402     unsigned N = ReadUnalignedLE16(d);
403     IdentifierInfo *FirstII
404       = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
405     if (N == 0)
406       return SelTable.getNullarySelector(FirstII);
407     else if (N == 1)
408       return SelTable.getUnarySelector(FirstII);
409
410     llvm::SmallVector<IdentifierInfo *, 16> Args;
411     Args.push_back(FirstII);
412     for (unsigned I = 1; I != N; ++I)
413       Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
414
415     return SelTable.getSelector(N, Args.data());
416   }
417
418   data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
419     using namespace clang::io;
420     unsigned NumInstanceMethods = ReadUnalignedLE16(d);
421     unsigned NumFactoryMethods = ReadUnalignedLE16(d);
422
423     data_type Result;
424
425     // Load instance methods
426     ObjCMethodList *Prev = 0;
427     for (unsigned I = 0; I != NumInstanceMethods; ++I) {
428       ObjCMethodDecl *Method
429         = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
430       if (!Result.first.Method) {
431         // This is the first method, which is the easy case.
432         Result.first.Method = Method;
433         Prev = &Result.first;
434         continue;
435       }
436
437       Prev->Next = new ObjCMethodList(Method, 0);
438       Prev = Prev->Next;
439     }
440
441     // Load factory methods
442     Prev = 0;
443     for (unsigned I = 0; I != NumFactoryMethods; ++I) {
444       ObjCMethodDecl *Method
445         = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
446       if (!Result.second.Method) {
447         // This is the first method, which is the easy case.
448         Result.second.Method = Method;
449         Prev = &Result.second;
450         continue;
451       }
452
453       Prev->Next = new ObjCMethodList(Method, 0);
454       Prev = Prev->Next;
455     }
456
457     return Result;
458   }
459 };
460
461 } // end anonymous namespace
462
463 /// \brief The on-disk hash table used for the global method pool.
464 typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
465   PCHMethodPoolLookupTable;
466
467 namespace {
468 class PCHIdentifierLookupTrait {
469   PCHReader &Reader;
470
471   // If we know the IdentifierInfo in advance, it is here and we will
472   // not build a new one. Used when deserializing information about an
473   // identifier that was constructed before the PCH file was read.
474   IdentifierInfo *KnownII;
475
476 public:
477   typedef IdentifierInfo * data_type;
478
479   typedef const std::pair<const char*, unsigned> external_key_type;
480
481   typedef external_key_type internal_key_type;
482
483   explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
484     : Reader(Reader), KnownII(II) { }
485
486   static bool EqualKey(const internal_key_type& a,
487                        const internal_key_type& b) {
488     return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
489                                   : false;
490   }
491
492   static unsigned ComputeHash(const internal_key_type& a) {
493     return llvm::HashString(llvm::StringRef(a.first, a.second));
494   }
495
496   // This hopefully will just get inlined and removed by the optimizer.
497   static const internal_key_type&
498   GetInternalKey(const external_key_type& x) { return x; }
499
500   static std::pair<unsigned, unsigned>
501   ReadKeyDataLength(const unsigned char*& d) {
502     using namespace clang::io;
503     unsigned DataLen = ReadUnalignedLE16(d);
504     unsigned KeyLen = ReadUnalignedLE16(d);
505     return std::make_pair(KeyLen, DataLen);
506   }
507
508   static std::pair<const char*, unsigned>
509   ReadKey(const unsigned char* d, unsigned n) {
510     assert(n >= 2 && d[n-1] == '\0');
511     return std::make_pair((const char*) d, n-1);
512   }
513
514   IdentifierInfo *ReadData(const internal_key_type& k,
515                            const unsigned char* d,
516                            unsigned DataLen) {
517     using namespace clang::io;
518     pch::IdentID ID = ReadUnalignedLE32(d);
519     bool IsInteresting = ID & 0x01;
520
521     // Wipe out the "is interesting" bit.
522     ID = ID >> 1;
523
524     if (!IsInteresting) {
525       // For unintersting identifiers, just build the IdentifierInfo
526       // and associate it with the persistent ID.
527       IdentifierInfo *II = KnownII;
528       if (!II)
529         II = &Reader.getIdentifierTable().CreateIdentifierInfo(
530                                                  k.first, k.first + k.second);
531       Reader.SetIdentifierInfo(ID, II);
532       return II;
533     }
534
535     unsigned Bits = ReadUnalignedLE16(d);
536     bool CPlusPlusOperatorKeyword = Bits & 0x01;
537     Bits >>= 1;
538     bool Poisoned = Bits & 0x01;
539     Bits >>= 1;
540     bool ExtensionToken = Bits & 0x01;
541     Bits >>= 1;
542     bool hasMacroDefinition = Bits & 0x01;
543     Bits >>= 1;
544     unsigned ObjCOrBuiltinID = Bits & 0x3FF;
545     Bits >>= 10;
546
547     assert(Bits == 0 && "Extra bits in the identifier?");
548     DataLen -= 6;
549
550     // Build the IdentifierInfo itself and link the identifier ID with
551     // the new IdentifierInfo.
552     IdentifierInfo *II = KnownII;
553     if (!II)
554       II = &Reader.getIdentifierTable().CreateIdentifierInfo(
555                                                  k.first, k.first + k.second);
556     Reader.SetIdentifierInfo(ID, II);
557
558     // Set or check the various bits in the IdentifierInfo structure.
559     // FIXME: Load token IDs lazily, too?
560     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
561     assert(II->isExtensionToken() == ExtensionToken &&
562            "Incorrect extension token flag");
563     (void)ExtensionToken;
564     II->setIsPoisoned(Poisoned);
565     assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
566            "Incorrect C++ operator keyword flag");
567     (void)CPlusPlusOperatorKeyword;
568
569     // If this identifier is a macro, deserialize the macro
570     // definition.
571     if (hasMacroDefinition) {
572       uint32_t Offset = ReadUnalignedLE32(d);
573       Reader.ReadMacroRecord(Offset);
574       DataLen -= 4;
575     }
576
577     // Read all of the declarations visible at global scope with this
578     // name.
579     if (Reader.getContext() == 0) return II;
580     if (DataLen > 0) {
581       llvm::SmallVector<uint32_t, 4> DeclIDs;
582       for (; DataLen > 0; DataLen -= 4)
583         DeclIDs.push_back(ReadUnalignedLE32(d));
584       Reader.SetGloballyVisibleDecls(II, DeclIDs);
585     }
586
587     return II;
588   }
589 };
590
591 } // end anonymous namespace
592
593 /// \brief The on-disk hash table used to contain information about
594 /// all of the identifiers in the program.
595 typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
596   PCHIdentifierLookupTable;
597
598 bool PCHReader::Error(const char *Msg) {
599   unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
600   Diag(DiagID);
601   return true;
602 }
603
604 /// \brief Check the contents of the predefines buffer against the
605 /// contents of the predefines buffer used to build the PCH file.
606 ///
607 /// The contents of the two predefines buffers should be the same. If
608 /// not, then some command-line option changed the preprocessor state
609 /// and we must reject the PCH file.
610 ///
611 /// \param PCHPredef The start of the predefines buffer in the PCH
612 /// file.
613 ///
614 /// \param PCHPredefLen The length of the predefines buffer in the PCH
615 /// file.
616 ///
617 /// \param PCHBufferID The FileID for the PCH predefines buffer.
618 ///
619 /// \returns true if there was a mismatch (in which case the PCH file
620 /// should be ignored), or false otherwise.
621 bool PCHReader::CheckPredefinesBuffer(llvm::StringRef PCHPredef,
622                                       FileID PCHBufferID) {
623   if (Listener)
624     return Listener->ReadPredefinesBuffer(PCHPredef, PCHBufferID,
625                                           ActualOriginalFileName,
626                                           SuggestedPredefines);
627   return false;
628 }
629
630 //===----------------------------------------------------------------------===//
631 // Source Manager Deserialization
632 //===----------------------------------------------------------------------===//
633
634 /// \brief Read the line table in the source manager block.
635 /// \returns true if ther was an error.
636 bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
637   unsigned Idx = 0;
638   LineTableInfo &LineTable = SourceMgr.getLineTable();
639
640   // Parse the file names
641   std::map<int, int> FileIDs;
642   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
643     // Extract the file name
644     unsigned FilenameLen = Record[Idx++];
645     std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
646     Idx += FilenameLen;
647     MaybeAddSystemRootToFilename(Filename);
648     FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
649                                                   Filename.size());
650   }
651
652   // Parse the line entries
653   std::vector<LineEntry> Entries;
654   while (Idx < Record.size()) {
655     int FID = FileIDs[Record[Idx++]];
656
657     // Extract the line entries
658     unsigned NumEntries = Record[Idx++];
659     Entries.clear();
660     Entries.reserve(NumEntries);
661     for (unsigned I = 0; I != NumEntries; ++I) {
662       unsigned FileOffset = Record[Idx++];
663       unsigned LineNo = Record[Idx++];
664       int FilenameID = Record[Idx++];
665       SrcMgr::CharacteristicKind FileKind
666         = (SrcMgr::CharacteristicKind)Record[Idx++];
667       unsigned IncludeOffset = Record[Idx++];
668       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
669                                        FileKind, IncludeOffset));
670     }
671     LineTable.AddEntry(FID, Entries);
672   }
673
674   return false;
675 }
676
677 namespace {
678
679 class PCHStatData {
680 public:
681   const bool hasStat;
682   const ino_t ino;
683   const dev_t dev;
684   const mode_t mode;
685   const time_t mtime;
686   const off_t size;
687
688   PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
689   : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
690
691   PCHStatData()
692     : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
693 };
694
695 class PCHStatLookupTrait {
696  public:
697   typedef const char *external_key_type;
698   typedef const char *internal_key_type;
699
700   typedef PCHStatData data_type;
701
702   static unsigned ComputeHash(const char *path) {
703     return llvm::HashString(path);
704   }
705
706   static internal_key_type GetInternalKey(const char *path) { return path; }
707
708   static bool EqualKey(internal_key_type a, internal_key_type b) {
709     return strcmp(a, b) == 0;
710   }
711
712   static std::pair<unsigned, unsigned>
713   ReadKeyDataLength(const unsigned char*& d) {
714     unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
715     unsigned DataLen = (unsigned) *d++;
716     return std::make_pair(KeyLen + 1, DataLen);
717   }
718
719   static internal_key_type ReadKey(const unsigned char *d, unsigned) {
720     return (const char *)d;
721   }
722
723   static data_type ReadData(const internal_key_type, const unsigned char *d,
724                             unsigned /*DataLen*/) {
725     using namespace clang::io;
726
727     if (*d++ == 1)
728       return data_type();
729
730     ino_t ino = (ino_t) ReadUnalignedLE32(d);
731     dev_t dev = (dev_t) ReadUnalignedLE32(d);
732     mode_t mode = (mode_t) ReadUnalignedLE16(d);
733     time_t mtime = (time_t) ReadUnalignedLE64(d);
734     off_t size = (off_t) ReadUnalignedLE64(d);
735     return data_type(ino, dev, mode, mtime, size);
736   }
737 };
738
739 /// \brief stat() cache for precompiled headers.
740 ///
741 /// This cache is very similar to the stat cache used by pretokenized
742 /// headers.
743 class PCHStatCache : public StatSysCallCache {
744   typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
745   CacheTy *Cache;
746
747   unsigned &NumStatHits, &NumStatMisses;
748 public:
749   PCHStatCache(const unsigned char *Buckets,
750                const unsigned char *Base,
751                unsigned &NumStatHits,
752                unsigned &NumStatMisses)
753     : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
754     Cache = CacheTy::Create(Buckets, Base);
755   }
756
757   ~PCHStatCache() { delete Cache; }
758
759   int stat(const char *path, struct stat *buf) {
760     // Do the lookup for the file's data in the PCH file.
761     CacheTy::iterator I = Cache->find(path);
762
763     // If we don't get a hit in the PCH file just forward to 'stat'.
764     if (I == Cache->end()) {
765       ++NumStatMisses;
766       return StatSysCallCache::stat(path, buf);
767     }
768
769     ++NumStatHits;
770     PCHStatData Data = *I;
771
772     if (!Data.hasStat)
773       return 1;
774
775     buf->st_ino = Data.ino;
776     buf->st_dev = Data.dev;
777     buf->st_mtime = Data.mtime;
778     buf->st_mode = Data.mode;
779     buf->st_size = Data.size;
780     return 0;
781   }
782 };
783 } // end anonymous namespace
784
785
786 /// \brief Read the source manager block
787 PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
788   using namespace SrcMgr;
789
790   // Set the source-location entry cursor to the current position in
791   // the stream. This cursor will be used to read the contents of the
792   // source manager block initially, and then lazily read
793   // source-location entries as needed.
794   SLocEntryCursor = Stream;
795
796   // The stream itself is going to skip over the source manager block.
797   if (Stream.SkipBlock()) {
798     Error("malformed block record in PCH file");
799     return Failure;
800   }
801
802   // Enter the source manager block.
803   if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
804     Error("malformed source manager block record in PCH file");
805     return Failure;
806   }
807
808   RecordData Record;
809   while (true) {
810     unsigned Code = SLocEntryCursor.ReadCode();
811     if (Code == llvm::bitc::END_BLOCK) {
812       if (SLocEntryCursor.ReadBlockEnd()) {
813         Error("error at end of Source Manager block in PCH file");
814         return Failure;
815       }
816       return Success;
817     }
818
819     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
820       // No known subblocks, always skip them.
821       SLocEntryCursor.ReadSubBlockID();
822       if (SLocEntryCursor.SkipBlock()) {
823         Error("malformed block record in PCH file");
824         return Failure;
825       }
826       continue;
827     }
828
829     if (Code == llvm::bitc::DEFINE_ABBREV) {
830       SLocEntryCursor.ReadAbbrevRecord();
831       continue;
832     }
833
834     // Read a record.
835     const char *BlobStart;
836     unsigned BlobLen;
837     Record.clear();
838     switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
839     default:  // Default behavior: ignore.
840       break;
841
842     case pch::SM_LINE_TABLE:
843       if (ParseLineTable(Record))
844         return Failure;
845       break;
846
847     case pch::SM_HEADER_FILE_INFO: {
848       HeaderFileInfo HFI;
849       HFI.isImport = Record[0];
850       HFI.DirInfo = Record[1];
851       HFI.NumIncludes = Record[2];
852       HFI.ControllingMacroID = Record[3];
853       if (Listener)
854         Listener->ReadHeaderFileInfo(HFI);
855       break;
856     }
857
858     case pch::SM_SLOC_FILE_ENTRY:
859     case pch::SM_SLOC_BUFFER_ENTRY:
860     case pch::SM_SLOC_INSTANTIATION_ENTRY:
861       // Once we hit one of the source location entries, we're done.
862       return Success;
863     }
864   }
865 }
866
867 /// \brief Read in the source location entry with the given ID.
868 PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
869   if (ID == 0)
870     return Success;
871
872   if (ID > TotalNumSLocEntries) {
873     Error("source location entry ID out-of-range for PCH file");
874     return Failure;
875   }
876
877   ++NumSLocEntriesRead;
878   SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
879   unsigned Code = SLocEntryCursor.ReadCode();
880   if (Code == llvm::bitc::END_BLOCK ||
881       Code == llvm::bitc::ENTER_SUBBLOCK ||
882       Code == llvm::bitc::DEFINE_ABBREV) {
883     Error("incorrectly-formatted source location entry in PCH file");
884     return Failure;
885   }
886
887   RecordData Record;
888   const char *BlobStart;
889   unsigned BlobLen;
890   switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
891   default:
892     Error("incorrectly-formatted source location entry in PCH file");
893     return Failure;
894
895   case pch::SM_SLOC_FILE_ENTRY: {
896     std::string Filename(BlobStart, BlobStart + BlobLen);
897     MaybeAddSystemRootToFilename(Filename);
898     const FileEntry *File = FileMgr.getFile(Filename);
899     if (File == 0) {
900       std::string ErrorStr = "could not find file '";
901       ErrorStr += Filename;
902       ErrorStr += "' referenced by PCH file";
903       Error(ErrorStr.c_str());
904       return Failure;
905     }
906
907     FileID FID = SourceMgr.createFileID(File,
908                                 SourceLocation::getFromRawEncoding(Record[1]),
909                                        (SrcMgr::CharacteristicKind)Record[2],
910                                         ID, Record[0]);
911     if (Record[3])
912       const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
913         .setHasLineDirectives();
914
915     break;
916   }
917
918   case pch::SM_SLOC_BUFFER_ENTRY: {
919     const char *Name = BlobStart;
920     unsigned Offset = Record[0];
921     unsigned Code = SLocEntryCursor.ReadCode();
922     Record.clear();
923     unsigned RecCode
924       = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
925     assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
926     (void)RecCode;
927     llvm::MemoryBuffer *Buffer
928       = llvm::MemoryBuffer::getMemBuffer(BlobStart,
929                                          BlobStart + BlobLen - 1,
930                                          Name);
931     FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
932
933     if (strcmp(Name, "<built-in>") == 0) {
934       PCHPredefinesBufferID = BufferID;
935       PCHPredefines = BlobStart;
936       PCHPredefinesLen = BlobLen - 1;
937     }
938
939     break;
940   }
941
942   case pch::SM_SLOC_INSTANTIATION_ENTRY: {
943     SourceLocation SpellingLoc
944       = SourceLocation::getFromRawEncoding(Record[1]);
945     SourceMgr.createInstantiationLoc(SpellingLoc,
946                               SourceLocation::getFromRawEncoding(Record[2]),
947                               SourceLocation::getFromRawEncoding(Record[3]),
948                                      Record[4],
949                                      ID,
950                                      Record[0]);
951     break;
952   }
953   }
954
955   return Success;
956 }
957
958 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
959 /// specified cursor.  Read the abbreviations that are at the top of the block
960 /// and then leave the cursor pointing into the block.
961 bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
962                                  unsigned BlockID) {
963   if (Cursor.EnterSubBlock(BlockID)) {
964     Error("malformed block record in PCH file");
965     return Failure;
966   }
967
968   while (true) {
969     unsigned Code = Cursor.ReadCode();
970
971     // We expect all abbrevs to be at the start of the block.
972     if (Code != llvm::bitc::DEFINE_ABBREV)
973       return false;
974     Cursor.ReadAbbrevRecord();
975   }
976 }
977
978 void PCHReader::ReadMacroRecord(uint64_t Offset) {
979   assert(PP && "Forgot to set Preprocessor ?");
980
981   // Keep track of where we are in the stream, then jump back there
982   // after reading this macro.
983   SavedStreamPosition SavedPosition(Stream);
984
985   Stream.JumpToBit(Offset);
986   RecordData Record;
987   llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
988   MacroInfo *Macro = 0;
989
990   while (true) {
991     unsigned Code = Stream.ReadCode();
992     switch (Code) {
993     case llvm::bitc::END_BLOCK:
994       return;
995
996     case llvm::bitc::ENTER_SUBBLOCK:
997       // No known subblocks, always skip them.
998       Stream.ReadSubBlockID();
999       if (Stream.SkipBlock()) {
1000         Error("malformed block record in PCH file");
1001         return;
1002       }
1003       continue;
1004
1005     case llvm::bitc::DEFINE_ABBREV:
1006       Stream.ReadAbbrevRecord();
1007       continue;
1008     default: break;
1009     }
1010
1011     // Read a record.
1012     Record.clear();
1013     pch::PreprocessorRecordTypes RecType =
1014       (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1015     switch (RecType) {
1016     case pch::PP_MACRO_OBJECT_LIKE:
1017     case pch::PP_MACRO_FUNCTION_LIKE: {
1018       // If we already have a macro, that means that we've hit the end
1019       // of the definition of the macro we were looking for. We're
1020       // done.
1021       if (Macro)
1022         return;
1023
1024       IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1025       if (II == 0) {
1026         Error("macro must have a name in PCH file");
1027         return;
1028       }
1029       SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1030       bool isUsed = Record[2];
1031
1032       MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1033       MI->setIsUsed(isUsed);
1034
1035       if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1036         // Decode function-like macro info.
1037         bool isC99VarArgs = Record[3];
1038         bool isGNUVarArgs = Record[4];
1039         MacroArgs.clear();
1040         unsigned NumArgs = Record[5];
1041         for (unsigned i = 0; i != NumArgs; ++i)
1042           MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1043
1044         // Install function-like macro info.
1045         MI->setIsFunctionLike();
1046         if (isC99VarArgs) MI->setIsC99Varargs();
1047         if (isGNUVarArgs) MI->setIsGNUVarargs();
1048         MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1049                             PP->getPreprocessorAllocator());
1050       }
1051
1052       // Finally, install the macro.
1053       PP->setMacroInfo(II, MI);
1054
1055       // Remember that we saw this macro last so that we add the tokens that
1056       // form its body to it.
1057       Macro = MI;
1058       ++NumMacrosRead;
1059       break;
1060     }
1061
1062     case pch::PP_TOKEN: {
1063       // If we see a TOKEN before a PP_MACRO_*, then the file is
1064       // erroneous, just pretend we didn't see this.
1065       if (Macro == 0) break;
1066
1067       Token Tok;
1068       Tok.startToken();
1069       Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1070       Tok.setLength(Record[1]);
1071       if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1072         Tok.setIdentifierInfo(II);
1073       Tok.setKind((tok::TokenKind)Record[3]);
1074       Tok.setFlag((Token::TokenFlags)Record[4]);
1075       Macro->AddTokenToBody(Tok);
1076       break;
1077     }
1078   }
1079   }
1080 }
1081
1082 void PCHReader::ReadDefinedMacros() {
1083   // If there was no preprocessor block, do nothing.
1084   if (!MacroCursor.getBitStreamReader())
1085     return;
1086   
1087   llvm::BitstreamCursor Cursor = MacroCursor;
1088   if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1089     Error("malformed preprocessor block record in PCH file");
1090     return;
1091   }
1092   
1093   RecordData Record;
1094   while (true) {
1095     unsigned Code = Cursor.ReadCode();
1096     if (Code == llvm::bitc::END_BLOCK) {
1097       if (Cursor.ReadBlockEnd())
1098         Error("error at end of preprocessor block in PCH file");
1099       return;
1100     }
1101     
1102     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1103       // No known subblocks, always skip them.
1104       Cursor.ReadSubBlockID();
1105       if (Cursor.SkipBlock()) {
1106         Error("malformed block record in PCH file");
1107         return;
1108       }
1109       continue;
1110     }
1111     
1112     if (Code == llvm::bitc::DEFINE_ABBREV) {
1113       Cursor.ReadAbbrevRecord();
1114       continue;
1115     }
1116     
1117     // Read a record.
1118     const char *BlobStart;
1119     unsigned BlobLen;
1120     Record.clear();
1121     switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1122     default:  // Default behavior: ignore.
1123       break;
1124         
1125     case pch::PP_MACRO_OBJECT_LIKE:
1126     case pch::PP_MACRO_FUNCTION_LIKE:
1127         DecodeIdentifierInfo(Record[0]);
1128       break;
1129
1130     case pch::PP_TOKEN:
1131       // Ignore tokens.
1132       break;
1133     }
1134   }
1135 }
1136
1137 /// \brief If we are loading a relocatable PCH file, and the filename is
1138 /// not an absolute path, add the system root to the beginning of the file
1139 /// name.
1140 void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1141   // If this is not a relocatable PCH file, there's nothing to do.
1142   if (!RelocatablePCH)
1143     return;
1144
1145   if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
1146     return;
1147
1148   if (isysroot == 0) {
1149     // If no system root was given, default to '/'
1150     Filename.insert(Filename.begin(), '/');
1151     return;
1152   }
1153
1154   unsigned Length = strlen(isysroot);
1155   if (isysroot[Length - 1] != '/')
1156     Filename.insert(Filename.begin(), '/');
1157
1158   Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1159 }
1160
1161 PCHReader::PCHReadResult
1162 PCHReader::ReadPCHBlock() {
1163   if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1164     Error("malformed block record in PCH file");
1165     return Failure;
1166   }
1167
1168   // Read all of the records and blocks for the PCH file.
1169   RecordData Record;
1170   while (!Stream.AtEndOfStream()) {
1171     unsigned Code = Stream.ReadCode();
1172     if (Code == llvm::bitc::END_BLOCK) {
1173       if (Stream.ReadBlockEnd()) {
1174         Error("error at end of module block in PCH file");
1175         return Failure;
1176       }
1177
1178       return Success;
1179     }
1180
1181     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1182       switch (Stream.ReadSubBlockID()) {
1183       case pch::DECLTYPES_BLOCK_ID:
1184         // We lazily load the decls block, but we want to set up the
1185         // DeclsCursor cursor to point into it.  Clone our current bitcode
1186         // cursor to it, enter the block and read the abbrevs in that block.
1187         // With the main cursor, we just skip over it.
1188         DeclsCursor = Stream;
1189         if (Stream.SkipBlock() ||  // Skip with the main cursor.
1190             // Read the abbrevs.
1191             ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
1192           Error("malformed block record in PCH file");
1193           return Failure;
1194         }
1195         break;
1196
1197       case pch::PREPROCESSOR_BLOCK_ID:
1198         MacroCursor = Stream;
1199         if (PP)
1200           PP->setExternalSource(this);
1201
1202         if (Stream.SkipBlock()) {
1203           Error("malformed block record in PCH file");
1204           return Failure;
1205         }
1206         break;
1207
1208       case pch::SOURCE_MANAGER_BLOCK_ID:
1209         switch (ReadSourceManagerBlock()) {
1210         case Success:
1211           break;
1212
1213         case Failure:
1214           Error("malformed source manager block in PCH file");
1215           return Failure;
1216
1217         case IgnorePCH:
1218           return IgnorePCH;
1219         }
1220         break;
1221       }
1222       continue;
1223     }
1224
1225     if (Code == llvm::bitc::DEFINE_ABBREV) {
1226       Stream.ReadAbbrevRecord();
1227       continue;
1228     }
1229
1230     // Read and process a record.
1231     Record.clear();
1232     const char *BlobStart = 0;
1233     unsigned BlobLen = 0;
1234     switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1235                                                    &BlobStart, &BlobLen)) {
1236     default:  // Default behavior: ignore.
1237       break;
1238
1239     case pch::TYPE_OFFSET:
1240       if (!TypesLoaded.empty()) {
1241         Error("duplicate TYPE_OFFSET record in PCH file");
1242         return Failure;
1243       }
1244       TypeOffsets = (const uint32_t *)BlobStart;
1245       TypesLoaded.resize(Record[0]);
1246       break;
1247
1248     case pch::DECL_OFFSET:
1249       if (!DeclsLoaded.empty()) {
1250         Error("duplicate DECL_OFFSET record in PCH file");
1251         return Failure;
1252       }
1253       DeclOffsets = (const uint32_t *)BlobStart;
1254       DeclsLoaded.resize(Record[0]);
1255       break;
1256
1257     case pch::LANGUAGE_OPTIONS:
1258       if (ParseLanguageOptions(Record))
1259         return IgnorePCH;
1260       break;
1261
1262     case pch::METADATA: {
1263       if (Record[0] != pch::VERSION_MAJOR) {
1264         Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1265                                            : diag::warn_pch_version_too_new);
1266         return IgnorePCH;
1267       }
1268
1269       RelocatablePCH = Record[4];
1270       if (Listener) {
1271         std::string TargetTriple(BlobStart, BlobLen);
1272         if (Listener->ReadTargetTriple(TargetTriple))
1273           return IgnorePCH;
1274       }
1275       break;
1276     }
1277
1278     case pch::IDENTIFIER_TABLE:
1279       IdentifierTableData = BlobStart;
1280       if (Record[0]) {
1281         IdentifierLookupTable
1282           = PCHIdentifierLookupTable::Create(
1283                         (const unsigned char *)IdentifierTableData + Record[0],
1284                         (const unsigned char *)IdentifierTableData,
1285                         PCHIdentifierLookupTrait(*this));
1286         if (PP)
1287           PP->getIdentifierTable().setExternalIdentifierLookup(this);
1288       }
1289       break;
1290
1291     case pch::IDENTIFIER_OFFSET:
1292       if (!IdentifiersLoaded.empty()) {
1293         Error("duplicate IDENTIFIER_OFFSET record in PCH file");
1294         return Failure;
1295       }
1296       IdentifierOffsets = (const uint32_t *)BlobStart;
1297       IdentifiersLoaded.resize(Record[0]);
1298       if (PP)
1299         PP->getHeaderSearchInfo().SetExternalLookup(this);
1300       break;
1301
1302     case pch::EXTERNAL_DEFINITIONS:
1303       if (!ExternalDefinitions.empty()) {
1304         Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
1305         return Failure;
1306       }
1307       ExternalDefinitions.swap(Record);
1308       break;
1309
1310     case pch::SPECIAL_TYPES:
1311       SpecialTypes.swap(Record);
1312       break;
1313
1314     case pch::STATISTICS:
1315       TotalNumStatements = Record[0];
1316       TotalNumMacros = Record[1];
1317       TotalLexicalDeclContexts = Record[2];
1318       TotalVisibleDeclContexts = Record[3];
1319       break;
1320
1321     case pch::TENTATIVE_DEFINITIONS:
1322       if (!TentativeDefinitions.empty()) {
1323         Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
1324         return Failure;
1325       }
1326       TentativeDefinitions.swap(Record);
1327       break;
1328
1329     case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1330       if (!LocallyScopedExternalDecls.empty()) {
1331         Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1332         return Failure;
1333       }
1334       LocallyScopedExternalDecls.swap(Record);
1335       break;
1336
1337     case pch::SELECTOR_OFFSETS:
1338       SelectorOffsets = (const uint32_t *)BlobStart;
1339       TotalNumSelectors = Record[0];
1340       SelectorsLoaded.resize(TotalNumSelectors);
1341       break;
1342
1343     case pch::METHOD_POOL:
1344       MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1345       if (Record[0])
1346         MethodPoolLookupTable
1347           = PCHMethodPoolLookupTable::Create(
1348                         MethodPoolLookupTableData + Record[0],
1349                         MethodPoolLookupTableData,
1350                         PCHMethodPoolLookupTrait(*this));
1351       TotalSelectorsInMethodPool = Record[1];
1352       break;
1353
1354     case pch::PP_COUNTER_VALUE:
1355       if (!Record.empty() && Listener)
1356         Listener->ReadCounter(Record[0]);
1357       break;
1358
1359     case pch::SOURCE_LOCATION_OFFSETS:
1360       SLocOffsets = (const uint32_t *)BlobStart;
1361       TotalNumSLocEntries = Record[0];
1362       SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
1363       break;
1364
1365     case pch::SOURCE_LOCATION_PRELOADS:
1366       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1367         PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1368         if (Result != Success)
1369           return Result;
1370       }
1371       break;
1372
1373     case pch::STAT_CACHE: {
1374       PCHStatCache *MyStatCache = 
1375         new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1376                          (const unsigned char *)BlobStart,
1377                          NumStatHits, NumStatMisses);
1378       FileMgr.addStatCache(MyStatCache);
1379       StatCache = MyStatCache;
1380       break;
1381     }
1382         
1383     case pch::EXT_VECTOR_DECLS:
1384       if (!ExtVectorDecls.empty()) {
1385         Error("duplicate EXT_VECTOR_DECLS record in PCH file");
1386         return Failure;
1387       }
1388       ExtVectorDecls.swap(Record);
1389       break;
1390
1391     case pch::ORIGINAL_FILE_NAME:
1392       ActualOriginalFileName.assign(BlobStart, BlobLen);
1393       OriginalFileName = ActualOriginalFileName;
1394       MaybeAddSystemRootToFilename(OriginalFileName);
1395       break;
1396
1397     case pch::COMMENT_RANGES:
1398       Comments = (SourceRange *)BlobStart;
1399       NumComments = BlobLen / sizeof(SourceRange);
1400       break;
1401         
1402     case pch::VERSION_CONTROL_BRANCH_REVISION: {
1403       llvm::StringRef CurBranch = getClangFullRepositoryVersion();
1404       llvm::StringRef PCHBranch(BlobStart, BlobLen);
1405       if (CurBranch != PCHBranch) {
1406         Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1407         return IgnorePCH;
1408       }
1409       break;
1410     }
1411     }
1412   }
1413   Error("premature end of bitstream in PCH file");
1414   return Failure;
1415 }
1416
1417 PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
1418   // Set the PCH file name.
1419   this->FileName = FileName;
1420
1421   // Open the PCH file.
1422   //
1423   // FIXME: This shouldn't be here, we should just take a raw_ostream.
1424   std::string ErrStr;
1425   Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1426   if (!Buffer) {
1427     Error(ErrStr.c_str());
1428     return IgnorePCH;
1429   }
1430
1431   // Initialize the stream
1432   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1433                   (const unsigned char *)Buffer->getBufferEnd());
1434   Stream.init(StreamFile);
1435
1436   // Sniff for the signature.
1437   if (Stream.Read(8) != 'C' ||
1438       Stream.Read(8) != 'P' ||
1439       Stream.Read(8) != 'C' ||
1440       Stream.Read(8) != 'H') {
1441     Diag(diag::err_not_a_pch_file) << FileName;
1442     return Failure;
1443   }
1444
1445   while (!Stream.AtEndOfStream()) {
1446     unsigned Code = Stream.ReadCode();
1447
1448     if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1449       Error("invalid record at top-level of PCH file");
1450       return Failure;
1451     }
1452
1453     unsigned BlockID = Stream.ReadSubBlockID();
1454
1455     // We only know the PCH subblock ID.
1456     switch (BlockID) {
1457     case llvm::bitc::BLOCKINFO_BLOCK_ID:
1458       if (Stream.ReadBlockInfoBlock()) {
1459         Error("malformed BlockInfoBlock in PCH file");
1460         return Failure;
1461       }
1462       break;
1463     case pch::PCH_BLOCK_ID:
1464       switch (ReadPCHBlock()) {
1465       case Success:
1466         break;
1467
1468       case Failure:
1469         return Failure;
1470
1471       case IgnorePCH:
1472         // FIXME: We could consider reading through to the end of this
1473         // PCH block, skipping subblocks, to see if there are other
1474         // PCH blocks elsewhere.
1475
1476         // Clear out any preallocated source location entries, so that
1477         // the source manager does not try to resolve them later.
1478         SourceMgr.ClearPreallocatedSLocEntries();
1479
1480         // Remove the stat cache.
1481         if (StatCache)
1482           FileMgr.removeStatCache((PCHStatCache*)StatCache);
1483
1484         return IgnorePCH;
1485       }
1486       break;
1487     default:
1488       if (Stream.SkipBlock()) {
1489         Error("malformed block record in PCH file");
1490         return Failure;
1491       }
1492       break;
1493     }
1494   }
1495
1496   // Check the predefines buffer.
1497   if (CheckPredefinesBuffer(llvm::StringRef(PCHPredefines, PCHPredefinesLen),
1498                             PCHPredefinesBufferID))
1499     return IgnorePCH;
1500
1501   if (PP) {
1502     // Initialization of keywords and pragmas occurs before the
1503     // PCH file is read, so there may be some identifiers that were
1504     // loaded into the IdentifierTable before we intercepted the
1505     // creation of identifiers. Iterate through the list of known
1506     // identifiers and determine whether we have to establish
1507     // preprocessor definitions or top-level identifier declaration
1508     // chains for those identifiers.
1509     //
1510     // We copy the IdentifierInfo pointers to a small vector first,
1511     // since de-serializing declarations or macro definitions can add
1512     // new entries into the identifier table, invalidating the
1513     // iterators.
1514     llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1515     for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1516                                 IdEnd = PP->getIdentifierTable().end();
1517          Id != IdEnd; ++Id)
1518       Identifiers.push_back(Id->second);
1519     PCHIdentifierLookupTable *IdTable
1520       = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1521     for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1522       IdentifierInfo *II = Identifiers[I];
1523       // Look in the on-disk hash table for an entry for
1524       PCHIdentifierLookupTrait Info(*this, II);
1525       std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
1526       PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1527       if (Pos == IdTable->end())
1528         continue;
1529
1530       // Dereferencing the iterator has the effect of populating the
1531       // IdentifierInfo node with the various declarations it needs.
1532       (void)*Pos;
1533     }
1534   }
1535
1536   if (Context)
1537     InitializeContext(*Context);
1538
1539   return Success;
1540 }
1541
1542 void PCHReader::InitializeContext(ASTContext &Ctx) {
1543   Context = &Ctx;
1544   assert(Context && "Passed null context!");
1545
1546   assert(PP && "Forgot to set Preprocessor ?");
1547   PP->getIdentifierTable().setExternalIdentifierLookup(this);
1548   PP->getHeaderSearchInfo().SetExternalLookup(this);
1549   PP->setExternalSource(this);
1550   
1551   // Load the translation unit declaration
1552   ReadDeclRecord(DeclOffsets[0], 0);
1553
1554   // Load the special types.
1555   Context->setBuiltinVaListType(
1556     GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1557   if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1558     Context->setObjCIdType(GetType(Id));
1559   if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1560     Context->setObjCSelType(GetType(Sel));
1561   if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1562     Context->setObjCProtoType(GetType(Proto));
1563   if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1564     Context->setObjCClassType(GetType(Class));
1565
1566   if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1567     Context->setCFConstantStringType(GetType(String));
1568   if (unsigned FastEnum
1569         = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1570     Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1571   if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1572     QualType FileType = GetType(File);
1573     assert(!FileType.isNull() && "FILE type is NULL");
1574     if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
1575       Context->setFILEDecl(Typedef->getDecl());
1576     else {
1577       const TagType *Tag = FileType->getAs<TagType>();
1578       assert(Tag && "Invalid FILE type in PCH file");
1579       Context->setFILEDecl(Tag->getDecl());
1580     }
1581   }
1582   if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1583     QualType Jmp_bufType = GetType(Jmp_buf);
1584     assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
1585     if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
1586       Context->setjmp_bufDecl(Typedef->getDecl());
1587     else {
1588       const TagType *Tag = Jmp_bufType->getAs<TagType>();
1589       assert(Tag && "Invalid jmp_bug type in PCH file");
1590       Context->setjmp_bufDecl(Tag->getDecl());
1591     }
1592   }
1593   if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1594     QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1595     assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
1596     if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
1597       Context->setsigjmp_bufDecl(Typedef->getDecl());
1598     else {
1599       const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
1600       assert(Tag && "Invalid sigjmp_buf type in PCH file");
1601       Context->setsigjmp_bufDecl(Tag->getDecl());
1602     }
1603   }
1604   if (unsigned ObjCIdRedef
1605         = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1606     Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
1607   if (unsigned ObjCClassRedef
1608       = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1609     Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
1610 #if 0
1611   // FIXME. Accommodate for this in several PCH/Index tests
1612   if (unsigned ObjCSelRedef
1613       = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1614     Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1615 #endif
1616   if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1617     Context->setBlockDescriptorType(GetType(String));
1618   if (unsigned String
1619       = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1620     Context->setBlockDescriptorExtendedType(GetType(String));
1621 }
1622
1623 /// \brief Retrieve the name of the original source file name
1624 /// directly from the PCH file, without actually loading the PCH
1625 /// file.
1626 std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1627                                              Diagnostic &Diags) {
1628   // Open the PCH file.
1629   std::string ErrStr;
1630   llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1631   Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1632   if (!Buffer) {
1633     Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
1634     return std::string();
1635   }
1636
1637   // Initialize the stream
1638   llvm::BitstreamReader StreamFile;
1639   llvm::BitstreamCursor Stream;
1640   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1641                   (const unsigned char *)Buffer->getBufferEnd());
1642   Stream.init(StreamFile);
1643
1644   // Sniff for the signature.
1645   if (Stream.Read(8) != 'C' ||
1646       Stream.Read(8) != 'P' ||
1647       Stream.Read(8) != 'C' ||
1648       Stream.Read(8) != 'H') {
1649     Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
1650     return std::string();
1651   }
1652
1653   RecordData Record;
1654   while (!Stream.AtEndOfStream()) {
1655     unsigned Code = Stream.ReadCode();
1656
1657     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1658       unsigned BlockID = Stream.ReadSubBlockID();
1659
1660       // We only know the PCH subblock ID.
1661       switch (BlockID) {
1662       case pch::PCH_BLOCK_ID:
1663         if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1664           Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
1665           return std::string();
1666         }
1667         break;
1668
1669       default:
1670         if (Stream.SkipBlock()) {
1671           Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
1672           return std::string();
1673         }
1674         break;
1675       }
1676       continue;
1677     }
1678
1679     if (Code == llvm::bitc::END_BLOCK) {
1680       if (Stream.ReadBlockEnd()) {
1681         Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
1682         return std::string();
1683       }
1684       continue;
1685     }
1686
1687     if (Code == llvm::bitc::DEFINE_ABBREV) {
1688       Stream.ReadAbbrevRecord();
1689       continue;
1690     }
1691
1692     Record.clear();
1693     const char *BlobStart = 0;
1694     unsigned BlobLen = 0;
1695     if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1696           == pch::ORIGINAL_FILE_NAME)
1697       return std::string(BlobStart, BlobLen);
1698   }
1699
1700   return std::string();
1701 }
1702
1703 /// \brief Parse the record that corresponds to a LangOptions data
1704 /// structure.
1705 ///
1706 /// This routine compares the language options used to generate the
1707 /// PCH file against the language options set for the current
1708 /// compilation. For each option, we classify differences between the
1709 /// two compiler states as either "benign" or "important". Benign
1710 /// differences don't matter, and we accept them without complaint
1711 /// (and without modifying the language options). Differences between
1712 /// the states for important options cause the PCH file to be
1713 /// unusable, so we emit a warning and return true to indicate that
1714 /// there was an error.
1715 ///
1716 /// \returns true if the PCH file is unacceptable, false otherwise.
1717 bool PCHReader::ParseLanguageOptions(
1718                              const llvm::SmallVectorImpl<uint64_t> &Record) {
1719   if (Listener) {
1720     LangOptions LangOpts;
1721
1722   #define PARSE_LANGOPT(Option)                  \
1723       LangOpts.Option = Record[Idx];             \
1724       ++Idx
1725
1726     unsigned Idx = 0;
1727     PARSE_LANGOPT(Trigraphs);
1728     PARSE_LANGOPT(BCPLComment);
1729     PARSE_LANGOPT(DollarIdents);
1730     PARSE_LANGOPT(AsmPreprocessor);
1731     PARSE_LANGOPT(GNUMode);
1732     PARSE_LANGOPT(ImplicitInt);
1733     PARSE_LANGOPT(Digraphs);
1734     PARSE_LANGOPT(HexFloats);
1735     PARSE_LANGOPT(C99);
1736     PARSE_LANGOPT(Microsoft);
1737     PARSE_LANGOPT(CPlusPlus);
1738     PARSE_LANGOPT(CPlusPlus0x);
1739     PARSE_LANGOPT(CXXOperatorNames);
1740     PARSE_LANGOPT(ObjC1);
1741     PARSE_LANGOPT(ObjC2);
1742     PARSE_LANGOPT(ObjCNonFragileABI);
1743     PARSE_LANGOPT(PascalStrings);
1744     PARSE_LANGOPT(WritableStrings);
1745     PARSE_LANGOPT(LaxVectorConversions);
1746     PARSE_LANGOPT(AltiVec);
1747     PARSE_LANGOPT(Exceptions);
1748     PARSE_LANGOPT(NeXTRuntime);
1749     PARSE_LANGOPT(Freestanding);
1750     PARSE_LANGOPT(NoBuiltin);
1751     PARSE_LANGOPT(ThreadsafeStatics);
1752     PARSE_LANGOPT(POSIXThreads);
1753     PARSE_LANGOPT(Blocks);
1754     PARSE_LANGOPT(EmitAllDecls);
1755     PARSE_LANGOPT(MathErrno);
1756     PARSE_LANGOPT(OverflowChecking);
1757     PARSE_LANGOPT(HeinousExtensions);
1758     PARSE_LANGOPT(Optimize);
1759     PARSE_LANGOPT(OptimizeSize);
1760     PARSE_LANGOPT(Static);
1761     PARSE_LANGOPT(PICLevel);
1762     PARSE_LANGOPT(GNUInline);
1763     PARSE_LANGOPT(NoInline);
1764     PARSE_LANGOPT(AccessControl);
1765     PARSE_LANGOPT(CharIsSigned);
1766     PARSE_LANGOPT(ShortWChar);
1767     LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1768     ++Idx;
1769     LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1770     ++Idx;
1771     LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1772                                    Record[Idx]);
1773     ++Idx;
1774     PARSE_LANGOPT(InstantiationDepth);
1775     PARSE_LANGOPT(OpenCL);
1776     PARSE_LANGOPT(CatchUndefined);
1777     // FIXME: Missing ElideConstructors?!
1778   #undef PARSE_LANGOPT
1779
1780     return Listener->ReadLanguageOptions(LangOpts);
1781   }
1782
1783   return false;
1784 }
1785
1786 void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1787   Comments.resize(NumComments);
1788   std::copy(this->Comments, this->Comments + NumComments,
1789             Comments.begin());
1790 }
1791
1792 /// \brief Read and return the type at the given offset.
1793 ///
1794 /// This routine actually reads the record corresponding to the type
1795 /// at the given offset in the bitstream. It is a helper routine for
1796 /// GetType, which deals with reading type IDs.
1797 QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
1798   // Keep track of where we are in the stream, then jump back there
1799   // after reading this type.
1800   SavedStreamPosition SavedPosition(DeclsCursor);
1801
1802   // Note that we are loading a type record.
1803   LoadingTypeOrDecl Loading(*this);
1804
1805   DeclsCursor.JumpToBit(Offset);
1806   RecordData Record;
1807   unsigned Code = DeclsCursor.ReadCode();
1808   switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
1809   case pch::TYPE_EXT_QUAL: {
1810     assert(Record.size() == 2 &&
1811            "Incorrect encoding of extended qualifier type");
1812     QualType Base = GetType(Record[0]);
1813     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1814     return Context->getQualifiedType(Base, Quals);
1815   }
1816
1817   case pch::TYPE_COMPLEX: {
1818     assert(Record.size() == 1 && "Incorrect encoding of complex type");
1819     QualType ElemType = GetType(Record[0]);
1820     return Context->getComplexType(ElemType);
1821   }
1822
1823   case pch::TYPE_POINTER: {
1824     assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1825     QualType PointeeType = GetType(Record[0]);
1826     return Context->getPointerType(PointeeType);
1827   }
1828
1829   case pch::TYPE_BLOCK_POINTER: {
1830     assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1831     QualType PointeeType = GetType(Record[0]);
1832     return Context->getBlockPointerType(PointeeType);
1833   }
1834
1835   case pch::TYPE_LVALUE_REFERENCE: {
1836     assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1837     QualType PointeeType = GetType(Record[0]);
1838     return Context->getLValueReferenceType(PointeeType);
1839   }
1840
1841   case pch::TYPE_RVALUE_REFERENCE: {
1842     assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1843     QualType PointeeType = GetType(Record[0]);
1844     return Context->getRValueReferenceType(PointeeType);
1845   }
1846
1847   case pch::TYPE_MEMBER_POINTER: {
1848     assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1849     QualType PointeeType = GetType(Record[0]);
1850     QualType ClassType = GetType(Record[1]);
1851     return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
1852   }
1853
1854   case pch::TYPE_CONSTANT_ARRAY: {
1855     QualType ElementType = GetType(Record[0]);
1856     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1857     unsigned IndexTypeQuals = Record[2];
1858     unsigned Idx = 3;
1859     llvm::APInt Size = ReadAPInt(Record, Idx);
1860     return Context->getConstantArrayType(ElementType, Size,
1861                                          ASM, IndexTypeQuals);
1862   }
1863
1864   case pch::TYPE_INCOMPLETE_ARRAY: {
1865     QualType ElementType = GetType(Record[0]);
1866     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1867     unsigned IndexTypeQuals = Record[2];
1868     return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1869   }
1870
1871   case pch::TYPE_VARIABLE_ARRAY: {
1872     QualType ElementType = GetType(Record[0]);
1873     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1874     unsigned IndexTypeQuals = Record[2];
1875     SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1876     SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1877     return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1878                                          ASM, IndexTypeQuals,
1879                                          SourceRange(LBLoc, RBLoc));
1880   }
1881
1882   case pch::TYPE_VECTOR: {
1883     if (Record.size() != 2) {
1884       Error("incorrect encoding of vector type in PCH file");
1885       return QualType();
1886     }
1887
1888     QualType ElementType = GetType(Record[0]);
1889     unsigned NumElements = Record[1];
1890     return Context->getVectorType(ElementType, NumElements);
1891   }
1892
1893   case pch::TYPE_EXT_VECTOR: {
1894     if (Record.size() != 2) {
1895       Error("incorrect encoding of extended vector type in PCH file");
1896       return QualType();
1897     }
1898
1899     QualType ElementType = GetType(Record[0]);
1900     unsigned NumElements = Record[1];
1901     return Context->getExtVectorType(ElementType, NumElements);
1902   }
1903
1904   case pch::TYPE_FUNCTION_NO_PROTO: {
1905     if (Record.size() != 3) {
1906       Error("incorrect encoding of no-proto function type");
1907       return QualType();
1908     }
1909     QualType ResultType = GetType(Record[0]);
1910     return Context->getFunctionNoProtoType(ResultType, Record[1],
1911                                            (CallingConv)Record[2]);
1912   }
1913
1914   case pch::TYPE_FUNCTION_PROTO: {
1915     QualType ResultType = GetType(Record[0]);
1916     bool NoReturn = Record[1];
1917     CallingConv CallConv = (CallingConv)Record[2];
1918     unsigned Idx = 3;
1919     unsigned NumParams = Record[Idx++];
1920     llvm::SmallVector<QualType, 16> ParamTypes;
1921     for (unsigned I = 0; I != NumParams; ++I)
1922       ParamTypes.push_back(GetType(Record[Idx++]));
1923     bool isVariadic = Record[Idx++];
1924     unsigned Quals = Record[Idx++];
1925     bool hasExceptionSpec = Record[Idx++];
1926     bool hasAnyExceptionSpec = Record[Idx++];
1927     unsigned NumExceptions = Record[Idx++];
1928     llvm::SmallVector<QualType, 2> Exceptions;
1929     for (unsigned I = 0; I != NumExceptions; ++I)
1930       Exceptions.push_back(GetType(Record[Idx++]));
1931     return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
1932                                     isVariadic, Quals, hasExceptionSpec,
1933                                     hasAnyExceptionSpec, NumExceptions,
1934                                     Exceptions.data(), NoReturn, CallConv);
1935   }
1936
1937   case pch::TYPE_UNRESOLVED_USING:
1938     return Context->getTypeDeclType(
1939              cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
1940
1941   case pch::TYPE_TYPEDEF:
1942     assert(Record.size() == 1 && "incorrect encoding of typedef type");
1943     return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1944
1945   case pch::TYPE_TYPEOF_EXPR:
1946     return Context->getTypeOfExprType(ReadTypeExpr());
1947
1948   case pch::TYPE_TYPEOF: {
1949     if (Record.size() != 1) {
1950       Error("incorrect encoding of typeof(type) in PCH file");
1951       return QualType();
1952     }
1953     QualType UnderlyingType = GetType(Record[0]);
1954     return Context->getTypeOfType(UnderlyingType);
1955   }
1956
1957   case pch::TYPE_DECLTYPE:
1958     return Context->getDecltypeType(ReadTypeExpr());
1959
1960   case pch::TYPE_RECORD:
1961     assert(Record.size() == 1 && "incorrect encoding of record type");
1962     return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
1963
1964   case pch::TYPE_ENUM:
1965     assert(Record.size() == 1 && "incorrect encoding of enum type");
1966     return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1967
1968   case pch::TYPE_ELABORATED: {
1969     assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1970     unsigned Tag = Record[1];
1971     return Context->getElaboratedType(GetType(Record[0]),
1972                                       (ElaboratedType::TagKind) Tag);
1973   }
1974
1975   case pch::TYPE_OBJC_INTERFACE: {
1976     unsigned Idx = 0;
1977     ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1978     unsigned NumProtos = Record[Idx++];
1979     llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1980     for (unsigned I = 0; I != NumProtos; ++I)
1981       Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1982     return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
1983   }
1984
1985   case pch::TYPE_OBJC_OBJECT_POINTER: {
1986     unsigned Idx = 0;
1987     QualType OIT = GetType(Record[Idx++]);
1988     unsigned NumProtos = Record[Idx++];
1989     llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1990     for (unsigned I = 0; I != NumProtos; ++I)
1991       Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1992     return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
1993   }
1994
1995   case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1996     unsigned Idx = 0;
1997     QualType Parm = GetType(Record[Idx++]);
1998     QualType Replacement = GetType(Record[Idx++]);
1999     return
2000       Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2001                                             Replacement);
2002   }
2003   }
2004   // Suppress a GCC warning
2005   return QualType();
2006 }
2007
2008 namespace {
2009
2010 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2011   PCHReader &Reader;
2012   const PCHReader::RecordData &Record;
2013   unsigned &Idx;
2014
2015 public:
2016   TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2017                 unsigned &Idx)
2018     : Reader(Reader), Record(Record), Idx(Idx) { }
2019
2020   // We want compile-time assurance that we've enumerated all of
2021   // these, so unfortunately we have to declare them first, then
2022   // define them out-of-line.
2023 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2024 #define TYPELOC(CLASS, PARENT) \
2025   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
2026 #include "clang/AST/TypeLocNodes.def"
2027
2028   void VisitFunctionTypeLoc(FunctionTypeLoc);
2029   void VisitArrayTypeLoc(ArrayTypeLoc);
2030 };
2031
2032 }
2033
2034 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2035   // nothing to do
2036 }
2037 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2038   TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2039   if (TL.needsExtraLocalData()) {
2040     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2041     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2042     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2043     TL.setModeAttr(Record[Idx++]);
2044   }
2045 }
2046 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2047   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2048 }
2049 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2050   TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2051 }
2052 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2053   TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2054 }
2055 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2056   TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2057 }
2058 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2059   TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2060 }
2061 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2062   TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2063 }
2064 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2065   TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2066   TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067   if (Record[Idx++])
2068     TL.setSizeExpr(Reader.ReadDeclExpr());
2069   else
2070     TL.setSizeExpr(0);
2071 }
2072 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2073   VisitArrayTypeLoc(TL);
2074 }
2075 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2076   VisitArrayTypeLoc(TL);
2077 }
2078 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2079   VisitArrayTypeLoc(TL);
2080 }
2081 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2082                                             DependentSizedArrayTypeLoc TL) {
2083   VisitArrayTypeLoc(TL);
2084 }
2085 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2086                                         DependentSizedExtVectorTypeLoc TL) {
2087   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2088 }
2089 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2090   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2091 }
2092 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2093   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2094 }
2095 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2096   TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097   TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2099     TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2100   }
2101 }
2102 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2103   VisitFunctionTypeLoc(TL);
2104 }
2105 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2106   VisitFunctionTypeLoc(TL);
2107 }
2108 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2109   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2110 }
2111 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2112   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2113 }
2114 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2115   TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2116   TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2117   TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2118 }
2119 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2120   TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121   TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2122   TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2123   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
2124 }
2125 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2126   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127 }
2128 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2129   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2130 }
2131 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2132   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2133 }
2134 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2135   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2136 }
2137 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2138   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2139 }
2140 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2141                                             SubstTemplateTypeParmTypeLoc TL) {
2142   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2143 }
2144 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2145                                            TemplateSpecializationTypeLoc TL) {
2146   TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2147   TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2148   TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2149   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2150     TL.setArgLocInfo(i,
2151         Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2152                                           Record, Idx));
2153 }
2154 void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2155   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2156 }
2157 void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2158   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2159 }
2160 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2161   TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2162   TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2163   TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2164   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2165     TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2166 }
2167 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2168   TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2169   TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2170   TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2171   TL.setHasBaseTypeAsWritten(Record[Idx++]);
2172   TL.setHasProtocolsAsWritten(Record[Idx++]);
2173   if (TL.hasProtocolsAsWritten())
2174     for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2175       TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2176 }
2177
2178 TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
2179                                              unsigned &Idx) {
2180   QualType InfoTy = GetType(Record[Idx++]);
2181   if (InfoTy.isNull())
2182     return 0;
2183
2184   TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
2185   TypeLocReader TLR(*this, Record, Idx);
2186   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2187     TLR.Visit(TL);
2188   return TInfo;
2189 }
2190
2191 QualType PCHReader::GetType(pch::TypeID ID) {
2192   unsigned FastQuals = ID & Qualifiers::FastMask;
2193   unsigned Index = ID >> Qualifiers::FastWidth;
2194
2195   if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2196     QualType T;
2197     switch ((pch::PredefinedTypeIDs)Index) {
2198     case pch::PREDEF_TYPE_NULL_ID: return QualType();
2199     case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2200     case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
2201
2202     case pch::PREDEF_TYPE_CHAR_U_ID:
2203     case pch::PREDEF_TYPE_CHAR_S_ID:
2204       // FIXME: Check that the signedness of CharTy is correct!
2205       T = Context->CharTy;
2206       break;
2207
2208     case pch::PREDEF_TYPE_UCHAR_ID:      T = Context->UnsignedCharTy;     break;
2209     case pch::PREDEF_TYPE_USHORT_ID:     T = Context->UnsignedShortTy;    break;
2210     case pch::PREDEF_TYPE_UINT_ID:       T = Context->UnsignedIntTy;      break;
2211     case pch::PREDEF_TYPE_ULONG_ID:      T = Context->UnsignedLongTy;     break;
2212     case pch::PREDEF_TYPE_ULONGLONG_ID:  T = Context->UnsignedLongLongTy; break;
2213     case pch::PREDEF_TYPE_UINT128_ID:    T = Context->UnsignedInt128Ty;   break;
2214     case pch::PREDEF_TYPE_SCHAR_ID:      T = Context->SignedCharTy;       break;
2215     case pch::PREDEF_TYPE_WCHAR_ID:      T = Context->WCharTy;            break;
2216     case pch::PREDEF_TYPE_SHORT_ID:      T = Context->ShortTy;            break;
2217     case pch::PREDEF_TYPE_INT_ID:        T = Context->IntTy;              break;
2218     case pch::PREDEF_TYPE_LONG_ID:       T = Context->LongTy;             break;
2219     case pch::PREDEF_TYPE_LONGLONG_ID:   T = Context->LongLongTy;         break;
2220     case pch::PREDEF_TYPE_INT128_ID:     T = Context->Int128Ty;           break;
2221     case pch::PREDEF_TYPE_FLOAT_ID:      T = Context->FloatTy;            break;
2222     case pch::PREDEF_TYPE_DOUBLE_ID:     T = Context->DoubleTy;           break;
2223     case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy;       break;
2224     case pch::PREDEF_TYPE_OVERLOAD_ID:   T = Context->OverloadTy;         break;
2225     case pch::PREDEF_TYPE_DEPENDENT_ID:  T = Context->DependentTy;        break;
2226     case pch::PREDEF_TYPE_NULLPTR_ID:    T = Context->NullPtrTy;          break;
2227     case pch::PREDEF_TYPE_CHAR16_ID:     T = Context->Char16Ty;           break;
2228     case pch::PREDEF_TYPE_CHAR32_ID:     T = Context->Char32Ty;           break;
2229     case pch::PREDEF_TYPE_OBJC_ID:       T = Context->ObjCBuiltinIdTy;    break;
2230     case pch::PREDEF_TYPE_OBJC_CLASS:    T = Context->ObjCBuiltinClassTy; break;
2231     case pch::PREDEF_TYPE_OBJC_SEL:      T = Context->ObjCBuiltinSelTy;   break;
2232     }
2233
2234     assert(!T.isNull() && "Unknown predefined type");
2235     return T.withFastQualifiers(FastQuals);
2236   }
2237
2238   Index -= pch::NUM_PREDEF_TYPE_IDS;
2239   //assert(Index < TypesLoaded.size() && "Type index out-of-range");
2240   if (TypesLoaded[Index].isNull())
2241     TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
2242
2243   return TypesLoaded[Index].withFastQualifiers(FastQuals);
2244 }
2245
2246 TemplateArgumentLocInfo
2247 PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2248                                       const RecordData &Record,
2249                                       unsigned &Index) {
2250   switch (Kind) {
2251   case TemplateArgument::Expression:
2252     return ReadDeclExpr();
2253   case TemplateArgument::Type:
2254     return GetTypeSourceInfo(Record, Index);
2255   case TemplateArgument::Template: {
2256     SourceLocation 
2257       QualStart = SourceLocation::getFromRawEncoding(Record[Index++]),
2258       QualEnd = SourceLocation::getFromRawEncoding(Record[Index++]),
2259       TemplateNameLoc = SourceLocation::getFromRawEncoding(Record[Index++]);
2260     return TemplateArgumentLocInfo(SourceRange(QualStart, QualEnd),
2261                                    TemplateNameLoc);
2262   }
2263   case TemplateArgument::Null:
2264   case TemplateArgument::Integral:
2265   case TemplateArgument::Declaration:
2266   case TemplateArgument::Pack:
2267     return TemplateArgumentLocInfo();
2268   }
2269   llvm_unreachable("unexpected template argument loc");
2270   return TemplateArgumentLocInfo();
2271 }
2272
2273 Decl *PCHReader::GetDecl(pch::DeclID ID) {
2274   if (ID == 0)
2275     return 0;
2276
2277   if (ID > DeclsLoaded.size()) {
2278     Error("declaration ID out-of-range for PCH file");
2279     return 0;
2280   }
2281
2282   unsigned Index = ID - 1;
2283   if (!DeclsLoaded[Index])
2284     ReadDeclRecord(DeclOffsets[Index], Index);
2285
2286   return DeclsLoaded[Index];
2287 }
2288
2289 /// \brief Resolve the offset of a statement into a statement.
2290 ///
2291 /// This operation will read a new statement from the external
2292 /// source each time it is called, and is meant to be used via a
2293 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2294 Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
2295   // Since we know tha this statement is part of a decl, make sure to use the
2296   // decl cursor to read it.
2297   DeclsCursor.JumpToBit(Offset);
2298   return ReadStmt(DeclsCursor);
2299 }
2300
2301 bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
2302                                   llvm::SmallVectorImpl<pch::DeclID> &Decls) {
2303   assert(DC->hasExternalLexicalStorage() &&
2304          "DeclContext has no lexical decls in storage");
2305   uint64_t Offset = DeclContextOffsets[DC].first;
2306   assert(Offset && "DeclContext has no lexical decls in storage");
2307
2308   // Keep track of where we are in the stream, then jump back there
2309   // after reading this context.
2310   SavedStreamPosition SavedPosition(DeclsCursor);
2311
2312   // Load the record containing all of the declarations lexically in
2313   // this context.
2314   DeclsCursor.JumpToBit(Offset);
2315   RecordData Record;
2316   unsigned Code = DeclsCursor.ReadCode();
2317   unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2318   (void)RecCode;
2319   assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2320
2321   // Load all of the declaration IDs
2322   Decls.clear();
2323   Decls.insert(Decls.end(), Record.begin(), Record.end());
2324   ++NumLexicalDeclContextsRead;
2325   return false;
2326 }
2327
2328 bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
2329                            llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
2330   assert(DC->hasExternalVisibleStorage() &&
2331          "DeclContext has no visible decls in storage");
2332   uint64_t Offset = DeclContextOffsets[DC].second;
2333   assert(Offset && "DeclContext has no visible decls in storage");
2334
2335   // Keep track of where we are in the stream, then jump back there
2336   // after reading this context.
2337   SavedStreamPosition SavedPosition(DeclsCursor);
2338
2339   // Load the record containing all of the declarations visible in
2340   // this context.
2341   DeclsCursor.JumpToBit(Offset);
2342   RecordData Record;
2343   unsigned Code = DeclsCursor.ReadCode();
2344   unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2345   (void)RecCode;
2346   assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2347   if (Record.size() == 0)
2348     return false;
2349
2350   Decls.clear();
2351
2352   unsigned Idx = 0;
2353   while (Idx < Record.size()) {
2354     Decls.push_back(VisibleDeclaration());
2355     Decls.back().Name = ReadDeclarationName(Record, Idx);
2356
2357     unsigned Size = Record[Idx++];
2358     llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2359     LoadedDecls.reserve(Size);
2360     for (unsigned I = 0; I < Size; ++I)
2361       LoadedDecls.push_back(Record[Idx++]);
2362   }
2363
2364   ++NumVisibleDeclContextsRead;
2365   return false;
2366 }
2367
2368 void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
2369   this->Consumer = Consumer;
2370
2371   if (!Consumer)
2372     return;
2373
2374   for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2375     // Force deserialization of this decl, which will cause it to be passed to
2376     // the consumer (or queued).
2377     GetDecl(ExternalDefinitions[I]);
2378   }
2379
2380   for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2381     DeclGroupRef DG(InterestingDecls[I]);
2382     Consumer->HandleTopLevelDecl(DG);
2383   }
2384 }
2385
2386 void PCHReader::PrintStats() {
2387   std::fprintf(stderr, "*** PCH Statistics:\n");
2388
2389   unsigned NumTypesLoaded
2390     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2391                                       QualType());
2392   unsigned NumDeclsLoaded
2393     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2394                                       (Decl *)0);
2395   unsigned NumIdentifiersLoaded
2396     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2397                                             IdentifiersLoaded.end(),
2398                                             (IdentifierInfo *)0);
2399   unsigned NumSelectorsLoaded
2400     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2401                                           SelectorsLoaded.end(),
2402                                           Selector());
2403
2404   std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
2405   std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
2406   if (TotalNumSLocEntries)
2407     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
2408                  NumSLocEntriesRead, TotalNumSLocEntries,
2409                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
2410   if (!TypesLoaded.empty())
2411     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
2412                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
2413                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2414   if (!DeclsLoaded.empty())
2415     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
2416                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2417                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
2418   if (!IdentifiersLoaded.empty())
2419     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
2420                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2421                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
2422   if (TotalNumSelectors)
2423     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
2424                  NumSelectorsLoaded, TotalNumSelectors,
2425                  ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2426   if (TotalNumStatements)
2427     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
2428                  NumStatementsRead, TotalNumStatements,
2429                  ((float)NumStatementsRead/TotalNumStatements * 100));
2430   if (TotalNumMacros)
2431     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
2432                  NumMacrosRead, TotalNumMacros,
2433                  ((float)NumMacrosRead/TotalNumMacros * 100));
2434   if (TotalLexicalDeclContexts)
2435     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
2436                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2437                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2438                   * 100));
2439   if (TotalVisibleDeclContexts)
2440     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
2441                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2442                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2443                   * 100));
2444   if (TotalSelectorsInMethodPool) {
2445     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
2446                  NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2447                  ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2448                   * 100));
2449     std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
2450   }
2451   std::fprintf(stderr, "\n");
2452 }
2453
2454 void PCHReader::InitializeSema(Sema &S) {
2455   SemaObj = &S;
2456   S.ExternalSource = this;
2457
2458   // Makes sure any declarations that were deserialized "too early"
2459   // still get added to the identifier's declaration chains.
2460   for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2461     SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2462     SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
2463   }
2464   PreloadedDecls.clear();
2465
2466   // If there were any tentative definitions, deserialize them and add
2467   // them to Sema's table of tentative definitions.
2468   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2469     VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2470     SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2471     SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
2472   }
2473
2474   // If there were any locally-scoped external declarations,
2475   // deserialize them and add them to Sema's table of locally-scoped
2476   // external declarations.
2477   for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2478     NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2479     SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2480   }
2481
2482   // If there were any ext_vector type declarations, deserialize them
2483   // and add them to Sema's vector of such declarations.
2484   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2485     SemaObj->ExtVectorDecls.push_back(
2486                                cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2487 }
2488
2489 IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2490   // Try to find this name within our on-disk hash table
2491   PCHIdentifierLookupTable *IdTable
2492     = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2493   std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2494   PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2495   if (Pos == IdTable->end())
2496     return 0;
2497
2498   // Dereferencing the iterator has the effect of building the
2499   // IdentifierInfo node and populating it with the various
2500   // declarations it needs.
2501   return *Pos;
2502 }
2503
2504 std::pair<ObjCMethodList, ObjCMethodList>
2505 PCHReader::ReadMethodPool(Selector Sel) {
2506   if (!MethodPoolLookupTable)
2507     return std::pair<ObjCMethodList, ObjCMethodList>();
2508
2509   // Try to find this selector within our on-disk hash table.
2510   PCHMethodPoolLookupTable *PoolTable
2511     = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2512   PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
2513   if (Pos == PoolTable->end()) {
2514     ++NumMethodPoolMisses;
2515     return std::pair<ObjCMethodList, ObjCMethodList>();;
2516   }
2517
2518   ++NumMethodPoolSelectorsRead;
2519   return *Pos;
2520 }
2521
2522 void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
2523   assert(ID && "Non-zero identifier ID required");
2524   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
2525   IdentifiersLoaded[ID - 1] = II;
2526 }
2527
2528 /// \brief Set the globally-visible declarations associated with the given
2529 /// identifier.
2530 ///
2531 /// If the PCH reader is currently in a state where the given declaration IDs
2532 /// cannot safely be resolved, they are queued until it is safe to resolve
2533 /// them.
2534 ///
2535 /// \param II an IdentifierInfo that refers to one or more globally-visible
2536 /// declarations.
2537 ///
2538 /// \param DeclIDs the set of declaration IDs with the name @p II that are
2539 /// visible at global scope.
2540 ///
2541 /// \param Nonrecursive should be true to indicate that the caller knows that
2542 /// this call is non-recursive, and therefore the globally-visible declarations
2543 /// will not be placed onto the pending queue.
2544 void
2545 PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2546                               const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2547                                    bool Nonrecursive) {
2548   if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2549     PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2550     PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2551     PII.II = II;
2552     for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2553       PII.DeclIDs.push_back(DeclIDs[I]);
2554     return;
2555   }
2556
2557   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2558     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2559     if (SemaObj) {
2560       // Introduce this declaration into the translation-unit scope
2561       // and add it to the declaration chain for this identifier, so
2562       // that (unqualified) name lookup will find it.
2563       SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2564       SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2565     } else {
2566       // Queue this declaration so that it will be added to the
2567       // translation unit scope and identifier's declaration chain
2568       // once a Sema object is known.
2569       PreloadedDecls.push_back(D);
2570     }
2571   }
2572 }
2573
2574 IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
2575   if (ID == 0)
2576     return 0;
2577
2578   if (!IdentifierTableData || IdentifiersLoaded.empty()) {
2579     Error("no identifier table in PCH file");
2580     return 0;
2581   }
2582
2583   assert(PP && "Forgot to set Preprocessor ?");
2584   if (!IdentifiersLoaded[ID - 1]) {
2585     uint32_t Offset = IdentifierOffsets[ID - 1];
2586     const char *Str = IdentifierTableData + Offset;
2587
2588     // All of the strings in the PCH file are preceded by a 16-bit
2589     // length. Extract that 16-bit length to avoid having to execute
2590     // strlen().
2591     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2592     //  unsigned integers.  This is important to avoid integer overflow when
2593     //  we cast them to 'unsigned'.
2594     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
2595     unsigned StrLen = (((unsigned) StrLenPtr[0])
2596                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2597     IdentifiersLoaded[ID - 1]
2598       = &PP->getIdentifierTable().get(Str, Str + StrLen);
2599   }
2600
2601   return IdentifiersLoaded[ID - 1];
2602 }
2603
2604 void PCHReader::ReadSLocEntry(unsigned ID) {
2605   ReadSLocEntryRecord(ID);
2606 }
2607
2608 Selector PCHReader::DecodeSelector(unsigned ID) {
2609   if (ID == 0)
2610     return Selector();
2611
2612   if (!MethodPoolLookupTableData)
2613     return Selector();
2614
2615   if (ID > TotalNumSelectors) {
2616     Error("selector ID out of range in PCH file");
2617     return Selector();
2618   }
2619
2620   unsigned Index = ID - 1;
2621   if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2622     // Load this selector from the selector table.
2623     // FIXME: endianness portability issues with SelectorOffsets table
2624     PCHMethodPoolLookupTrait Trait(*this);
2625     SelectorsLoaded[Index]
2626       = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2627   }
2628
2629   return SelectorsLoaded[Index];
2630 }
2631
2632 DeclarationName
2633 PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2634   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2635   switch (Kind) {
2636   case DeclarationName::Identifier:
2637     return DeclarationName(GetIdentifierInfo(Record, Idx));
2638
2639   case DeclarationName::ObjCZeroArgSelector:
2640   case DeclarationName::ObjCOneArgSelector:
2641   case DeclarationName::ObjCMultiArgSelector:
2642     return DeclarationName(GetSelector(Record, Idx));
2643
2644   case DeclarationName::CXXConstructorName:
2645     return Context->DeclarationNames.getCXXConstructorName(
2646                           Context->getCanonicalType(GetType(Record[Idx++])));
2647
2648   case DeclarationName::CXXDestructorName:
2649     return Context->DeclarationNames.getCXXDestructorName(
2650                           Context->getCanonicalType(GetType(Record[Idx++])));
2651
2652   case DeclarationName::CXXConversionFunctionName:
2653     return Context->DeclarationNames.getCXXConversionFunctionName(
2654                           Context->getCanonicalType(GetType(Record[Idx++])));
2655
2656   case DeclarationName::CXXOperatorName:
2657     return Context->DeclarationNames.getCXXOperatorName(
2658                                        (OverloadedOperatorKind)Record[Idx++]);
2659
2660   case DeclarationName::CXXLiteralOperatorName:
2661     return Context->DeclarationNames.getCXXLiteralOperatorName(
2662                                        GetIdentifierInfo(Record, Idx));
2663
2664   case DeclarationName::CXXUsingDirective:
2665     return DeclarationName::getUsingDirectiveName();
2666   }
2667
2668   // Required to silence GCC warning
2669   return DeclarationName();
2670 }
2671
2672 /// \brief Read an integral value
2673 llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2674   unsigned BitWidth = Record[Idx++];
2675   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2676   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2677   Idx += NumWords;
2678   return Result;
2679 }
2680
2681 /// \brief Read a signed integral value
2682 llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2683   bool isUnsigned = Record[Idx++];
2684   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2685 }
2686
2687 /// \brief Read a floating-point value
2688 llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
2689   return llvm::APFloat(ReadAPInt(Record, Idx));
2690 }
2691
2692 // \brief Read a string
2693 std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2694   unsigned Len = Record[Idx++];
2695   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
2696   Idx += Len;
2697   return Result;
2698 }
2699
2700 DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
2701   return Diag(SourceLocation(), DiagID);
2702 }
2703
2704 DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2705   return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
2706 }
2707
2708 /// \brief Retrieve the identifier table associated with the
2709 /// preprocessor.
2710 IdentifierTable &PCHReader::getIdentifierTable() {
2711   assert(PP && "Forgot to set Preprocessor ?");
2712   return PP->getIdentifierTable();
2713 }
2714
2715 /// \brief Record that the given ID maps to the given switch-case
2716 /// statement.
2717 void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2718   assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2719   SwitchCaseStmts[ID] = SC;
2720 }
2721
2722 /// \brief Retrieve the switch-case statement with the given ID.
2723 SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2724   assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2725   return SwitchCaseStmts[ID];
2726 }
2727
2728 /// \brief Record that the given label statement has been
2729 /// deserialized and has the given ID.
2730 void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2731   assert(LabelStmts.find(ID) == LabelStmts.end() &&
2732          "Deserialized label twice");
2733   LabelStmts[ID] = S;
2734
2735   // If we've already seen any goto statements that point to this
2736   // label, resolve them now.
2737   typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2738   std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2739   for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2740     Goto->second->setLabel(S);
2741   UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
2742
2743   // If we've already seen any address-label statements that point to
2744   // this label, resolve them now.
2745   typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2746   std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2747     = UnresolvedAddrLabelExprs.equal_range(ID);
2748   for (AddrLabelIter AddrLabel = AddrLabels.first;
2749        AddrLabel != AddrLabels.second; ++AddrLabel)
2750     AddrLabel->second->setLabel(S);
2751   UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
2752 }
2753
2754 /// \brief Set the label of the given statement to the label
2755 /// identified by ID.
2756 ///
2757 /// Depending on the order in which the label and other statements
2758 /// referencing that label occur, this operation may complete
2759 /// immediately (updating the statement) or it may queue the
2760 /// statement to be back-patched later.
2761 void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2762   std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2763   if (Label != LabelStmts.end()) {
2764     // We've already seen this label, so set the label of the goto and
2765     // we're done.
2766     S->setLabel(Label->second);
2767   } else {
2768     // We haven't seen this label yet, so add this goto to the set of
2769     // unresolved goto statements.
2770     UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2771   }
2772 }
2773
2774 /// \brief Set the label of the given expression to the label
2775 /// identified by ID.
2776 ///
2777 /// Depending on the order in which the label and other statements
2778 /// referencing that label occur, this operation may complete
2779 /// immediately (updating the statement) or it may queue the
2780 /// statement to be back-patched later.
2781 void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2782   std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2783   if (Label != LabelStmts.end()) {
2784     // We've already seen this label, so set the label of the
2785     // label-address expression and we're done.
2786     S->setLabel(Label->second);
2787   } else {
2788     // We haven't seen this label yet, so add this label-address
2789     // expression to the set of unresolved label-address expressions.
2790     UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2791   }
2792 }
2793
2794
2795 PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2796   : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2797   Reader.CurrentlyLoadingTypeOrDecl = this;
2798 }
2799
2800 PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2801   if (!Parent) {
2802     // If any identifiers with corresponding top-level declarations have
2803     // been loaded, load those declarations now.
2804     while (!Reader.PendingIdentifierInfos.empty()) {
2805       Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2806                                  Reader.PendingIdentifierInfos.front().DeclIDs,
2807                                      true);
2808       Reader.PendingIdentifierInfos.pop_front();
2809     }
2810   }
2811
2812   Reader.CurrentlyLoadingTypeOrDecl = Parent;
2813 }