SourceManager.cpp revision f715ca12bfc9fddfde75f98a197424434428b821
1//===--- SourceManager.cpp - Track and cache source files -----------------===//
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 implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/SourceManagerInternals.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/FileManager.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/raw_ostream.h"
21#include "llvm/System/Path.h"
22#include <algorithm>
23#include <string>
24#include <cstring>
25#include <cstdio>
26
27using namespace clang;
28using namespace SrcMgr;
29using llvm::MemoryBuffer;
30
31//===----------------------------------------------------------------------===//
32// SourceManager Helper Classes
33//===----------------------------------------------------------------------===//
34
35struct BufferResult::FailureData {
36  const llvm::MemoryBuffer *Buffer;
37  const char *FileName;
38  std::string ErrorStr;
39};
40
41BufferResult::BufferResult(const BufferResult &Other) {
42  if (const llvm::MemoryBuffer *Buffer
43                        = Other.Data.dyn_cast<const llvm::MemoryBuffer *>()) {
44    Data = Buffer;
45    return;
46  }
47
48  Data = new FailureData(*Other.Data.get<FailureData *>());
49}
50
51BufferResult::BufferResult(const char *FileName, llvm::StringRef ErrorStr,
52                           const llvm::MemoryBuffer *Buffer) {
53  FailureData *FD = new FailureData;
54  FD->FileName = FileName;
55  FD->ErrorStr = ErrorStr;
56  FD->Buffer = Buffer;
57  Data = FD;
58}
59
60BufferResult::~BufferResult() {
61  if (FailureData *FD = Data.dyn_cast<FailureData *>())
62    delete FD;
63}
64
65bool BufferResult::isInvalid() const {
66  return Data.is<FailureData *>();
67}
68
69const llvm::MemoryBuffer *BufferResult::getBuffer(Diagnostic &Diags) const {
70  llvm::StringRef FileName;
71  std::string ErrorMsg;
72  const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
73  if (!ErrorMsg.empty()) {
74    Diags.Report(diag::err_cannot_open_file)
75      << FileName << ErrorMsg;
76  }
77  return Result;
78}
79
80const llvm::MemoryBuffer *BufferResult::getBuffer(llvm::StringRef &FileName,
81                                                  std::string &Error) const {
82  if (const llvm::MemoryBuffer *Buffer
83                                  = Data.dyn_cast<const llvm::MemoryBuffer *>())
84    return Buffer;
85
86  FailureData *Fail = Data.get<FailureData *>();
87  FileName = Fail->FileName;
88  Error = Fail->ErrorStr;
89  return Fail->Buffer;
90}
91
92BufferResult::operator const llvm::MemoryBuffer *() const {
93  llvm::StringRef FileName;
94  std::string ErrorMsg;
95  const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
96  if (!ErrorMsg.empty()) {
97    fprintf(stderr, "error: cannot open file '%s': %s\n",
98            FileName.str().c_str(), ErrorMsg.c_str());
99  }
100
101  return Result;
102}
103
104ContentCache::~ContentCache() {
105  delete Buffer;
106}
107
108/// getSizeBytesMapped - Returns the number of bytes actually mapped for
109///  this ContentCache.  This can be 0 if the MemBuffer was not actually
110///  instantiated.
111unsigned ContentCache::getSizeBytesMapped() const {
112  return Buffer ? Buffer->getBufferSize() : 0;
113}
114
115/// getSize - Returns the size of the content encapsulated by this ContentCache.
116///  This can be the size of the source file or the size of an arbitrary
117///  scratch buffer.  If the ContentCache encapsulates a source file, that
118///  file is not lazily brought in from disk to satisfy this query.
119unsigned ContentCache::getSize() const {
120  return Buffer ? (unsigned) Buffer->getBufferSize()
121                : (unsigned) Entry->getSize();
122}
123
124void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
125  assert(B != Buffer);
126
127  delete Buffer;
128  Buffer = B;
129}
130
131BufferResult ContentCache::getBuffer() const {
132  // Lazily create the Buffer for ContentCaches that wrap files.
133  if (!Buffer && Entry) {
134    std::string ErrorStr;
135    struct stat FileInfo;
136    Buffer = MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
137                                   Entry->getSize(), &FileInfo);
138
139    // If we were unable to open the file, then we are in an inconsistent
140    // situation where the content cache referenced a file which no longer
141    // exists. Most likely, we were using a stat cache with an invalid entry but
142    // the file could also have been removed during processing. Since we can't
143    // really deal with this situation, just create an empty buffer.
144    //
145    // FIXME: This is definitely not ideal, but our immediate clients can't
146    // currently handle returning a null entry here. Ideally we should detect
147    // that we are in an inconsistent situation and error out as quickly as
148    // possible.
149    if (!Buffer) {
150      const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
151      Buffer = MemoryBuffer::getNewMemBuffer(Entry->getSize(), "<invalid>");
152      char *Ptr = const_cast<char*>(Buffer->getBufferStart());
153      for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
154        Ptr[i] = FillStr[i % FillStr.size()];
155      return BufferResult(Entry->getName(), ErrorStr, Buffer);
156    } else {
157      // Check that the file's size and modification time is the same as
158      // in the file entry (which may have come from a stat cache).
159      // FIXME: Make these strings localizable.
160      if (FileInfo.st_size != Entry->getSize()) {
161        ErrorStr = "file has changed size since it was originally read";
162        return BufferResult(Entry->getName(), ErrorStr, Buffer);
163      } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
164        ErrorStr = "file has been modified since it was originally read";
165        return BufferResult(Entry->getName(), ErrorStr, Buffer);
166      }
167    }
168  }
169
170  return Buffer;
171}
172
173unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
174  // Look up the filename in the string table, returning the pre-existing value
175  // if it exists.
176  llvm::StringMapEntry<unsigned> &Entry =
177    FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
178  if (Entry.getValue() != ~0U)
179    return Entry.getValue();
180
181  // Otherwise, assign this the next available ID.
182  Entry.setValue(FilenamesByID.size());
183  FilenamesByID.push_back(&Entry);
184  return FilenamesByID.size()-1;
185}
186
187/// AddLineNote - Add a line note to the line table that indicates that there
188/// is a #line at the specified FID/Offset location which changes the presumed
189/// location to LineNo/FilenameID.
190void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
191                                unsigned LineNo, int FilenameID) {
192  std::vector<LineEntry> &Entries = LineEntries[FID];
193
194  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195         "Adding line entries out of order!");
196
197  SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
198  unsigned IncludeOffset = 0;
199
200  if (!Entries.empty()) {
201    // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202    // that we are still in "foo.h".
203    if (FilenameID == -1)
204      FilenameID = Entries.back().FilenameID;
205
206    // If we are after a line marker that switched us to system header mode, or
207    // that set #include information, preserve it.
208    Kind = Entries.back().FileKind;
209    IncludeOffset = Entries.back().IncludeOffset;
210  }
211
212  Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
213                                   IncludeOffset));
214}
215
216/// AddLineNote This is the same as the previous version of AddLineNote, but is
217/// used for GNU line markers.  If EntryExit is 0, then this doesn't change the
218/// presumed #include stack.  If it is 1, this is a file entry, if it is 2 then
219/// this is a file exit.  FileKind specifies whether this is a system header or
220/// extern C system header.
221void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
222                                unsigned LineNo, int FilenameID,
223                                unsigned EntryExit,
224                                SrcMgr::CharacteristicKind FileKind) {
225  assert(FilenameID != -1 && "Unspecified filename should use other accessor");
226
227  std::vector<LineEntry> &Entries = LineEntries[FID];
228
229  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230         "Adding line entries out of order!");
231
232  unsigned IncludeOffset = 0;
233  if (EntryExit == 0) {  // No #include stack change.
234    IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235  } else if (EntryExit == 1) {
236    IncludeOffset = Offset-1;
237  } else if (EntryExit == 2) {
238    assert(!Entries.empty() && Entries.back().IncludeOffset &&
239       "PPDirectives should have caught case when popping empty include stack");
240
241    // Get the include loc of the last entries' include loc as our include loc.
242    IncludeOffset = 0;
243    if (const LineEntry *PrevEntry =
244          FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245      IncludeOffset = PrevEntry->IncludeOffset;
246  }
247
248  Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
249                                   IncludeOffset));
250}
251
252
253/// FindNearestLineEntry - Find the line entry nearest to FID that is before
254/// it.  If there is no line entry before Offset in FID, return null.
255const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
256                                                     unsigned Offset) {
257  const std::vector<LineEntry> &Entries = LineEntries[FID];
258  assert(!Entries.empty() && "No #line entries for this FID after all!");
259
260  // It is very common for the query to be after the last #line, check this
261  // first.
262  if (Entries.back().FileOffset <= Offset)
263    return &Entries.back();
264
265  // Do a binary search to find the maximal element that is still before Offset.
266  std::vector<LineEntry>::const_iterator I =
267    std::upper_bound(Entries.begin(), Entries.end(), Offset);
268  if (I == Entries.begin()) return 0;
269  return &*--I;
270}
271
272/// \brief Add a new line entry that has already been encoded into
273/// the internal representation of the line table.
274void LineTableInfo::AddEntry(unsigned FID,
275                             const std::vector<LineEntry> &Entries) {
276  LineEntries[FID] = Entries;
277}
278
279/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
280///
281unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
282  if (LineTable == 0)
283    LineTable = new LineTableInfo();
284  return LineTable->getLineTableFilenameID(Ptr, Len);
285}
286
287
288/// AddLineNote - Add a line note to the line table for the FileID and offset
289/// specified by Loc.  If FilenameID is -1, it is considered to be
290/// unspecified.
291void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
292                                int FilenameID) {
293  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
294
295  const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
296
297  // Remember that this file has #line directives now if it doesn't already.
298  const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
299
300  if (LineTable == 0)
301    LineTable = new LineTableInfo();
302  LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
303}
304
305/// AddLineNote - Add a GNU line marker to the line table.
306void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
307                                int FilenameID, bool IsFileEntry,
308                                bool IsFileExit, bool IsSystemHeader,
309                                bool IsExternCHeader) {
310  // If there is no filename and no flags, this is treated just like a #line,
311  // which does not change the flags of the previous line marker.
312  if (FilenameID == -1) {
313    assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
314           "Can't set flags without setting the filename!");
315    return AddLineNote(Loc, LineNo, FilenameID);
316  }
317
318  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
319  const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
320
321  // Remember that this file has #line directives now if it doesn't already.
322  const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
323
324  if (LineTable == 0)
325    LineTable = new LineTableInfo();
326
327  SrcMgr::CharacteristicKind FileKind;
328  if (IsExternCHeader)
329    FileKind = SrcMgr::C_ExternCSystem;
330  else if (IsSystemHeader)
331    FileKind = SrcMgr::C_System;
332  else
333    FileKind = SrcMgr::C_User;
334
335  unsigned EntryExit = 0;
336  if (IsFileEntry)
337    EntryExit = 1;
338  else if (IsFileExit)
339    EntryExit = 2;
340
341  LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
342                         EntryExit, FileKind);
343}
344
345LineTableInfo &SourceManager::getLineTable() {
346  if (LineTable == 0)
347    LineTable = new LineTableInfo();
348  return *LineTable;
349}
350
351//===----------------------------------------------------------------------===//
352// Private 'Create' methods.
353//===----------------------------------------------------------------------===//
354
355SourceManager::~SourceManager() {
356  delete LineTable;
357
358  // Delete FileEntry objects corresponding to content caches.  Since the actual
359  // content cache objects are bump pointer allocated, we just have to run the
360  // dtors, but we call the deallocate method for completeness.
361  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
362    MemBufferInfos[i]->~ContentCache();
363    ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
364  }
365  for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
366       I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
367    I->second->~ContentCache();
368    ContentCacheAlloc.Deallocate(I->second);
369  }
370}
371
372void SourceManager::clearIDTables() {
373  MainFileID = FileID();
374  SLocEntryTable.clear();
375  LastLineNoFileIDQuery = FileID();
376  LastLineNoContentCache = 0;
377  LastFileIDLookup = FileID();
378
379  if (LineTable)
380    LineTable->clear();
381
382  // Use up FileID #0 as an invalid instantiation.
383  NextOffset = 0;
384  createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
385}
386
387/// getOrCreateContentCache - Create or return a cached ContentCache for the
388/// specified file.
389const ContentCache *
390SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
391  assert(FileEnt && "Didn't specify a file entry to use?");
392
393  // Do we already have information about this file?
394  ContentCache *&Entry = FileInfos[FileEnt];
395  if (Entry) return Entry;
396
397  // Nope, create a new Cache entry.  Make sure it is at least 8-byte aligned
398  // so that FileInfo can use the low 3 bits of the pointer for its own
399  // nefarious purposes.
400  unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
401  EntryAlign = std::max(8U, EntryAlign);
402  Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
403  new (Entry) ContentCache(FileEnt);
404  return Entry;
405}
406
407
408/// createMemBufferContentCache - Create a new ContentCache for the specified
409///  memory buffer.  This does no caching.
410const ContentCache*
411SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
412  // Add a new ContentCache to the MemBufferInfos list and return it.  Make sure
413  // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
414  // the pointer for its own nefarious purposes.
415  unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
416  EntryAlign = std::max(8U, EntryAlign);
417  ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
418  new (Entry) ContentCache();
419  MemBufferInfos.push_back(Entry);
420  Entry->setBuffer(Buffer);
421  return Entry;
422}
423
424void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
425                                           unsigned NumSLocEntries,
426                                           unsigned NextOffset) {
427  ExternalSLocEntries = Source;
428  this->NextOffset = NextOffset;
429  SLocEntryLoaded.resize(NumSLocEntries + 1);
430  SLocEntryLoaded[0] = true;
431  SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
432}
433
434void SourceManager::ClearPreallocatedSLocEntries() {
435  unsigned I = 0;
436  for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
437    if (!SLocEntryLoaded[I])
438      break;
439
440  // We've already loaded all preallocated source location entries.
441  if (I == SLocEntryLoaded.size())
442    return;
443
444  // Remove everything from location I onward.
445  SLocEntryTable.resize(I);
446  SLocEntryLoaded.clear();
447  ExternalSLocEntries = 0;
448}
449
450
451//===----------------------------------------------------------------------===//
452// Methods to create new FileID's and instantiations.
453//===----------------------------------------------------------------------===//
454
455/// createFileID - Create a new fileID for the specified ContentCache and
456/// include position.  This works regardless of whether the ContentCache
457/// corresponds to a file or some other input source.
458FileID SourceManager::createFileID(const ContentCache *File,
459                                   SourceLocation IncludePos,
460                                   SrcMgr::CharacteristicKind FileCharacter,
461                                   unsigned PreallocatedID,
462                                   unsigned Offset) {
463  if (PreallocatedID) {
464    // If we're filling in a preallocated ID, just load in the file
465    // entry and return.
466    assert(PreallocatedID < SLocEntryLoaded.size() &&
467           "Preallocate ID out-of-range");
468    assert(!SLocEntryLoaded[PreallocatedID] &&
469           "Source location entry already loaded");
470    assert(Offset && "Preallocate source location cannot have zero offset");
471    SLocEntryTable[PreallocatedID]
472      = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
473    SLocEntryLoaded[PreallocatedID] = true;
474    FileID FID = FileID::get(PreallocatedID);
475    return LastFileIDLookup = FID;
476  }
477
478  SLocEntryTable.push_back(SLocEntry::get(NextOffset,
479                                          FileInfo::get(IncludePos, File,
480                                                        FileCharacter)));
481  unsigned FileSize = File->getSize();
482  assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
483  NextOffset += FileSize+1;
484
485  // Set LastFileIDLookup to the newly created file.  The next getFileID call is
486  // almost guaranteed to be from that file.
487  FileID FID = FileID::get(SLocEntryTable.size()-1);
488  return LastFileIDLookup = FID;
489}
490
491/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
492/// that a token from SpellingLoc should actually be referenced from
493/// InstantiationLoc.
494SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
495                                                     SourceLocation ILocStart,
496                                                     SourceLocation ILocEnd,
497                                                     unsigned TokLength,
498                                                     unsigned PreallocatedID,
499                                                     unsigned Offset) {
500  InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
501  if (PreallocatedID) {
502    // If we're filling in a preallocated ID, just load in the
503    // instantiation entry and return.
504    assert(PreallocatedID < SLocEntryLoaded.size() &&
505           "Preallocate ID out-of-range");
506    assert(!SLocEntryLoaded[PreallocatedID] &&
507           "Source location entry already loaded");
508    assert(Offset && "Preallocate source location cannot have zero offset");
509    SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
510    SLocEntryLoaded[PreallocatedID] = true;
511    return SourceLocation::getMacroLoc(Offset);
512  }
513  SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
514  assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
515  NextOffset += TokLength+1;
516  return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
517}
518
519BufferResult SourceManager::getMemoryBufferForFile(const FileEntry *File) {
520  const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
521  assert(IR && "getOrCreateContentCache() cannot return NULL");
522  return IR->getBuffer();
523}
524
525bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
526                                         const llvm::MemoryBuffer *Buffer) {
527  const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
528  if (IR == 0)
529    return true;
530
531  const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
532  return false;
533}
534
535std::pair<const char*, const char*>
536SourceManager::getBufferData(FileID FID, bool *Invalid) const {
537  if (Invalid)
538    *Invalid = false;
539
540  const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(Diag);
541  if (!Buf) {
542    if (*Invalid)
543      *Invalid = true;
544    const char *FakeText = "";
545    return std::make_pair(FakeText, FakeText + strlen(FakeText));
546  }
547  return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
548}
549
550//===----------------------------------------------------------------------===//
551// SourceLocation manipulation methods.
552//===----------------------------------------------------------------------===//
553
554/// getFileIDSlow - Return the FileID for a SourceLocation.  This is a very hot
555/// method that is used for all SourceManager queries that start with a
556/// SourceLocation object.  It is responsible for finding the entry in
557/// SLocEntryTable which contains the specified location.
558///
559FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
560  assert(SLocOffset && "Invalid FileID");
561
562  // After the first and second level caches, I see two common sorts of
563  // behavior: 1) a lot of searched FileID's are "near" the cached file location
564  // or are "near" the cached instantiation location.  2) others are just
565  // completely random and may be a very long way away.
566  //
567  // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
568  // then we fall back to a less cache efficient, but more scalable, binary
569  // search to find the location.
570
571  // See if this is near the file point - worst case we start scanning from the
572  // most newly created FileID.
573  std::vector<SrcMgr::SLocEntry>::const_iterator I;
574
575  if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
576    // Neither loc prunes our search.
577    I = SLocEntryTable.end();
578  } else {
579    // Perhaps it is near the file point.
580    I = SLocEntryTable.begin()+LastFileIDLookup.ID;
581  }
582
583  // Find the FileID that contains this.  "I" is an iterator that points to a
584  // FileID whose offset is known to be larger than SLocOffset.
585  unsigned NumProbes = 0;
586  while (1) {
587    --I;
588    if (ExternalSLocEntries)
589      getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
590    if (I->getOffset() <= SLocOffset) {
591#if 0
592      printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
593             I-SLocEntryTable.begin(),
594             I->isInstantiation() ? "inst" : "file",
595             LastFileIDLookup.ID,  int(SLocEntryTable.end()-I));
596#endif
597      FileID Res = FileID::get(I-SLocEntryTable.begin());
598
599      // If this isn't an instantiation, remember it.  We have good locality
600      // across FileID lookups.
601      if (!I->isInstantiation())
602        LastFileIDLookup = Res;
603      NumLinearScans += NumProbes+1;
604      return Res;
605    }
606    if (++NumProbes == 8)
607      break;
608  }
609
610  // Convert "I" back into an index.  We know that it is an entry whose index is
611  // larger than the offset we are looking for.
612  unsigned GreaterIndex = I-SLocEntryTable.begin();
613  // LessIndex - This is the lower bound of the range that we're searching.
614  // We know that the offset corresponding to the FileID is is less than
615  // SLocOffset.
616  unsigned LessIndex = 0;
617  NumProbes = 0;
618  while (1) {
619    unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
620    unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
621
622    ++NumProbes;
623
624    // If the offset of the midpoint is too large, chop the high side of the
625    // range to the midpoint.
626    if (MidOffset > SLocOffset) {
627      GreaterIndex = MiddleIndex;
628      continue;
629    }
630
631    // If the middle index contains the value, succeed and return.
632    if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
633#if 0
634      printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
635             I-SLocEntryTable.begin(),
636             I->isInstantiation() ? "inst" : "file",
637             LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
638#endif
639      FileID Res = FileID::get(MiddleIndex);
640
641      // If this isn't an instantiation, remember it.  We have good locality
642      // across FileID lookups.
643      if (!I->isInstantiation())
644        LastFileIDLookup = Res;
645      NumBinaryProbes += NumProbes;
646      return Res;
647    }
648
649    // Otherwise, move the low-side up to the middle index.
650    LessIndex = MiddleIndex;
651  }
652}
653
654SourceLocation SourceManager::
655getInstantiationLocSlowCase(SourceLocation Loc) const {
656  do {
657    // Note: If Loc indicates an offset into a token that came from a macro
658    // expansion (e.g. the 5th character of the token) we do not want to add
659    // this offset when going to the instantiation location.  The instatiation
660    // location is the macro invocation, which the offset has nothing to do
661    // with.  This is unlike when we get the spelling loc, because the offset
662    // directly correspond to the token whose spelling we're inspecting.
663    Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
664                   .getInstantiationLocStart();
665  } while (!Loc.isFileID());
666
667  return Loc;
668}
669
670SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
671  do {
672    std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
673    Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
674    Loc = Loc.getFileLocWithOffset(LocInfo.second);
675  } while (!Loc.isFileID());
676  return Loc;
677}
678
679
680std::pair<FileID, unsigned>
681SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
682                                                     unsigned Offset) const {
683  // If this is an instantiation record, walk through all the instantiation
684  // points.
685  FileID FID;
686  SourceLocation Loc;
687  do {
688    Loc = E->getInstantiation().getInstantiationLocStart();
689
690    FID = getFileID(Loc);
691    E = &getSLocEntry(FID);
692    Offset += Loc.getOffset()-E->getOffset();
693  } while (!Loc.isFileID());
694
695  return std::make_pair(FID, Offset);
696}
697
698std::pair<FileID, unsigned>
699SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
700                                                unsigned Offset) const {
701  // If this is an instantiation record, walk through all the instantiation
702  // points.
703  FileID FID;
704  SourceLocation Loc;
705  do {
706    Loc = E->getInstantiation().getSpellingLoc();
707
708    FID = getFileID(Loc);
709    E = &getSLocEntry(FID);
710    Offset += Loc.getOffset()-E->getOffset();
711  } while (!Loc.isFileID());
712
713  return std::make_pair(FID, Offset);
714}
715
716/// getImmediateSpellingLoc - Given a SourceLocation object, return the
717/// spelling location referenced by the ID.  This is the first level down
718/// towards the place where the characters that make up the lexed token can be
719/// found.  This should not generally be used by clients.
720SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
721  if (Loc.isFileID()) return Loc;
722  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
723  Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
724  return Loc.getFileLocWithOffset(LocInfo.second);
725}
726
727
728/// getImmediateInstantiationRange - Loc is required to be an instantiation
729/// location.  Return the start/end of the instantiation information.
730std::pair<SourceLocation,SourceLocation>
731SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
732  assert(Loc.isMacroID() && "Not an instantiation loc!");
733  const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
734  return II.getInstantiationLocRange();
735}
736
737/// getInstantiationRange - Given a SourceLocation object, return the
738/// range of tokens covered by the instantiation in the ultimate file.
739std::pair<SourceLocation,SourceLocation>
740SourceManager::getInstantiationRange(SourceLocation Loc) const {
741  if (Loc.isFileID()) return std::make_pair(Loc, Loc);
742
743  std::pair<SourceLocation,SourceLocation> Res =
744    getImmediateInstantiationRange(Loc);
745
746  // Fully resolve the start and end locations to their ultimate instantiation
747  // points.
748  while (!Res.first.isFileID())
749    Res.first = getImmediateInstantiationRange(Res.first).first;
750  while (!Res.second.isFileID())
751    Res.second = getImmediateInstantiationRange(Res.second).second;
752  return Res;
753}
754
755
756
757//===----------------------------------------------------------------------===//
758// Queries about the code at a SourceLocation.
759//===----------------------------------------------------------------------===//
760
761/// getCharacterData - Return a pointer to the start of the specified location
762/// in the appropriate MemoryBuffer.
763const char *SourceManager::getCharacterData(SourceLocation SL) const {
764  // Note that this is a hot function in the getSpelling() path, which is
765  // heavily used by -E mode.
766  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
767
768  // Note that calling 'getBuffer()' may lazily page in a source file.
769  return getSLocEntry(LocInfo.first).getFile().getContentCache()
770              ->getBuffer()->getBufferStart() + LocInfo.second;
771}
772
773
774/// getColumnNumber - Return the column # for the specified file position.
775/// this is significantly cheaper to compute than the line number.
776unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
777  const char *Buf = getBuffer(FID)->getBufferStart();
778
779  unsigned LineStart = FilePos;
780  while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
781    --LineStart;
782  return FilePos-LineStart+1;
783}
784
785unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
786  if (Loc.isInvalid()) return 0;
787  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
788  return getColumnNumber(LocInfo.first, LocInfo.second);
789}
790
791unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
792  if (Loc.isInvalid()) return 0;
793  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
794  return getColumnNumber(LocInfo.first, LocInfo.second);
795}
796
797
798
799static DISABLE_INLINE void ComputeLineNumbers(ContentCache* FI,
800                                              llvm::BumpPtrAllocator &Alloc);
801static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
802  // Note that calling 'getBuffer()' may lazily page in the file.
803  const MemoryBuffer *Buffer = FI->getBuffer();
804
805  // Find the file offsets of all of the *physical* source lines.  This does
806  // not look at trigraphs, escaped newlines, or anything else tricky.
807  std::vector<unsigned> LineOffsets;
808
809  // Line #1 starts at char 0.
810  LineOffsets.push_back(0);
811
812  const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
813  const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
814  unsigned Offs = 0;
815  while (1) {
816    // Skip over the contents of the line.
817    // TODO: Vectorize this?  This is very performance sensitive for programs
818    // with lots of diagnostics and in -E mode.
819    const unsigned char *NextBuf = (const unsigned char *)Buf;
820    while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
821      ++NextBuf;
822    Offs += NextBuf-Buf;
823    Buf = NextBuf;
824
825    if (Buf[0] == '\n' || Buf[0] == '\r') {
826      // If this is \n\r or \r\n, skip both characters.
827      if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
828        ++Offs, ++Buf;
829      ++Offs, ++Buf;
830      LineOffsets.push_back(Offs);
831    } else {
832      // Otherwise, this is a null.  If end of file, exit.
833      if (Buf == End) break;
834      // Otherwise, skip the null.
835      ++Offs, ++Buf;
836    }
837  }
838
839  // Copy the offsets into the FileInfo structure.
840  FI->NumLines = LineOffsets.size();
841  FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
842  std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
843}
844
845/// getLineNumber - Given a SourceLocation, return the spelling line number
846/// for the position indicated.  This requires building and caching a table of
847/// line offsets for the MemoryBuffer, so this is not cheap: use only when
848/// about to emit a diagnostic.
849unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
850  ContentCache *Content;
851  if (LastLineNoFileIDQuery == FID)
852    Content = LastLineNoContentCache;
853  else
854    Content = const_cast<ContentCache*>(getSLocEntry(FID)
855                                        .getFile().getContentCache());
856
857  // If this is the first use of line information for this buffer, compute the
858  /// SourceLineCache for it on demand.
859  if (Content->SourceLineCache == 0)
860    ComputeLineNumbers(Content, ContentCacheAlloc);
861
862  // Okay, we know we have a line number table.  Do a binary search to find the
863  // line number that this character position lands on.
864  unsigned *SourceLineCache = Content->SourceLineCache;
865  unsigned *SourceLineCacheStart = SourceLineCache;
866  unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
867
868  unsigned QueriedFilePos = FilePos+1;
869
870  // FIXME: I would like to be convinced that this code is worth being as
871  // complicated as it is, binary search isn't that slow.
872  //
873  // If it is worth being optimized, then in my opinion it could be more
874  // performant, simpler, and more obviously correct by just "galloping" outward
875  // from the queried file position. In fact, this could be incorporated into a
876  // generic algorithm such as lower_bound_with_hint.
877  //
878  // If someone gives me a test case where this matters, and I will do it! - DWD
879
880  // If the previous query was to the same file, we know both the file pos from
881  // that query and the line number returned.  This allows us to narrow the
882  // search space from the entire file to something near the match.
883  if (LastLineNoFileIDQuery == FID) {
884    if (QueriedFilePos >= LastLineNoFilePos) {
885      // FIXME: Potential overflow?
886      SourceLineCache = SourceLineCache+LastLineNoResult-1;
887
888      // The query is likely to be nearby the previous one.  Here we check to
889      // see if it is within 5, 10 or 20 lines.  It can be far away in cases
890      // where big comment blocks and vertical whitespace eat up lines but
891      // contribute no tokens.
892      if (SourceLineCache+5 < SourceLineCacheEnd) {
893        if (SourceLineCache[5] > QueriedFilePos)
894          SourceLineCacheEnd = SourceLineCache+5;
895        else if (SourceLineCache+10 < SourceLineCacheEnd) {
896          if (SourceLineCache[10] > QueriedFilePos)
897            SourceLineCacheEnd = SourceLineCache+10;
898          else if (SourceLineCache+20 < SourceLineCacheEnd) {
899            if (SourceLineCache[20] > QueriedFilePos)
900              SourceLineCacheEnd = SourceLineCache+20;
901          }
902        }
903      }
904    } else {
905      if (LastLineNoResult < Content->NumLines)
906        SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
907    }
908  }
909
910  // If the spread is large, do a "radix" test as our initial guess, based on
911  // the assumption that lines average to approximately the same length.
912  // NOTE: This is currently disabled, as it does not appear to be profitable in
913  // initial measurements.
914  if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
915    unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
916
917    // Take a stab at guessing where it is.
918    unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
919
920    // Check for -10 and +10 lines.
921    unsigned LowerBound = std::max(int(ApproxPos-10), 0);
922    unsigned UpperBound = std::min(ApproxPos+10, FileLen);
923
924    // If the computed lower bound is less than the query location, move it in.
925    if (SourceLineCache < SourceLineCacheStart+LowerBound &&
926        SourceLineCacheStart[LowerBound] < QueriedFilePos)
927      SourceLineCache = SourceLineCacheStart+LowerBound;
928
929    // If the computed upper bound is greater than the query location, move it.
930    if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
931        SourceLineCacheStart[UpperBound] >= QueriedFilePos)
932      SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
933  }
934
935  unsigned *Pos
936    = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
937  unsigned LineNo = Pos-SourceLineCacheStart;
938
939  LastLineNoFileIDQuery = FID;
940  LastLineNoContentCache = Content;
941  LastLineNoFilePos = QueriedFilePos;
942  LastLineNoResult = LineNo;
943  return LineNo;
944}
945
946unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
947  if (Loc.isInvalid()) return 0;
948  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
949  return getLineNumber(LocInfo.first, LocInfo.second);
950}
951unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
952  if (Loc.isInvalid()) return 0;
953  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
954  return getLineNumber(LocInfo.first, LocInfo.second);
955}
956
957/// getFileCharacteristic - return the file characteristic of the specified
958/// source location, indicating whether this is a normal file, a system
959/// header, or an "implicit extern C" system header.
960///
961/// This state can be modified with flags on GNU linemarker directives like:
962///   # 4 "foo.h" 3
963/// which changes all source locations in the current file after that to be
964/// considered to be from a system header.
965SrcMgr::CharacteristicKind
966SourceManager::getFileCharacteristic(SourceLocation Loc) const {
967  assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
968  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
969  const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
970
971  // If there are no #line directives in this file, just return the whole-file
972  // state.
973  if (!FI.hasLineDirectives())
974    return FI.getFileCharacteristic();
975
976  assert(LineTable && "Can't have linetable entries without a LineTable!");
977  // See if there is a #line directive before the location.
978  const LineEntry *Entry =
979    LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
980
981  // If this is before the first line marker, use the file characteristic.
982  if (!Entry)
983    return FI.getFileCharacteristic();
984
985  return Entry->FileKind;
986}
987
988/// Return the filename or buffer identifier of the buffer the location is in.
989/// Note that this name does not respect #line directives.  Use getPresumedLoc
990/// for normal clients.
991const char *SourceManager::getBufferName(SourceLocation Loc) const {
992  if (Loc.isInvalid()) return "<invalid loc>";
993
994  return getBuffer(getFileID(Loc))->getBufferIdentifier();
995}
996
997
998/// getPresumedLoc - This method returns the "presumed" location of a
999/// SourceLocation specifies.  A "presumed location" can be modified by #line
1000/// or GNU line marker directives.  This provides a view on the data that a
1001/// user should see in diagnostics, for example.
1002///
1003/// Note that a presumed location is always given as the instantiation point
1004/// of an instantiation location, not at the spelling location.
1005PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1006  if (Loc.isInvalid()) return PresumedLoc();
1007
1008  // Presumed locations are always for instantiation points.
1009  std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1010
1011  const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1012  const SrcMgr::ContentCache *C = FI.getContentCache();
1013
1014  // To get the source name, first consult the FileEntry (if one exists)
1015  // before the MemBuffer as this will avoid unnecessarily paging in the
1016  // MemBuffer.
1017  const char *Filename =
1018    C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
1019  unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1020  unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second);
1021  SourceLocation IncludeLoc = FI.getIncludeLoc();
1022
1023  // If we have #line directives in this file, update and overwrite the physical
1024  // location info if appropriate.
1025  if (FI.hasLineDirectives()) {
1026    assert(LineTable && "Can't have linetable entries without a LineTable!");
1027    // See if there is a #line directive before this.  If so, get it.
1028    if (const LineEntry *Entry =
1029          LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
1030      // If the LineEntry indicates a filename, use it.
1031      if (Entry->FilenameID != -1)
1032        Filename = LineTable->getFilename(Entry->FilenameID);
1033
1034      // Use the line number specified by the LineEntry.  This line number may
1035      // be multiple lines down from the line entry.  Add the difference in
1036      // physical line numbers from the query point and the line marker to the
1037      // total.
1038      unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1039      LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1040
1041      // Note that column numbers are not molested by line markers.
1042
1043      // Handle virtual #include manipulation.
1044      if (Entry->IncludeOffset) {
1045        IncludeLoc = getLocForStartOfFile(LocInfo.first);
1046        IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1047      }
1048    }
1049  }
1050
1051  return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
1052}
1053
1054//===----------------------------------------------------------------------===//
1055// Other miscellaneous methods.
1056//===----------------------------------------------------------------------===//
1057
1058/// \brief Get the source location for the given file:line:col triplet.
1059///
1060/// If the source file is included multiple times, the source location will
1061/// be based upon the first inclusion.
1062SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1063                                          unsigned Line, unsigned Col) const {
1064  assert(SourceFile && "Null source file!");
1065  assert(Line && Col && "Line and column should start from 1!");
1066
1067  fileinfo_iterator FI = FileInfos.find(SourceFile);
1068  if (FI == FileInfos.end())
1069    return SourceLocation();
1070  ContentCache *Content = FI->second;
1071
1072  // If this is the first use of line information for this buffer, compute the
1073  /// SourceLineCache for it on demand.
1074  if (Content->SourceLineCache == 0)
1075    ComputeLineNumbers(Content, ContentCacheAlloc);
1076
1077  // Find the first file ID that corresponds to the given file.
1078  FileID FirstFID;
1079
1080  // First, check the main file ID, since it is common to look for a
1081  // location in the main file.
1082  if (!MainFileID.isInvalid()) {
1083    const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1084    if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1085      FirstFID = MainFileID;
1086  }
1087
1088  if (FirstFID.isInvalid()) {
1089    // The location we're looking for isn't in the main file; look
1090    // through all of the source locations.
1091    for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1092      const SLocEntry &SLoc = getSLocEntry(I);
1093      if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1094        FirstFID = FileID::get(I);
1095        break;
1096      }
1097    }
1098  }
1099
1100  if (FirstFID.isInvalid())
1101    return SourceLocation();
1102
1103  if (Line > Content->NumLines) {
1104    unsigned Size = Content->getBuffer()->getBufferSize();
1105    if (Size > 0)
1106      --Size;
1107    return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1108  }
1109
1110  unsigned FilePos = Content->SourceLineCache[Line - 1];
1111  const char *Buf = Content->getBuffer()->getBufferStart() + FilePos;
1112  unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf;
1113  unsigned i = 0;
1114
1115  // Check that the given column is valid.
1116  while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1117    ++i;
1118  if (i < Col-1)
1119    return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1120
1121  return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
1122}
1123
1124/// \brief Determines the order of 2 source locations in the translation unit.
1125///
1126/// \returns true if LHS source location comes before RHS, false otherwise.
1127bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1128                                              SourceLocation RHS) const {
1129  assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1130  if (LHS == RHS)
1131    return false;
1132
1133  std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1134  std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1135
1136  // If the source locations are in the same file, just compare offsets.
1137  if (LOffs.first == ROffs.first)
1138    return LOffs.second < ROffs.second;
1139
1140  // If we are comparing a source location with multiple locations in the same
1141  // file, we get a big win by caching the result.
1142
1143  if (LastLFIDForBeforeTUCheck == LOffs.first &&
1144      LastRFIDForBeforeTUCheck == ROffs.first)
1145    return LastResForBeforeTUCheck;
1146
1147  LastLFIDForBeforeTUCheck = LOffs.first;
1148  LastRFIDForBeforeTUCheck = ROffs.first;
1149
1150  // "Traverse" the include/instantiation stacks of both locations and try to
1151  // find a common "ancestor".
1152  //
1153  // First we traverse the stack of the right location and check each level
1154  // against the level of the left location, while collecting all levels in a
1155  // "stack map".
1156
1157  std::map<FileID, unsigned> ROffsMap;
1158  ROffsMap[ROffs.first] = ROffs.second;
1159
1160  while (1) {
1161    SourceLocation UpperLoc;
1162    const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1163    if (Entry.isInstantiation())
1164      UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1165    else
1166      UpperLoc = Entry.getFile().getIncludeLoc();
1167
1168    if (UpperLoc.isInvalid())
1169      break; // We reached the top.
1170
1171    ROffs = getDecomposedLoc(UpperLoc);
1172
1173    if (LOffs.first == ROffs.first)
1174      return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
1175
1176    ROffsMap[ROffs.first] = ROffs.second;
1177  }
1178
1179  // We didn't find a common ancestor. Now traverse the stack of the left
1180  // location, checking against the stack map of the right location.
1181
1182  while (1) {
1183    SourceLocation UpperLoc;
1184    const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1185    if (Entry.isInstantiation())
1186      UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1187    else
1188      UpperLoc = Entry.getFile().getIncludeLoc();
1189
1190    if (UpperLoc.isInvalid())
1191      break; // We reached the top.
1192
1193    LOffs = getDecomposedLoc(UpperLoc);
1194
1195    std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1196    if (I != ROffsMap.end())
1197      return LastResForBeforeTUCheck = LOffs.second < I->second;
1198  }
1199
1200  // There is no common ancestor, most probably because one location is in the
1201  // predefines buffer.
1202  //
1203  // FIXME: We should rearrange the external interface so this simply never
1204  // happens; it can't conceptually happen. Also see PR5662.
1205
1206  // If exactly one location is a memory buffer, assume it preceeds the other.
1207  bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1208  bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1209  if (LIsMB != RIsMB)
1210    return LastResForBeforeTUCheck = LIsMB;
1211
1212  // Otherwise, just assume FileIDs were created in order.
1213  return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
1214}
1215
1216/// PrintStats - Print statistics to stderr.
1217///
1218void SourceManager::PrintStats() const {
1219  llvm::errs() << "\n*** Source Manager Stats:\n";
1220  llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1221               << " mem buffers mapped.\n";
1222  llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1223               << NextOffset << "B of Sloc address space used.\n";
1224
1225  unsigned NumLineNumsComputed = 0;
1226  unsigned NumFileBytesMapped = 0;
1227  for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1228    NumLineNumsComputed += I->second->SourceLineCache != 0;
1229    NumFileBytesMapped  += I->second->getSizeBytesMapped();
1230  }
1231
1232  llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1233               << NumLineNumsComputed << " files with line #'s computed.\n";
1234  llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1235               << NumBinaryProbes << " binary.\n";
1236}
1237
1238ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
1239