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