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