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