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