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