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