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