xref: /llvm-project/clang/lib/Basic/SourceManager.cpp (revision edf3b277a5f2ebe144827ed47463c22743cac5f9)
1 //===- SourceManager.cpp - Track and cache source files -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the SourceManager interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LLVM.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManagerInternals.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Capacity.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstddef>
39 #include <cstdint>
40 #include <memory>
41 #include <optional>
42 #include <tuple>
43 #include <utility>
44 #include <vector>
45 
46 using namespace clang;
47 using namespace SrcMgr;
48 using llvm::MemoryBuffer;
49 
50 #define DEBUG_TYPE "source-manager"
51 
52 // Reaching a limit of 2^31 results in a hard error. This metric allows to track
53 // if particular invocation of the compiler is close to it.
54 STATISTIC(MaxUsedSLocBytes, "Maximum number of bytes used by source locations "
55                             "(both loaded and local).");
56 
57 //===----------------------------------------------------------------------===//
58 // SourceManager Helper Classes
59 //===----------------------------------------------------------------------===//
60 
61 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
62 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
63 unsigned ContentCache::getSizeBytesMapped() const {
64   return Buffer ? Buffer->getBufferSize() : 0;
65 }
66 
67 /// Returns the kind of memory used to back the memory buffer for
68 /// this content cache.  This is used for performance analysis.
69 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
70   if (Buffer == nullptr) {
71     assert(0 && "Buffer should never be null");
72     return llvm::MemoryBuffer::MemoryBuffer_Malloc;
73   }
74   return Buffer->getBufferKind();
75 }
76 
77 /// getSize - Returns the size of the content encapsulated by this ContentCache.
78 ///  This can be the size of the source file or the size of an arbitrary
79 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
80 ///  file is not lazily brought in from disk to satisfy this query.
81 unsigned ContentCache::getSize() const {
82   return Buffer ? (unsigned)Buffer->getBufferSize()
83                 : (unsigned)ContentsEntry->getSize();
84 }
85 
86 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
87   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
88   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
89   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
90   const char *InvalidBOM =
91       llvm::StringSwitch<const char *>(BufStr)
92           .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
93                       "UTF-32 (BE)")
94           .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
95                       "UTF-32 (LE)")
96           .StartsWith("\xFE\xFF", "UTF-16 (BE)")
97           .StartsWith("\xFF\xFE", "UTF-16 (LE)")
98           .StartsWith("\x2B\x2F\x76", "UTF-7")
99           .StartsWith("\xF7\x64\x4C", "UTF-1")
100           .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
101           .StartsWith("\x0E\xFE\xFF", "SCSU")
102           .StartsWith("\xFB\xEE\x28", "BOCU-1")
103           .StartsWith("\x84\x31\x95\x33", "GB-18030")
104           .Default(nullptr);
105 
106   return InvalidBOM;
107 }
108 
109 std::optional<llvm::MemoryBufferRef>
110 ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
111                               SourceLocation Loc) const {
112   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
113   // computed it, just return what we have.
114   if (IsBufferInvalid)
115     return std::nullopt;
116   if (Buffer)
117     return Buffer->getMemBufferRef();
118   if (!ContentsEntry)
119     return std::nullopt;
120 
121   // Start with the assumption that the buffer is invalid to simplify early
122   // return paths.
123   IsBufferInvalid = true;
124   bool IsText = false;
125 
126 #ifdef __MVS__
127   // If the file is tagged with a text ccsid, it may require autoconversion.
128   llvm::ErrorOr<bool> IsFileText =
129       llvm::iszOSTextFile(ContentsEntry->getName().data());
130   if (IsFileText)
131     IsText = *IsFileText;
132 #endif
133 
134   auto BufferOrError = FM.getBufferForFile(
135       *ContentsEntry, IsFileVolatile, /*RequiresNullTerminator=*/true, IsText);
136 
137   // If we were unable to open the file, then we are in an inconsistent
138   // situation where the content cache referenced a file which no longer
139   // exists. Most likely, we were using a stat cache with an invalid entry but
140   // the file could also have been removed during processing. Since we can't
141   // really deal with this situation, just create an empty buffer.
142   if (!BufferOrError) {
143     Diag.Report(Loc, diag::err_cannot_open_file)
144         << ContentsEntry->getName() << BufferOrError.getError().message();
145 
146     return std::nullopt;
147   }
148 
149   Buffer = std::move(*BufferOrError);
150 
151   // Check that the file's size fits in an 'unsigned' (with room for a
152   // past-the-end value). This is deeply regrettable, but various parts of
153   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
154   // offsets, line numbers, string literal lengths, and so on, and fail
155   // miserably on large source files.
156   //
157   // Note: ContentsEntry could be a named pipe, in which case
158   // ContentsEntry::getSize() could have the wrong size. Use
159   // MemoryBuffer::getBufferSize() instead.
160   if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
161     Diag.Report(Loc, diag::err_file_too_large) << ContentsEntry->getName();
162 
163     return std::nullopt;
164   }
165 
166   // Unless this is a named pipe (in which case we can handle a mismatch),
167   // check that the file's size is the same as in the file entry (which may
168   // have come from a stat cache).
169   if (!ContentsEntry->isNamedPipe() &&
170       Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
171     Diag.Report(Loc, diag::err_file_modified) << ContentsEntry->getName();
172 
173     return std::nullopt;
174   }
175 
176   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
177   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
178   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
179   StringRef BufStr = Buffer->getBuffer();
180   const char *InvalidBOM = getInvalidBOM(BufStr);
181 
182   if (InvalidBOM) {
183     Diag.Report(Loc, diag::err_unsupported_bom)
184       << InvalidBOM << ContentsEntry->getName();
185     return std::nullopt;
186   }
187 
188   // Buffer has been validated.
189   IsBufferInvalid = false;
190   return Buffer->getMemBufferRef();
191 }
192 
193 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
194   auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
195   if (IterBool.second)
196     FilenamesByID.push_back(&*IterBool.first);
197   return IterBool.first->second;
198 }
199 
200 /// Add a line note to the line table that indicates that there is a \#line or
201 /// GNU line marker at the specified FID/Offset location which changes the
202 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
203 /// change the presumed \#include stack.  If it is 1, this is a file entry, if
204 /// it is 2 then this is a file exit. FileKind specifies whether this is a
205 /// system header or extern C system header.
206 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
207                                 int FilenameID, unsigned EntryExit,
208                                 SrcMgr::CharacteristicKind FileKind) {
209   std::vector<LineEntry> &Entries = LineEntries[FID];
210 
211   assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
212          "Adding line entries out of order!");
213 
214   unsigned IncludeOffset = 0;
215   if (EntryExit == 1) {
216     // Push #include
217     IncludeOffset = Offset-1;
218   } else {
219     const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
220     if (EntryExit == 2) {
221       // Pop #include
222       assert(PrevEntry && PrevEntry->IncludeOffset &&
223              "PPDirectives should have caught case when popping empty include "
224              "stack");
225       PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
226     }
227     if (PrevEntry) {
228       IncludeOffset = PrevEntry->IncludeOffset;
229       if (FilenameID == -1) {
230         // An unspecified FilenameID means use the previous (or containing)
231         // filename if available, or the main source file otherwise.
232         FilenameID = PrevEntry->FilenameID;
233       }
234     }
235   }
236 
237   Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
238                                    IncludeOffset));
239 }
240 
241 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
242 /// it.  If there is no line entry before Offset in FID, return null.
243 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
244                                                      unsigned Offset) {
245   const std::vector<LineEntry> &Entries = LineEntries[FID];
246   assert(!Entries.empty() && "No #line entries for this FID after all!");
247 
248   // It is very common for the query to be after the last #line, check this
249   // first.
250   if (Entries.back().FileOffset <= Offset)
251     return &Entries.back();
252 
253   // Do a binary search to find the maximal element that is still before Offset.
254   std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
255   if (I == Entries.begin())
256     return nullptr;
257   return &*--I;
258 }
259 
260 /// Add a new line entry that has already been encoded into
261 /// the internal representation of the line table.
262 void LineTableInfo::AddEntry(FileID FID,
263                              const std::vector<LineEntry> &Entries) {
264   LineEntries[FID] = Entries;
265 }
266 
267 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
268 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
269   return getLineTable().getLineTableFilenameID(Name);
270 }
271 
272 /// AddLineNote - Add a line note to the line table for the FileID and offset
273 /// specified by Loc.  If FilenameID is -1, it is considered to be
274 /// unspecified.
275 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
276                                 int FilenameID, bool IsFileEntry,
277                                 bool IsFileExit,
278                                 SrcMgr::CharacteristicKind FileKind) {
279   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
280 
281   bool Invalid = false;
282   SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
283   if (!Entry.isFile() || Invalid)
284     return;
285 
286   SrcMgr::FileInfo &FileInfo = Entry.getFile();
287 
288   // Remember that this file has #line directives now if it doesn't already.
289   FileInfo.setHasLineDirectives();
290 
291   (void) getLineTable();
292 
293   unsigned EntryExit = 0;
294   if (IsFileEntry)
295     EntryExit = 1;
296   else if (IsFileExit)
297     EntryExit = 2;
298 
299   LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
300                          EntryExit, FileKind);
301 }
302 
303 LineTableInfo &SourceManager::getLineTable() {
304   if (!LineTable)
305     LineTable.reset(new LineTableInfo());
306   return *LineTable;
307 }
308 
309 //===----------------------------------------------------------------------===//
310 // Private 'Create' methods.
311 //===----------------------------------------------------------------------===//
312 
313 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
314                              bool UserFilesAreVolatile)
315   : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
316   clearIDTables();
317   Diag.setSourceManager(this);
318 }
319 
320 SourceManager::~SourceManager() {
321   // Delete FileEntry objects corresponding to content caches.  Since the actual
322   // content cache objects are bump pointer allocated, we just have to run the
323   // dtors, but we call the deallocate method for completeness.
324   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
325     if (MemBufferInfos[i]) {
326       MemBufferInfos[i]->~ContentCache();
327       ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
328     }
329   }
330   for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
331     if (I->second) {
332       I->second->~ContentCache();
333       ContentCacheAlloc.Deallocate(I->second);
334     }
335   }
336 }
337 
338 void SourceManager::clearIDTables() {
339   MainFileID = FileID();
340   LocalSLocEntryTable.clear();
341   LoadedSLocEntryTable.clear();
342   SLocEntryLoaded.clear();
343   SLocEntryOffsetLoaded.clear();
344   LastLineNoFileIDQuery = FileID();
345   LastLineNoContentCache = nullptr;
346   LastFileIDLookup = FileID();
347 
348   IncludedLocMap.clear();
349   if (LineTable)
350     LineTable->clear();
351 
352   // Use up FileID #0 as an invalid expansion.
353   NextLocalOffset = 0;
354   CurrentLoadedOffset = MaxLoadedOffset;
355   createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
356 }
357 
358 bool SourceManager::isMainFile(const FileEntry &SourceFile) {
359   assert(MainFileID.isValid() && "expected initialized SourceManager");
360   if (auto *FE = getFileEntryForID(MainFileID))
361     return FE->getUID() == SourceFile.getUID();
362   return false;
363 }
364 
365 void SourceManager::initializeForReplay(const SourceManager &Old) {
366   assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
367 
368   auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
369     auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
370     Clone->OrigEntry = Cache->OrigEntry;
371     Clone->ContentsEntry = Cache->ContentsEntry;
372     Clone->BufferOverridden = Cache->BufferOverridden;
373     Clone->IsFileVolatile = Cache->IsFileVolatile;
374     Clone->IsTransient = Cache->IsTransient;
375     Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
376     return Clone;
377   };
378 
379   // Ensure all SLocEntries are loaded from the external source.
380   for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
381     if (!Old.SLocEntryLoaded[I])
382       Old.loadSLocEntry(I, nullptr);
383 
384   // Inherit any content cache data from the old source manager.
385   for (auto &FileInfo : Old.FileInfos) {
386     SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
387     if (Slot)
388       continue;
389     Slot = CloneContentCache(FileInfo.second);
390   }
391 }
392 
393 ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
394                                                      bool isSystemFile) {
395   // Do we already have information about this file?
396   ContentCache *&Entry = FileInfos[FileEnt];
397   if (Entry)
398     return *Entry;
399 
400   // Nope, create a new Cache entry.
401   Entry = ContentCacheAlloc.Allocate<ContentCache>();
402 
403   if (OverriddenFilesInfo) {
404     // If the file contents are overridden with contents from another file,
405     // pass that file to ContentCache.
406     auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
407     if (overI == OverriddenFilesInfo->OverriddenFiles.end())
408       new (Entry) ContentCache(FileEnt);
409     else
410       new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
411                                                               : overI->second,
412                                overI->second);
413   } else {
414     new (Entry) ContentCache(FileEnt);
415   }
416 
417   Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
418   Entry->IsTransient = FilesAreTransient;
419   Entry->BufferOverridden |= FileEnt.isNamedPipe();
420 
421   return *Entry;
422 }
423 
424 /// Create a new ContentCache for the specified memory buffer.
425 /// This does no caching.
426 ContentCache &SourceManager::createMemBufferContentCache(
427     std::unique_ptr<llvm::MemoryBuffer> Buffer) {
428   // Add a new ContentCache to the MemBufferInfos list and return it.
429   ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
430   new (Entry) ContentCache();
431   MemBufferInfos.push_back(Entry);
432   Entry->setBuffer(std::move(Buffer));
433   return *Entry;
434 }
435 
436 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
437                                                       bool *Invalid) const {
438   return const_cast<SourceManager *>(this)->loadSLocEntry(Index, Invalid);
439 }
440 
441 SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, bool *Invalid) {
442   assert(!SLocEntryLoaded[Index]);
443   if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
444     if (Invalid)
445       *Invalid = true;
446     // If the file of the SLocEntry changed we could still have loaded it.
447     if (!SLocEntryLoaded[Index]) {
448       // Try to recover; create a SLocEntry so the rest of clang can handle it.
449       if (!FakeSLocEntryForRecovery)
450         FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
451             0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
452                              SrcMgr::C_User, "")));
453       return *FakeSLocEntryForRecovery;
454     }
455   }
456 
457   return LoadedSLocEntryTable[Index];
458 }
459 
460 std::pair<int, SourceLocation::UIntTy>
461 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
462                                          SourceLocation::UIntTy TotalSize) {
463   assert(ExternalSLocEntries && "Don't have an external sloc source");
464   // Make sure we're not about to run out of source locations.
465   if (CurrentLoadedOffset < TotalSize ||
466       CurrentLoadedOffset - TotalSize < NextLocalOffset) {
467     return std::make_pair(0, 0);
468   }
469   LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
470   SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
471   SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());
472   CurrentLoadedOffset -= TotalSize;
473   updateSlocUsageStats();
474   int BaseID = -int(LoadedSLocEntryTable.size()) - 1;
475   LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));
476   return std::make_pair(BaseID, CurrentLoadedOffset);
477 }
478 
479 /// As part of recovering from missing or changed content, produce a
480 /// fake, non-empty buffer.
481 llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
482   if (!FakeBufferForRecovery)
483     FakeBufferForRecovery =
484         llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
485 
486   return *FakeBufferForRecovery;
487 }
488 
489 /// As part of recovering from missing or changed content, produce a
490 /// fake content cache.
491 SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
492   if (!FakeContentCacheForRecovery) {
493     FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
494     FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
495   }
496   return *FakeContentCacheForRecovery;
497 }
498 
499 /// Returns the previous in-order FileID or an invalid FileID if there
500 /// is no previous one.
501 FileID SourceManager::getPreviousFileID(FileID FID) const {
502   if (FID.isInvalid())
503     return FileID();
504 
505   int ID = FID.ID;
506   if (ID == -1)
507     return FileID();
508 
509   if (ID > 0) {
510     if (ID-1 == 0)
511       return FileID();
512   } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
513     return FileID();
514   }
515 
516   return FileID::get(ID-1);
517 }
518 
519 /// Returns the next in-order FileID or an invalid FileID if there is
520 /// no next one.
521 FileID SourceManager::getNextFileID(FileID FID) const {
522   if (FID.isInvalid())
523     return FileID();
524 
525   int ID = FID.ID;
526   if (ID > 0) {
527     if (unsigned(ID+1) >= local_sloc_entry_size())
528       return FileID();
529   } else if (ID+1 >= -1) {
530     return FileID();
531   }
532 
533   return FileID::get(ID+1);
534 }
535 
536 //===----------------------------------------------------------------------===//
537 // Methods to create new FileID's and macro expansions.
538 //===----------------------------------------------------------------------===//
539 
540 /// Create a new FileID that represents the specified file
541 /// being \#included from the specified IncludePosition.
542 FileID SourceManager::createFileID(FileEntryRef SourceFile,
543                                    SourceLocation IncludePos,
544                                    SrcMgr::CharacteristicKind FileCharacter,
545                                    int LoadedID,
546                                    SourceLocation::UIntTy LoadedOffset) {
547   SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
548                                                      isSystem(FileCharacter));
549 
550   // If this is a named pipe, immediately load the buffer to ensure subsequent
551   // calls to ContentCache::getSize() are accurate.
552   if (IR.ContentsEntry->isNamedPipe())
553     (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
554 
555   return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
556                           LoadedID, LoadedOffset);
557 }
558 
559 /// Create a new FileID that represents the specified memory buffer.
560 ///
561 /// This does no caching of the buffer and takes ownership of the
562 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
563 FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
564                                    SrcMgr::CharacteristicKind FileCharacter,
565                                    int LoadedID,
566                                    SourceLocation::UIntTy LoadedOffset,
567                                    SourceLocation IncludeLoc) {
568   StringRef Name = Buffer->getBufferIdentifier();
569   return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
570                           IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
571 }
572 
573 /// Create a new FileID that represents the specified memory buffer.
574 ///
575 /// This does not take ownership of the MemoryBuffer. The memory buffer must
576 /// outlive the SourceManager.
577 FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
578                                    SrcMgr::CharacteristicKind FileCharacter,
579                                    int LoadedID,
580                                    SourceLocation::UIntTy LoadedOffset,
581                                    SourceLocation IncludeLoc) {
582   return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
583                       LoadedID, LoadedOffset, IncludeLoc);
584 }
585 
586 /// Get the FileID for \p SourceFile if it exists. Otherwise, create a
587 /// new FileID for the \p SourceFile.
588 FileID
589 SourceManager::getOrCreateFileID(FileEntryRef SourceFile,
590                                  SrcMgr::CharacteristicKind FileCharacter) {
591   FileID ID = translateFile(SourceFile);
592   return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
593 					  FileCharacter);
594 }
595 
596 /// createFileID - Create a new FileID for the specified ContentCache and
597 /// include position.  This works regardless of whether the ContentCache
598 /// corresponds to a file or some other input source.
599 FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
600                                        SourceLocation IncludePos,
601                                        SrcMgr::CharacteristicKind FileCharacter,
602                                        int LoadedID,
603                                        SourceLocation::UIntTy LoadedOffset) {
604   if (LoadedID < 0) {
605     assert(LoadedID != -1 && "Loading sentinel FileID");
606     unsigned Index = unsigned(-LoadedID) - 2;
607     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
608     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
609     LoadedSLocEntryTable[Index] = SLocEntry::get(
610         LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
611     SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
612     return FileID::get(LoadedID);
613   }
614   unsigned FileSize = File.getSize();
615   if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
616         NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
617     Diag.Report(IncludePos, diag::err_sloc_space_too_large);
618     noteSLocAddressSpaceUsage(Diag);
619     return FileID();
620   }
621   LocalSLocEntryTable.push_back(
622       SLocEntry::get(NextLocalOffset,
623                      FileInfo::get(IncludePos, File, FileCharacter, Filename)));
624   // We do a +1 here because we want a SourceLocation that means "the end of the
625   // file", e.g. for the "no newline at the end of the file" diagnostic.
626   NextLocalOffset += FileSize + 1;
627   updateSlocUsageStats();
628 
629   // Set LastFileIDLookup to the newly created file.  The next getFileID call is
630   // almost guaranteed to be from that file.
631   FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
632   return LastFileIDLookup = FID;
633 }
634 
635 SourceLocation SourceManager::createMacroArgExpansionLoc(
636     SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
637   ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
638                                                         ExpansionLoc);
639   return createExpansionLocImpl(Info, Length);
640 }
641 
642 SourceLocation SourceManager::createExpansionLoc(
643     SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
644     SourceLocation ExpansionLocEnd, unsigned Length,
645     bool ExpansionIsTokenRange, int LoadedID,
646     SourceLocation::UIntTy LoadedOffset) {
647   ExpansionInfo Info = ExpansionInfo::create(
648       SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
649   return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
650 }
651 
652 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
653                                                   SourceLocation TokenStart,
654                                                   SourceLocation TokenEnd) {
655   assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
656          "token spans multiple files");
657   return createExpansionLocImpl(
658       ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
659       TokenEnd.getOffset() - TokenStart.getOffset());
660 }
661 
662 SourceLocation
663 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
664                                       unsigned Length, int LoadedID,
665                                       SourceLocation::UIntTy LoadedOffset) {
666   if (LoadedID < 0) {
667     assert(LoadedID != -1 && "Loading sentinel FileID");
668     unsigned Index = unsigned(-LoadedID) - 2;
669     assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
670     assert(!SLocEntryLoaded[Index] && "FileID already loaded");
671     LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
672     SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
673     return SourceLocation::getMacroLoc(LoadedOffset);
674   }
675   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
676   if (NextLocalOffset + Length + 1 <= NextLocalOffset ||
677       NextLocalOffset + Length + 1 > CurrentLoadedOffset) {
678     Diag.Report(SourceLocation(), diag::err_sloc_space_too_large);
679     // FIXME: call `noteSLocAddressSpaceUsage` to report details to users and
680     // use a source location from `Info` to point at an error.
681     // Currently, both cause Clang to run indefinitely, this needs to be fixed.
682     // FIXME: return an error instead of crashing. Returning invalid source
683     // locations causes compiler to run indefinitely.
684     llvm::report_fatal_error("ran out of source locations");
685   }
686   // See createFileID for that +1.
687   NextLocalOffset += Length + 1;
688   updateSlocUsageStats();
689   return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
690 }
691 
692 std::optional<llvm::MemoryBufferRef>
693 SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) {
694   SrcMgr::ContentCache &IR = getOrCreateContentCache(File);
695   return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
696 }
697 
698 void SourceManager::overrideFileContents(
699     FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
700   SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);
701 
702   IR.setBuffer(std::move(Buffer));
703   IR.BufferOverridden = true;
704 
705   getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
706 }
707 
708 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
709                                          FileEntryRef NewFile) {
710   assert(SourceFile->getSize() == NewFile.getSize() &&
711          "Different sizes, use the FileManager to create a virtual file with "
712          "the correct size");
713   assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&
714          "This function should be called at the initialization stage, before "
715          "any parsing occurs.");
716   // FileEntryRef is not default-constructible.
717   auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
718       std::make_pair(SourceFile, NewFile));
719   if (!Pair.second)
720     Pair.first->second = NewFile;
721 }
722 
723 OptionalFileEntryRef
724 SourceManager::bypassFileContentsOverride(FileEntryRef File) {
725   assert(isFileOverridden(&File.getFileEntry()));
726   OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
727 
728   // If the file can't be found in the FS, give up.
729   if (!BypassFile)
730     return std::nullopt;
731 
732   (void)getOrCreateContentCache(*BypassFile);
733   return BypassFile;
734 }
735 
736 void SourceManager::setFileIsTransient(FileEntryRef File) {
737   getOrCreateContentCache(File).IsTransient = true;
738 }
739 
740 std::optional<StringRef>
741 SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
742   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
743     if (Entry->getFile().getContentCache().OrigEntry)
744       return Entry->getFile().getName();
745   return std::nullopt;
746 }
747 
748 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
749   auto B = getBufferDataOrNone(FID);
750   if (Invalid)
751     *Invalid = !B;
752   return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
753 }
754 
755 std::optional<StringRef>
756 SourceManager::getBufferDataIfLoaded(FileID FID) const {
757   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
758     return Entry->getFile().getContentCache().getBufferDataIfLoaded();
759   return std::nullopt;
760 }
761 
762 std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
763   if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
764     if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
765             Diag, getFileManager(), SourceLocation()))
766       return B->getBuffer();
767   return std::nullopt;
768 }
769 
770 //===----------------------------------------------------------------------===//
771 // SourceLocation manipulation methods.
772 //===----------------------------------------------------------------------===//
773 
774 /// Return the FileID for a SourceLocation.
775 ///
776 /// This is the cache-miss path of getFileID. Not as hot as that function, but
777 /// still very important. It is responsible for finding the entry in the
778 /// SLocEntry tables that contains the specified location.
779 FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
780   if (!SLocOffset)
781     return FileID::get(0);
782 
783   // Now it is time to search for the correct file. See where the SLocOffset
784   // sits in the global view and consult local or loaded buffers for it.
785   if (SLocOffset < NextLocalOffset)
786     return getFileIDLocal(SLocOffset);
787   return getFileIDLoaded(SLocOffset);
788 }
789 
790 /// Return the FileID for a SourceLocation with a low offset.
791 ///
792 /// This function knows that the SourceLocation is in a local buffer, not a
793 /// loaded one.
794 FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
795   assert(SLocOffset < NextLocalOffset && "Bad function choice");
796 
797   // After the first and second level caches, I see two common sorts of
798   // behavior: 1) a lot of searched FileID's are "near" the cached file
799   // location or are "near" the cached expansion location. 2) others are just
800   // completely random and may be a very long way away.
801   //
802   // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
803   // then we fall back to a less cache efficient, but more scalable, binary
804   // search to find the location.
805 
806   // See if this is near the file point - worst case we start scanning from the
807   // most newly created FileID.
808 
809   // LessIndex - This is the lower bound of the range that we're searching.
810   // We know that the offset corresponding to the FileID is less than
811   // SLocOffset.
812   unsigned LessIndex = 0;
813   // upper bound of the search range.
814   unsigned GreaterIndex = LocalSLocEntryTable.size();
815   if (LastFileIDLookup.ID >= 0) {
816     // Use the LastFileIDLookup to prune the search space.
817     if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
818       LessIndex = LastFileIDLookup.ID;
819     else
820       GreaterIndex = LastFileIDLookup.ID;
821   }
822 
823   // Find the FileID that contains this.
824   unsigned NumProbes = 0;
825   while (true) {
826     --GreaterIndex;
827     assert(GreaterIndex < LocalSLocEntryTable.size());
828     if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
829       FileID Res = FileID::get(int(GreaterIndex));
830       // Remember it.  We have good locality across FileID lookups.
831       LastFileIDLookup = Res;
832       NumLinearScans += NumProbes+1;
833       return Res;
834     }
835     if (++NumProbes == 8)
836       break;
837   }
838 
839   NumProbes = 0;
840   while (true) {
841     unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
842     SourceLocation::UIntTy MidOffset =
843         getLocalSLocEntry(MiddleIndex).getOffset();
844 
845     ++NumProbes;
846 
847     // If the offset of the midpoint is too large, chop the high side of the
848     // range to the midpoint.
849     if (MidOffset > SLocOffset) {
850       GreaterIndex = MiddleIndex;
851       continue;
852     }
853 
854     // If the middle index contains the value, succeed and return.
855     if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
856         SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
857       FileID Res = FileID::get(MiddleIndex);
858 
859       // Remember it.  We have good locality across FileID lookups.
860       LastFileIDLookup = Res;
861       NumBinaryProbes += NumProbes;
862       return Res;
863     }
864 
865     // Otherwise, move the low-side up to the middle index.
866     LessIndex = MiddleIndex;
867   }
868 }
869 
870 /// Return the FileID for a SourceLocation with a high offset.
871 ///
872 /// This function knows that the SourceLocation is in a loaded buffer, not a
873 /// local one.
874 FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
875   if (SLocOffset < CurrentLoadedOffset) {
876     assert(0 && "Invalid SLocOffset or bad function choice");
877     return FileID();
878   }
879 
880   return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));
881 }
882 
883 SourceLocation SourceManager::
884 getExpansionLocSlowCase(SourceLocation Loc) const {
885   do {
886     // Note: If Loc indicates an offset into a token that came from a macro
887     // expansion (e.g. the 5th character of the token) we do not want to add
888     // this offset when going to the expansion location.  The expansion
889     // location is the macro invocation, which the offset has nothing to do
890     // with.  This is unlike when we get the spelling loc, because the offset
891     // directly correspond to the token whose spelling we're inspecting.
892     Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
893   } while (!Loc.isFileID());
894 
895   return Loc;
896 }
897 
898 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
899   do {
900     std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
901     Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
902     Loc = Loc.getLocWithOffset(LocInfo.second);
903   } while (!Loc.isFileID());
904   return Loc;
905 }
906 
907 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
908   do {
909     if (isMacroArgExpansion(Loc))
910       Loc = getImmediateSpellingLoc(Loc);
911     else
912       Loc = getImmediateExpansionRange(Loc).getBegin();
913   } while (!Loc.isFileID());
914   return Loc;
915 }
916 
917 
918 std::pair<FileID, unsigned>
919 SourceManager::getDecomposedExpansionLocSlowCase(
920                                              const SrcMgr::SLocEntry *E) const {
921   // If this is an expansion record, walk through all the expansion points.
922   FileID FID;
923   SourceLocation Loc;
924   unsigned Offset;
925   do {
926     Loc = E->getExpansion().getExpansionLocStart();
927 
928     FID = getFileID(Loc);
929     E = &getSLocEntry(FID);
930     Offset = Loc.getOffset()-E->getOffset();
931   } while (!Loc.isFileID());
932 
933   return std::make_pair(FID, Offset);
934 }
935 
936 std::pair<FileID, unsigned>
937 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
938                                                 unsigned Offset) const {
939   // If this is an expansion record, walk through all the expansion points.
940   FileID FID;
941   SourceLocation Loc;
942   do {
943     Loc = E->getExpansion().getSpellingLoc();
944     Loc = Loc.getLocWithOffset(Offset);
945 
946     FID = getFileID(Loc);
947     E = &getSLocEntry(FID);
948     Offset = Loc.getOffset()-E->getOffset();
949   } while (!Loc.isFileID());
950 
951   return std::make_pair(FID, Offset);
952 }
953 
954 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
955 /// spelling location referenced by the ID.  This is the first level down
956 /// towards the place where the characters that make up the lexed token can be
957 /// found.  This should not generally be used by clients.
958 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
959   if (Loc.isFileID()) return Loc;
960   std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
961   Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
962   return Loc.getLocWithOffset(LocInfo.second);
963 }
964 
965 /// Return the filename of the file containing a SourceLocation.
966 StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
967   if (OptionalFileEntryRef F = getFileEntryRefForID(getFileID(SpellingLoc)))
968     return F->getName();
969   return StringRef();
970 }
971 
972 /// getImmediateExpansionRange - Loc is required to be an expansion location.
973 /// Return the start/end of the expansion information.
974 CharSourceRange
975 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
976   assert(Loc.isMacroID() && "Not a macro expansion loc!");
977   const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
978   return Expansion.getExpansionLocRange();
979 }
980 
981 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
982   while (isMacroArgExpansion(Loc))
983     Loc = getImmediateSpellingLoc(Loc);
984   return Loc;
985 }
986 
987 /// getExpansionRange - Given a SourceLocation object, return the range of
988 /// tokens covered by the expansion in the ultimate file.
989 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
990   if (Loc.isFileID())
991     return CharSourceRange(SourceRange(Loc, Loc), true);
992 
993   CharSourceRange Res = getImmediateExpansionRange(Loc);
994 
995   // Fully resolve the start and end locations to their ultimate expansion
996   // points.
997   while (!Res.getBegin().isFileID())
998     Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
999   while (!Res.getEnd().isFileID()) {
1000     CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1001     Res.setEnd(EndRange.getEnd());
1002     Res.setTokenRange(EndRange.isTokenRange());
1003   }
1004   return Res;
1005 }
1006 
1007 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1008                                         SourceLocation *StartLoc) const {
1009   if (!Loc.isMacroID()) return false;
1010 
1011   FileID FID = getFileID(Loc);
1012   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1013   if (!Expansion.isMacroArgExpansion()) return false;
1014 
1015   if (StartLoc)
1016     *StartLoc = Expansion.getExpansionLocStart();
1017   return true;
1018 }
1019 
1020 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1021   if (!Loc.isMacroID()) return false;
1022 
1023   FileID FID = getFileID(Loc);
1024   const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1025   return Expansion.isMacroBodyExpansion();
1026 }
1027 
1028 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1029                                              SourceLocation *MacroBegin) const {
1030   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1031 
1032   std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1033   if (DecompLoc.second > 0)
1034     return false; // Does not point at the start of expansion range.
1035 
1036   bool Invalid = false;
1037   const SrcMgr::ExpansionInfo &ExpInfo =
1038       getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1039   if (Invalid)
1040     return false;
1041   SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1042 
1043   if (ExpInfo.isMacroArgExpansion()) {
1044     // For macro argument expansions, check if the previous FileID is part of
1045     // the same argument expansion, in which case this Loc is not at the
1046     // beginning of the expansion.
1047     FileID PrevFID = getPreviousFileID(DecompLoc.first);
1048     if (!PrevFID.isInvalid()) {
1049       const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1050       if (Invalid)
1051         return false;
1052       if (PrevEntry.isExpansion() &&
1053           PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1054         return false;
1055     }
1056   }
1057 
1058   if (MacroBegin)
1059     *MacroBegin = ExpLoc;
1060   return true;
1061 }
1062 
1063 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1064                                                SourceLocation *MacroEnd) const {
1065   assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1066 
1067   FileID FID = getFileID(Loc);
1068   SourceLocation NextLoc = Loc.getLocWithOffset(1);
1069   if (isInFileID(NextLoc, FID))
1070     return false; // Does not point at the end of expansion range.
1071 
1072   bool Invalid = false;
1073   const SrcMgr::ExpansionInfo &ExpInfo =
1074       getSLocEntry(FID, &Invalid).getExpansion();
1075   if (Invalid)
1076     return false;
1077 
1078   if (ExpInfo.isMacroArgExpansion()) {
1079     // For macro argument expansions, check if the next FileID is part of the
1080     // same argument expansion, in which case this Loc is not at the end of the
1081     // expansion.
1082     FileID NextFID = getNextFileID(FID);
1083     if (!NextFID.isInvalid()) {
1084       const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1085       if (Invalid)
1086         return false;
1087       if (NextEntry.isExpansion() &&
1088           NextEntry.getExpansion().getExpansionLocStart() ==
1089               ExpInfo.getExpansionLocStart())
1090         return false;
1091     }
1092   }
1093 
1094   if (MacroEnd)
1095     *MacroEnd = ExpInfo.getExpansionLocEnd();
1096   return true;
1097 }
1098 
1099 //===----------------------------------------------------------------------===//
1100 // Queries about the code at a SourceLocation.
1101 //===----------------------------------------------------------------------===//
1102 
1103 /// getCharacterData - Return a pointer to the start of the specified location
1104 /// in the appropriate MemoryBuffer.
1105 const char *SourceManager::getCharacterData(SourceLocation SL,
1106                                             bool *Invalid) const {
1107   // Note that this is a hot function in the getSpelling() path, which is
1108   // heavily used by -E mode.
1109   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1110 
1111   // Note that calling 'getBuffer()' may lazily page in a source file.
1112   bool CharDataInvalid = false;
1113   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1114   if (CharDataInvalid || !Entry.isFile()) {
1115     if (Invalid)
1116       *Invalid = true;
1117 
1118     return "<<<<INVALID BUFFER>>>>";
1119   }
1120   std::optional<llvm::MemoryBufferRef> Buffer =
1121       Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(),
1122                                                         SourceLocation());
1123   if (Invalid)
1124     *Invalid = !Buffer;
1125   return Buffer ? Buffer->getBufferStart() + LocInfo.second
1126                 : "<<<<INVALID BUFFER>>>>";
1127 }
1128 
1129 /// getColumnNumber - Return the column # for the specified file position.
1130 /// this is significantly cheaper to compute than the line number.
1131 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1132                                         bool *Invalid) const {
1133   std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID);
1134   if (Invalid)
1135     *Invalid = !MemBuf;
1136 
1137   if (!MemBuf)
1138     return 1;
1139 
1140   // It is okay to request a position just past the end of the buffer.
1141   if (FilePos > MemBuf->getBufferSize()) {
1142     if (Invalid)
1143       *Invalid = true;
1144     return 1;
1145   }
1146 
1147   const char *Buf = MemBuf->getBufferStart();
1148   // See if we just calculated the line number for this FilePos and can use
1149   // that to lookup the start of the line instead of searching for it.
1150   if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1151       LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1152     const unsigned *SourceLineCache =
1153         LastLineNoContentCache->SourceLineCache.begin();
1154     unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1155     unsigned LineEnd = SourceLineCache[LastLineNoResult];
1156     if (FilePos >= LineStart && FilePos < LineEnd) {
1157       // LineEnd is the LineStart of the next line.
1158       // A line ends with separator LF or CR+LF on Windows.
1159       // FilePos might point to the last separator,
1160       // but we need a column number at most 1 + the last column.
1161       if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1162         if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1163           --FilePos;
1164       }
1165       return FilePos - LineStart + 1;
1166     }
1167   }
1168 
1169   unsigned LineStart = FilePos;
1170   while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1171     --LineStart;
1172   return FilePos-LineStart+1;
1173 }
1174 
1175 // isInvalid - Return the result of calling loc.isInvalid(), and
1176 // if Invalid is not null, set its value to same.
1177 template<typename LocType>
1178 static bool isInvalid(LocType Loc, bool *Invalid) {
1179   bool MyInvalid = Loc.isInvalid();
1180   if (Invalid)
1181     *Invalid = MyInvalid;
1182   return MyInvalid;
1183 }
1184 
1185 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1186                                                 bool *Invalid) const {
1187   if (isInvalid(Loc, Invalid)) return 0;
1188   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1189   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1190 }
1191 
1192 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1193                                                  bool *Invalid) const {
1194   if (isInvalid(Loc, Invalid)) return 0;
1195   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1196   return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1197 }
1198 
1199 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1200                                                 bool *Invalid) const {
1201   PresumedLoc PLoc = getPresumedLoc(Loc);
1202   if (isInvalid(PLoc, Invalid)) return 0;
1203   return PLoc.getColumn();
1204 }
1205 
1206 // Check if mutli-byte word x has bytes between m and n, included. This may also
1207 // catch bytes equal to n + 1.
1208 // The returned value holds a 0x80 at each byte position that holds a match.
1209 // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1210 template <class T>
1211 static constexpr inline T likelyhasbetween(T x, unsigned char m,
1212                                            unsigned char n) {
1213   return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1214           ((x & ~static_cast<T>(0) / 255 * 127) +
1215            (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1216          ~static_cast<T>(0) / 255 * 128;
1217 }
1218 
1219 LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1220                                          llvm::BumpPtrAllocator &Alloc) {
1221 
1222   // Find the file offsets of all of the *physical* source lines.  This does
1223   // not look at trigraphs, escaped newlines, or anything else tricky.
1224   SmallVector<unsigned, 256> LineOffsets;
1225 
1226   // Line #1 starts at char 0.
1227   LineOffsets.push_back(0);
1228 
1229   const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart();
1230   const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1231   const unsigned char *Buf = Start;
1232 
1233   uint64_t Word;
1234 
1235   // scan sizeof(Word) bytes at a time for new lines.
1236   // This is much faster than scanning each byte independently.
1237   if ((unsigned long)(End - Start) > sizeof(Word)) {
1238     do {
1239       Word = llvm::support::endian::read64(Buf, llvm::endianness::little);
1240       // no new line => jump over sizeof(Word) bytes.
1241       auto Mask = likelyhasbetween(Word, '\n', '\r');
1242       if (!Mask) {
1243         Buf += sizeof(Word);
1244         continue;
1245       }
1246 
1247       // At that point, Mask contains 0x80 set at each byte that holds a value
1248       // in [\n, \r + 1 [
1249 
1250       // Scan for the next newline - it's very likely there's one.
1251       unsigned N = llvm::countr_zero(Mask) - 7; // -7 because 0x80 is the marker
1252       Word >>= N;
1253       Buf += N / 8 + 1;
1254       unsigned char Byte = Word;
1255       switch (Byte) {
1256       case '\r':
1257         // If this is \r\n, skip both characters.
1258         if (*Buf == '\n') {
1259           ++Buf;
1260         }
1261         [[fallthrough]];
1262       case '\n':
1263         LineOffsets.push_back(Buf - Start);
1264       };
1265     } while (Buf < End - sizeof(Word) - 1);
1266   }
1267 
1268   // Handle tail using a regular check.
1269   while (Buf < End) {
1270     if (*Buf == '\n') {
1271       LineOffsets.push_back(Buf - Start + 1);
1272     } else if (*Buf == '\r') {
1273       // If this is \r\n, skip both characters.
1274       if (Buf + 1 < End && Buf[1] == '\n') {
1275         ++Buf;
1276       }
1277       LineOffsets.push_back(Buf - Start + 1);
1278     }
1279     ++Buf;
1280   }
1281 
1282   return LineOffsetMapping(LineOffsets, Alloc);
1283 }
1284 
1285 LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1286                                      llvm::BumpPtrAllocator &Alloc)
1287     : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1288   Storage[0] = LineOffsets.size();
1289   std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1290 }
1291 
1292 /// getLineNumber - Given a SourceLocation, return the spelling line number
1293 /// for the position indicated.  This requires building and caching a table of
1294 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1295 /// about to emit a diagnostic.
1296 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1297                                       bool *Invalid) const {
1298   if (FID.isInvalid()) {
1299     if (Invalid)
1300       *Invalid = true;
1301     return 1;
1302   }
1303 
1304   const ContentCache *Content;
1305   if (LastLineNoFileIDQuery == FID)
1306     Content = LastLineNoContentCache;
1307   else {
1308     bool MyInvalid = false;
1309     const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1310     if (MyInvalid || !Entry.isFile()) {
1311       if (Invalid)
1312         *Invalid = true;
1313       return 1;
1314     }
1315 
1316     Content = &Entry.getFile().getContentCache();
1317   }
1318 
1319   // If this is the first use of line information for this buffer, compute the
1320   // SourceLineCache for it on demand.
1321   if (!Content->SourceLineCache) {
1322     std::optional<llvm::MemoryBufferRef> Buffer =
1323         Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
1324     if (Invalid)
1325       *Invalid = !Buffer;
1326     if (!Buffer)
1327       return 1;
1328 
1329     Content->SourceLineCache =
1330         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1331   } else if (Invalid)
1332     *Invalid = false;
1333 
1334   // Okay, we know we have a line number table.  Do a binary search to find the
1335   // line number that this character position lands on.
1336   const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1337   const unsigned *SourceLineCacheStart = SourceLineCache;
1338   const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1339 
1340   unsigned QueriedFilePos = FilePos+1;
1341 
1342   // FIXME: I would like to be convinced that this code is worth being as
1343   // complicated as it is, binary search isn't that slow.
1344   //
1345   // If it is worth being optimized, then in my opinion it could be more
1346   // performant, simpler, and more obviously correct by just "galloping" outward
1347   // from the queried file position. In fact, this could be incorporated into a
1348   // generic algorithm such as lower_bound_with_hint.
1349   //
1350   // If someone gives me a test case where this matters, and I will do it! - DWD
1351 
1352   // If the previous query was to the same file, we know both the file pos from
1353   // that query and the line number returned.  This allows us to narrow the
1354   // search space from the entire file to something near the match.
1355   if (LastLineNoFileIDQuery == FID) {
1356     if (QueriedFilePos >= LastLineNoFilePos) {
1357       // FIXME: Potential overflow?
1358       SourceLineCache = SourceLineCache+LastLineNoResult-1;
1359 
1360       // The query is likely to be nearby the previous one.  Here we check to
1361       // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1362       // where big comment blocks and vertical whitespace eat up lines but
1363       // contribute no tokens.
1364       if (SourceLineCache+5 < SourceLineCacheEnd) {
1365         if (SourceLineCache[5] > QueriedFilePos)
1366           SourceLineCacheEnd = SourceLineCache+5;
1367         else if (SourceLineCache+10 < SourceLineCacheEnd) {
1368           if (SourceLineCache[10] > QueriedFilePos)
1369             SourceLineCacheEnd = SourceLineCache+10;
1370           else if (SourceLineCache+20 < SourceLineCacheEnd) {
1371             if (SourceLineCache[20] > QueriedFilePos)
1372               SourceLineCacheEnd = SourceLineCache+20;
1373           }
1374         }
1375       }
1376     } else {
1377       if (LastLineNoResult < Content->SourceLineCache.size())
1378         SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1379     }
1380   }
1381 
1382   const unsigned *Pos =
1383       std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1384   unsigned LineNo = Pos-SourceLineCacheStart;
1385 
1386   LastLineNoFileIDQuery = FID;
1387   LastLineNoContentCache = Content;
1388   LastLineNoFilePos = QueriedFilePos;
1389   LastLineNoResult = LineNo;
1390   return LineNo;
1391 }
1392 
1393 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1394                                               bool *Invalid) const {
1395   if (isInvalid(Loc, Invalid)) return 0;
1396   std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1397   return getLineNumber(LocInfo.first, LocInfo.second);
1398 }
1399 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1400                                                bool *Invalid) const {
1401   if (isInvalid(Loc, Invalid)) return 0;
1402   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1403   return getLineNumber(LocInfo.first, LocInfo.second);
1404 }
1405 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1406                                               bool *Invalid) const {
1407   PresumedLoc PLoc = getPresumedLoc(Loc);
1408   if (isInvalid(PLoc, Invalid)) return 0;
1409   return PLoc.getLine();
1410 }
1411 
1412 /// getFileCharacteristic - return the file characteristic of the specified
1413 /// source location, indicating whether this is a normal file, a system
1414 /// header, or an "implicit extern C" system header.
1415 ///
1416 /// This state can be modified with flags on GNU linemarker directives like:
1417 ///   # 4 "foo.h" 3
1418 /// which changes all source locations in the current file after that to be
1419 /// considered to be from a system header.
1420 SrcMgr::CharacteristicKind
1421 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1422   assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1423   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1424   const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1425   if (!SEntry)
1426     return C_User;
1427 
1428   const SrcMgr::FileInfo &FI = SEntry->getFile();
1429 
1430   // If there are no #line directives in this file, just return the whole-file
1431   // state.
1432   if (!FI.hasLineDirectives())
1433     return FI.getFileCharacteristic();
1434 
1435   assert(LineTable && "Can't have linetable entries without a LineTable!");
1436   // See if there is a #line directive before the location.
1437   const LineEntry *Entry =
1438     LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1439 
1440   // If this is before the first line marker, use the file characteristic.
1441   if (!Entry)
1442     return FI.getFileCharacteristic();
1443 
1444   return Entry->FileKind;
1445 }
1446 
1447 /// Return the filename or buffer identifier of the buffer the location is in.
1448 /// Note that this name does not respect \#line directives.  Use getPresumedLoc
1449 /// for normal clients.
1450 StringRef SourceManager::getBufferName(SourceLocation Loc,
1451                                        bool *Invalid) const {
1452   if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1453 
1454   auto B = getBufferOrNone(getFileID(Loc));
1455   if (Invalid)
1456     *Invalid = !B;
1457   return B ? B->getBufferIdentifier() : "<invalid buffer>";
1458 }
1459 
1460 /// getPresumedLoc - This method returns the "presumed" location of a
1461 /// SourceLocation specifies.  A "presumed location" can be modified by \#line
1462 /// or GNU line marker directives.  This provides a view on the data that a
1463 /// user should see in diagnostics, for example.
1464 ///
1465 /// Note that a presumed location is always given as the expansion point of an
1466 /// expansion location, not at the spelling location.
1467 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1468                                           bool UseLineDirectives) const {
1469   if (Loc.isInvalid()) return PresumedLoc();
1470 
1471   // Presumed locations are always for expansion points.
1472   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1473 
1474   bool Invalid = false;
1475   const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1476   if (Invalid || !Entry.isFile())
1477     return PresumedLoc();
1478 
1479   const SrcMgr::FileInfo &FI = Entry.getFile();
1480   const SrcMgr::ContentCache *C = &FI.getContentCache();
1481 
1482   // To get the source name, first consult the FileEntry (if one exists)
1483   // before the MemBuffer as this will avoid unnecessarily paging in the
1484   // MemBuffer.
1485   FileID FID = LocInfo.first;
1486   StringRef Filename;
1487   if (C->OrigEntry)
1488     Filename = C->OrigEntry->getName();
1489   else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1490     Filename = Buffer->getBufferIdentifier();
1491 
1492   unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1493   if (Invalid)
1494     return PresumedLoc();
1495   unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1496   if (Invalid)
1497     return PresumedLoc();
1498 
1499   SourceLocation IncludeLoc = FI.getIncludeLoc();
1500 
1501   // If we have #line directives in this file, update and overwrite the physical
1502   // location info if appropriate.
1503   if (UseLineDirectives && FI.hasLineDirectives()) {
1504     assert(LineTable && "Can't have linetable entries without a LineTable!");
1505     // See if there is a #line directive before this.  If so, get it.
1506     if (const LineEntry *Entry =
1507           LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1508       // If the LineEntry indicates a filename, use it.
1509       if (Entry->FilenameID != -1) {
1510         Filename = LineTable->getFilename(Entry->FilenameID);
1511         // The contents of files referenced by #line are not in the
1512         // SourceManager
1513         FID = FileID::get(0);
1514       }
1515 
1516       // Use the line number specified by the LineEntry.  This line number may
1517       // be multiple lines down from the line entry.  Add the difference in
1518       // physical line numbers from the query point and the line marker to the
1519       // total.
1520       unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1521       LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1522 
1523       // Note that column numbers are not molested by line markers.
1524 
1525       // Handle virtual #include manipulation.
1526       if (Entry->IncludeOffset) {
1527         IncludeLoc = getLocForStartOfFile(LocInfo.first);
1528         IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1529       }
1530     }
1531   }
1532 
1533   return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1534 }
1535 
1536 /// Returns whether the PresumedLoc for a given SourceLocation is
1537 /// in the main file.
1538 ///
1539 /// This computes the "presumed" location for a SourceLocation, then checks
1540 /// whether it came from a file other than the main file. This is different
1541 /// from isWrittenInMainFile() because it takes line marker directives into
1542 /// account.
1543 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1544   if (Loc.isInvalid()) return false;
1545 
1546   // Presumed locations are always for expansion points.
1547   std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1548 
1549   const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1550   if (!Entry)
1551     return false;
1552 
1553   const SrcMgr::FileInfo &FI = Entry->getFile();
1554 
1555   // Check if there is a line directive for this location.
1556   if (FI.hasLineDirectives())
1557     if (const LineEntry *Entry =
1558             LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1559       if (Entry->IncludeOffset)
1560         return false;
1561 
1562   return FI.getIncludeLoc().isInvalid();
1563 }
1564 
1565 /// The size of the SLocEntry that \p FID represents.
1566 unsigned SourceManager::getFileIDSize(FileID FID) const {
1567   bool Invalid = false;
1568   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1569   if (Invalid)
1570     return 0;
1571 
1572   int ID = FID.ID;
1573   SourceLocation::UIntTy NextOffset;
1574   if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1575     NextOffset = getNextLocalOffset();
1576   else if (ID+1 == -1)
1577     NextOffset = MaxLoadedOffset;
1578   else
1579     NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1580 
1581   return NextOffset - Entry.getOffset() - 1;
1582 }
1583 
1584 //===----------------------------------------------------------------------===//
1585 // Other miscellaneous methods.
1586 //===----------------------------------------------------------------------===//
1587 
1588 /// Get the source location for the given file:line:col triplet.
1589 ///
1590 /// If the source file is included multiple times, the source location will
1591 /// be based upon an arbitrary inclusion.
1592 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1593                                                   unsigned Line,
1594                                                   unsigned Col) const {
1595   assert(SourceFile && "Null source file!");
1596   assert(Line && Col && "Line and column should start from 1!");
1597 
1598   FileID FirstFID = translateFile(SourceFile);
1599   return translateLineCol(FirstFID, Line, Col);
1600 }
1601 
1602 /// Get the FileID for the given file.
1603 ///
1604 /// If the source file is included multiple times, the FileID will be the
1605 /// first inclusion.
1606 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1607   assert(SourceFile && "Null source file!");
1608 
1609   // First, check the main file ID, since it is common to look for a
1610   // location in the main file.
1611   if (MainFileID.isValid()) {
1612     bool Invalid = false;
1613     const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1614     if (Invalid)
1615       return FileID();
1616 
1617     if (MainSLoc.isFile()) {
1618       if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1619         return MainFileID;
1620     }
1621   }
1622 
1623   // The location we're looking for isn't in the main file; look
1624   // through all of the local source locations.
1625   for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1626     const SLocEntry &SLoc = getLocalSLocEntry(I);
1627     if (SLoc.isFile() &&
1628         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1629       return FileID::get(I);
1630   }
1631 
1632   // If that still didn't help, try the modules.
1633   for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1634     const SLocEntry &SLoc = getLoadedSLocEntry(I);
1635     if (SLoc.isFile() &&
1636         SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1637       return FileID::get(-int(I) - 2);
1638   }
1639 
1640   return FileID();
1641 }
1642 
1643 /// Get the source location in \arg FID for the given line:col.
1644 /// Returns null location if \arg FID is not a file SLocEntry.
1645 SourceLocation SourceManager::translateLineCol(FileID FID,
1646                                                unsigned Line,
1647                                                unsigned Col) const {
1648   // Lines are used as a one-based index into a zero-based array. This assert
1649   // checks for possible buffer underruns.
1650   assert(Line && Col && "Line and column should start from 1!");
1651 
1652   if (FID.isInvalid())
1653     return SourceLocation();
1654 
1655   bool Invalid = false;
1656   const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1657   if (Invalid)
1658     return SourceLocation();
1659 
1660   if (!Entry.isFile())
1661     return SourceLocation();
1662 
1663   SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1664 
1665   if (Line == 1 && Col == 1)
1666     return FileLoc;
1667 
1668   const ContentCache *Content = &Entry.getFile().getContentCache();
1669 
1670   // If this is the first use of line information for this buffer, compute the
1671   // SourceLineCache for it on demand.
1672   std::optional<llvm::MemoryBufferRef> Buffer =
1673       Content->getBufferOrNone(Diag, getFileManager());
1674   if (!Buffer)
1675     return SourceLocation();
1676   if (!Content->SourceLineCache)
1677     Content->SourceLineCache =
1678         LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1679 
1680   if (Line > Content->SourceLineCache.size()) {
1681     unsigned Size = Buffer->getBufferSize();
1682     if (Size > 0)
1683       --Size;
1684     return FileLoc.getLocWithOffset(Size);
1685   }
1686 
1687   unsigned FilePos = Content->SourceLineCache[Line - 1];
1688   const char *Buf = Buffer->getBufferStart() + FilePos;
1689   unsigned BufLength = Buffer->getBufferSize() - FilePos;
1690   if (BufLength == 0)
1691     return FileLoc.getLocWithOffset(FilePos);
1692 
1693   unsigned i = 0;
1694 
1695   // Check that the given column is valid.
1696   while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1697     ++i;
1698   return FileLoc.getLocWithOffset(FilePos + i);
1699 }
1700 
1701 /// Compute a map of macro argument chunks to their expanded source
1702 /// location. Chunks that are not part of a macro argument will map to an
1703 /// invalid source location. e.g. if a file contains one macro argument at
1704 /// offset 100 with length 10, this is how the map will be formed:
1705 ///     0   -> SourceLocation()
1706 ///     100 -> Expanded macro arg location
1707 ///     110 -> SourceLocation()
1708 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1709                                           FileID FID) const {
1710   assert(FID.isValid());
1711 
1712   // Initially no macro argument chunk is present.
1713   MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1714 
1715   int ID = FID.ID;
1716   while (true) {
1717     ++ID;
1718     // Stop if there are no more FileIDs to check.
1719     if (ID > 0) {
1720       if (unsigned(ID) >= local_sloc_entry_size())
1721         return;
1722     } else if (ID == -1) {
1723       return;
1724     }
1725 
1726     bool Invalid = false;
1727     const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1728     if (Invalid)
1729       return;
1730     if (Entry.isFile()) {
1731       auto& File = Entry.getFile();
1732       if (File.getFileCharacteristic() == C_User_ModuleMap ||
1733           File.getFileCharacteristic() == C_System_ModuleMap)
1734         continue;
1735 
1736       SourceLocation IncludeLoc = File.getIncludeLoc();
1737       bool IncludedInFID =
1738           (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1739           // Predefined header doesn't have a valid include location in main
1740           // file, but any files created by it should still be skipped when
1741           // computing macro args expanded in the main file.
1742           (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1743       if (IncludedInFID) {
1744         // Skip the files/macros of the #include'd file, we only care about
1745         // macros that lexed macro arguments from our file.
1746         if (Entry.getFile().NumCreatedFIDs)
1747           ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1748         continue;
1749       }
1750       // If file was included but not from FID, there is no more files/macros
1751       // that may be "contained" in this file.
1752       if (IncludeLoc.isValid())
1753         return;
1754       continue;
1755     }
1756 
1757     const ExpansionInfo &ExpInfo = Entry.getExpansion();
1758 
1759     if (ExpInfo.getExpansionLocStart().isFileID()) {
1760       if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1761         return; // No more files/macros that may be "contained" in this file.
1762     }
1763 
1764     if (!ExpInfo.isMacroArgExpansion())
1765       continue;
1766 
1767     associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1768                                  ExpInfo.getSpellingLoc(),
1769                                  SourceLocation::getMacroLoc(Entry.getOffset()),
1770                                  getFileIDSize(FileID::get(ID)));
1771   }
1772 }
1773 
1774 void SourceManager::associateFileChunkWithMacroArgExp(
1775                                          MacroArgsMap &MacroArgsCache,
1776                                          FileID FID,
1777                                          SourceLocation SpellLoc,
1778                                          SourceLocation ExpansionLoc,
1779                                          unsigned ExpansionLength) const {
1780   if (!SpellLoc.isFileID()) {
1781     SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1782     SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
1783 
1784     // The spelling range for this macro argument expansion can span multiple
1785     // consecutive FileID entries. Go through each entry contained in the
1786     // spelling range and if one is itself a macro argument expansion, recurse
1787     // and associate the file chunk that it represents.
1788 
1789     FileID SpellFID; // Current FileID in the spelling range.
1790     unsigned SpellRelativeOffs;
1791     std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1792     while (true) {
1793       const SLocEntry &Entry = getSLocEntry(SpellFID);
1794       SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
1795       unsigned SpellFIDSize = getFileIDSize(SpellFID);
1796       SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1797       const ExpansionInfo &Info = Entry.getExpansion();
1798       if (Info.isMacroArgExpansion()) {
1799         unsigned CurrSpellLength;
1800         if (SpellFIDEndOffs < SpellEndOffs)
1801           CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1802         else
1803           CurrSpellLength = ExpansionLength;
1804         associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1805                       Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1806                       ExpansionLoc, CurrSpellLength);
1807       }
1808 
1809       if (SpellFIDEndOffs >= SpellEndOffs)
1810         return; // we covered all FileID entries in the spelling range.
1811 
1812       // Move to the next FileID entry in the spelling range.
1813       unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1814       ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1815       ExpansionLength -= advance;
1816       ++SpellFID.ID;
1817       SpellRelativeOffs = 0;
1818     }
1819   }
1820 
1821   assert(SpellLoc.isFileID());
1822 
1823   unsigned BeginOffs;
1824   if (!isInFileID(SpellLoc, FID, &BeginOffs))
1825     return;
1826 
1827   unsigned EndOffs = BeginOffs + ExpansionLength;
1828 
1829   // Add a new chunk for this macro argument. A previous macro argument chunk
1830   // may have been lexed again, so e.g. if the map is
1831   //     0   -> SourceLocation()
1832   //     100 -> Expanded loc #1
1833   //     110 -> SourceLocation()
1834   // and we found a new macro FileID that lexed from offset 105 with length 3,
1835   // the new map will be:
1836   //     0   -> SourceLocation()
1837   //     100 -> Expanded loc #1
1838   //     105 -> Expanded loc #2
1839   //     108 -> Expanded loc #1
1840   //     110 -> SourceLocation()
1841   //
1842   // Since re-lexed macro chunks will always be the same size or less of
1843   // previous chunks, we only need to find where the ending of the new macro
1844   // chunk is mapped to and update the map with new begin/end mappings.
1845 
1846   MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1847   --I;
1848   SourceLocation EndOffsMappedLoc = I->second;
1849   MacroArgsCache[BeginOffs] = ExpansionLoc;
1850   MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1851 }
1852 
1853 void SourceManager::updateSlocUsageStats() const {
1854   SourceLocation::UIntTy UsedBytes =
1855       NextLocalOffset + (MaxLoadedOffset - CurrentLoadedOffset);
1856   MaxUsedSLocBytes.updateMax(UsedBytes);
1857 }
1858 
1859 /// If \arg Loc points inside a function macro argument, the returned
1860 /// location will be the macro location in which the argument was expanded.
1861 /// If a macro argument is used multiple times, the expanded location will
1862 /// be at the first expansion of the argument.
1863 /// e.g.
1864 ///   MY_MACRO(foo);
1865 ///             ^
1866 /// Passing a file location pointing at 'foo', will yield a macro location
1867 /// where 'foo' was expanded into.
1868 SourceLocation
1869 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1870   if (Loc.isInvalid() || !Loc.isFileID())
1871     return Loc;
1872 
1873   FileID FID;
1874   unsigned Offset;
1875   std::tie(FID, Offset) = getDecomposedLoc(Loc);
1876   if (FID.isInvalid())
1877     return Loc;
1878 
1879   std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1880   if (!MacroArgsCache) {
1881     MacroArgsCache = std::make_unique<MacroArgsMap>();
1882     computeMacroArgsCache(*MacroArgsCache, FID);
1883   }
1884 
1885   assert(!MacroArgsCache->empty());
1886   MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1887   // In case every element in MacroArgsCache is greater than Offset we can't
1888   // decrement the iterator.
1889   if (I == MacroArgsCache->begin())
1890     return Loc;
1891 
1892   --I;
1893 
1894   SourceLocation::UIntTy MacroArgBeginOffs = I->first;
1895   SourceLocation MacroArgExpandedLoc = I->second;
1896   if (MacroArgExpandedLoc.isValid())
1897     return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1898 
1899   return Loc;
1900 }
1901 
1902 std::pair<FileID, unsigned>
1903 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1904   if (FID.isInvalid())
1905     return std::make_pair(FileID(), 0);
1906 
1907   // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1908 
1909   using DecompTy = std::pair<FileID, unsigned>;
1910   auto InsertOp = IncludedLocMap.try_emplace(FID);
1911   DecompTy &DecompLoc = InsertOp.first->second;
1912   if (!InsertOp.second)
1913     return DecompLoc; // already in map.
1914 
1915   SourceLocation UpperLoc;
1916   bool Invalid = false;
1917   const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1918   if (!Invalid) {
1919     if (Entry.isExpansion())
1920       UpperLoc = Entry.getExpansion().getExpansionLocStart();
1921     else
1922       UpperLoc = Entry.getFile().getIncludeLoc();
1923   }
1924 
1925   if (UpperLoc.isValid())
1926     DecompLoc = getDecomposedLoc(UpperLoc);
1927 
1928   return DecompLoc;
1929 }
1930 
1931 FileID SourceManager::getUniqueLoadedASTFileID(SourceLocation Loc) const {
1932   assert(isLoadedSourceLocation(Loc) &&
1933          "Must be a source location in a loaded PCH/Module file");
1934 
1935   auto [FID, Ignore] = getDecomposedLoc(Loc);
1936   // `LoadedSLocEntryAllocBegin` stores the sorted lowest FID of each loaded
1937   // allocation. Later allocations have lower FileIDs. The call below is to find
1938   // the lowest FID of a loaded allocation from any FID in the same allocation.
1939   // The lowest FID is used to identify a loaded allocation.
1940   const FileID *FirstFID =
1941       llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, std::greater<FileID>{});
1942 
1943   assert(FirstFID &&
1944          "The failure to find the first FileID of a "
1945          "loaded AST from a loaded source location was unexpected.");
1946   return *FirstFID;
1947 }
1948 
1949 bool SourceManager::isInTheSameTranslationUnitImpl(
1950     const std::pair<FileID, unsigned> &LOffs,
1951     const std::pair<FileID, unsigned> &ROffs) const {
1952   // If one is local while the other is loaded.
1953   if (isLoadedFileID(LOffs.first) != isLoadedFileID(ROffs.first))
1954     return false;
1955 
1956   if (isLoadedFileID(LOffs.first) && isLoadedFileID(ROffs.first)) {
1957     auto FindSLocEntryAlloc = [this](FileID FID) {
1958       // Loaded FileIDs are negative, we store the lowest FileID from each
1959       // allocation, later allocations have lower FileIDs.
1960       return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID,
1961                                std::greater<FileID>{});
1962     };
1963 
1964     // If both are loaded from different AST files.
1965     if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first))
1966       return false;
1967   }
1968 
1969   return true;
1970 }
1971 
1972 /// Given a decomposed source location, move it up the include/expansion stack
1973 /// to the parent source location within the same translation unit.  If this is
1974 /// possible, return the decomposed version of the parent in Loc and return
1975 /// false.  If Loc is a top-level entry, return true and don't modify it.
1976 static bool
1977 MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1978                                       const SourceManager &SM) {
1979   std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1980   if (UpperLoc.first.isInvalid() ||
1981       !SM.isInTheSameTranslationUnitImpl(UpperLoc, Loc))
1982     return true; // We reached the top.
1983 
1984   Loc = UpperLoc;
1985   return false;
1986 }
1987 
1988 /// Return the cache entry for comparing the given file IDs
1989 /// for isBeforeInTranslationUnit.
1990 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1991                                                             FileID RFID) const {
1992   // This is a magic number for limiting the cache size.  It was experimentally
1993   // derived from a small Objective-C project (where the cache filled
1994   // out to ~250 items).  We can make it larger if necessary.
1995   // FIXME: this is almost certainly full these days. Use an LRU cache?
1996   enum { MagicCacheSize = 300 };
1997   IsBeforeInTUCacheKey Key(LFID, RFID);
1998 
1999   // If the cache size isn't too large, do a lookup and if necessary default
2000   // construct an entry.  We can then return it to the caller for direct
2001   // use.  When they update the value, the cache will get automatically
2002   // updated as well.
2003   if (IBTUCache.size() < MagicCacheSize)
2004     return IBTUCache.try_emplace(Key, LFID, RFID).first->second;
2005 
2006   // Otherwise, do a lookup that will not construct a new value.
2007   InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2008   if (I != IBTUCache.end())
2009     return I->second;
2010 
2011   // Fall back to the overflow value.
2012   IBTUCacheOverflow.setQueryFIDs(LFID, RFID);
2013   return IBTUCacheOverflow;
2014 }
2015 
2016 /// Determines the order of 2 source locations in the translation unit.
2017 ///
2018 /// \returns true if LHS source location comes before RHS, false otherwise.
2019 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2020                                               SourceLocation RHS) const {
2021   assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2022   if (LHS == RHS)
2023     return false;
2024 
2025   std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2026   std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2027 
2028   // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2029   // is a serialized one referring to a file that was removed after we loaded
2030   // the PCH.
2031   if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2032     return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2033 
2034   std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2035   if (InSameTU.first)
2036     return InSameTU.second;
2037   // This case is used by libclang: clang_isBeforeInTranslationUnit
2038   return LOffs.first < ROffs.first;
2039 }
2040 
2041 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2042     std::pair<FileID, unsigned> &LOffs,
2043     std::pair<FileID, unsigned> &ROffs) const {
2044   // If the source locations are not in the same TU, return early.
2045   if (!isInTheSameTranslationUnitImpl(LOffs, ROffs))
2046     return std::make_pair(false, false);
2047 
2048   // If the source locations are in the same file, just compare offsets.
2049   if (LOffs.first == ROffs.first)
2050     return std::make_pair(true, LOffs.second < ROffs.second);
2051 
2052   // If we are comparing a source location with multiple locations in the same
2053   // file, we get a big win by caching the result.
2054   InBeforeInTUCacheEntry &IsBeforeInTUCache =
2055     getInBeforeInTUCache(LOffs.first, ROffs.first);
2056 
2057   // If we are comparing a source location with multiple locations in the same
2058   // file, we get a big win by caching the result.
2059   if (IsBeforeInTUCache.isCacheValid())
2060     return std::make_pair(
2061         true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2062 
2063   // Okay, we missed in the cache, we'll compute the answer and populate it.
2064   // We need to find the common ancestor. The only way of doing this is to
2065   // build the complete include chain for one and then walking up the chain
2066   // of the other looking for a match.
2067 
2068   // A location within a FileID on the path up from LOffs to the main file.
2069   struct Entry {
2070     std::pair<FileID, unsigned> DecomposedLoc; // FileID redundant, but clearer.
2071     FileID ChildFID; // Used for breaking ties. Invalid for the initial loc.
2072   };
2073   llvm::SmallDenseMap<FileID, Entry, 16> LChain;
2074 
2075   FileID LChild;
2076   do {
2077     LChain.try_emplace(LOffs.first, Entry{LOffs, LChild});
2078     // We catch the case where LOffs is in a file included by ROffs and
2079     // quit early. The other way round unfortunately remains suboptimal.
2080     if (LOffs.first == ROffs.first)
2081       break;
2082     LChild = LOffs.first;
2083   } while (!MoveUpTranslationUnitIncludeHierarchy(LOffs, *this));
2084 
2085   FileID RChild;
2086   do {
2087     auto LIt = LChain.find(ROffs.first);
2088     if (LIt != LChain.end()) {
2089       // Compare the locations within the common file and cache them.
2090       LOffs = LIt->second.DecomposedLoc;
2091       LChild = LIt->second.ChildFID;
2092       // The relative order of LChild and RChild is a tiebreaker when
2093       // - locs expand to the same location (occurs in macro arg expansion)
2094       // - one loc is a parent of the other (we consider the parent as "first")
2095       // For the parent entry to be first, its invalid child file ID must
2096       // compare smaller to the valid child file ID of the other entry.
2097       // However loaded FileIDs are <0, so we perform *unsigned* comparison!
2098       // This changes the relative order of local vs loaded FileIDs, but it
2099       // doesn't matter as these are never mixed in macro expansion.
2100       unsigned LChildID = LChild.ID;
2101       unsigned RChildID = RChild.ID;
2102       assert(((LOffs.second != ROffs.second) ||
2103               (LChildID == 0 || RChildID == 0) ||
2104               isInSameSLocAddrSpace(getComposedLoc(LChild, 0),
2105                                     getComposedLoc(RChild, 0), nullptr)) &&
2106              "Mixed local/loaded FileIDs with same include location?");
2107       IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second,
2108                                      LChildID < RChildID);
2109       return std::make_pair(
2110           true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2111     }
2112     RChild = ROffs.first;
2113   } while (!MoveUpTranslationUnitIncludeHierarchy(ROffs, *this));
2114 
2115   // If we found no match, the location is either in a built-ins buffer or
2116   // associated with global inline asm. PR5662 and PR22576 are examples.
2117 
2118   StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2119   StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
2120 
2121   bool LIsBuiltins = LB == "<built-in>";
2122   bool RIsBuiltins = RB == "<built-in>";
2123   // Sort built-in before non-built-in.
2124   if (LIsBuiltins || RIsBuiltins) {
2125     if (LIsBuiltins != RIsBuiltins)
2126       return std::make_pair(true, LIsBuiltins);
2127     // Both are in built-in buffers, but from different files. We just claim
2128     // that lower IDs come first.
2129     return std::make_pair(true, LOffs.first < ROffs.first);
2130   }
2131 
2132   bool LIsAsm = LB == "<inline asm>";
2133   bool RIsAsm = RB == "<inline asm>";
2134   // Sort assembler after built-ins, but before the rest.
2135   if (LIsAsm || RIsAsm) {
2136     if (LIsAsm != RIsAsm)
2137       return std::make_pair(true, RIsAsm);
2138     assert(LOffs.first == ROffs.first);
2139     return std::make_pair(true, false);
2140   }
2141 
2142   bool LIsScratch = LB == "<scratch space>";
2143   bool RIsScratch = RB == "<scratch space>";
2144   // Sort scratch after inline asm, but before the rest.
2145   if (LIsScratch || RIsScratch) {
2146     if (LIsScratch != RIsScratch)
2147       return std::make_pair(true, LIsScratch);
2148     return std::make_pair(true, LOffs.second < ROffs.second);
2149   }
2150 
2151   llvm_unreachable("Unsortable locations found");
2152 }
2153 
2154 void SourceManager::PrintStats() const {
2155   llvm::errs() << "\n*** Source Manager Stats:\n";
2156   llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2157                << " mem buffers mapped.\n";
2158   llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntries allocated ("
2159                << llvm::capacity_in_bytes(LocalSLocEntryTable)
2160                << " bytes of capacity), " << NextLocalOffset
2161                << "B of SLoc address space used.\n";
2162   llvm::errs() << LoadedSLocEntryTable.size()
2163                << " loaded SLocEntries allocated ("
2164                << llvm::capacity_in_bytes(LoadedSLocEntryTable)
2165                << " bytes of capacity), "
2166                << MaxLoadedOffset - CurrentLoadedOffset
2167                << "B of SLoc address space used.\n";
2168 
2169   unsigned NumLineNumsComputed = 0;
2170   unsigned NumFileBytesMapped = 0;
2171   for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2172     NumLineNumsComputed += bool(I->second->SourceLineCache);
2173     NumFileBytesMapped  += I->second->getSizeBytesMapped();
2174   }
2175   unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2176 
2177   llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2178                << NumLineNumsComputed << " files with line #'s computed, "
2179                << NumMacroArgsComputed << " files with macro args computed.\n";
2180   llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2181                << NumBinaryProbes << " binary.\n";
2182 }
2183 
2184 LLVM_DUMP_METHOD void SourceManager::dump() const {
2185   llvm::raw_ostream &out = llvm::errs();
2186 
2187   auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2188                            std::optional<SourceLocation::UIntTy> NextStart) {
2189     out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2190         << " <SourceLocation " << Entry.getOffset() << ":";
2191     if (NextStart)
2192       out << *NextStart << ">\n";
2193     else
2194       out << "???\?>\n";
2195     if (Entry.isFile()) {
2196       auto &FI = Entry.getFile();
2197       if (FI.NumCreatedFIDs)
2198         out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2199             << ">\n";
2200       if (FI.getIncludeLoc().isValid())
2201         out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2202       auto &CC = FI.getContentCache();
2203       out << "  for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
2204           << "\n";
2205       if (CC.BufferOverridden)
2206         out << "  contents overridden\n";
2207       if (CC.ContentsEntry != CC.OrigEntry) {
2208         out << "  contents from "
2209             << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
2210             << "\n";
2211       }
2212     } else {
2213       auto &EI = Entry.getExpansion();
2214       out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2215       out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2216           << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2217           << EI.getExpansionLocEnd().getOffset() << ">\n";
2218     }
2219   };
2220 
2221   // Dump local SLocEntries.
2222   for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2223     DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2224                   ID == NumIDs - 1 ? NextLocalOffset
2225                                    : LocalSLocEntryTable[ID + 1].getOffset());
2226   }
2227   // Dump loaded SLocEntries.
2228   std::optional<SourceLocation::UIntTy> NextStart;
2229   for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2230     int ID = -(int)Index - 2;
2231     if (SLocEntryLoaded[Index]) {
2232       DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2233       NextStart = LoadedSLocEntryTable[Index].getOffset();
2234     } else {
2235       NextStart = std::nullopt;
2236     }
2237   }
2238 }
2239 
2240 void SourceManager::noteSLocAddressSpaceUsage(
2241     DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const {
2242   struct Info {
2243     // A location where this file was entered.
2244     SourceLocation Loc;
2245     // Number of times this FileEntry was entered.
2246     unsigned Inclusions = 0;
2247     // Size usage from the file itself.
2248     uint64_t DirectSize = 0;
2249     // Total size usage from the file and its macro expansions.
2250     uint64_t TotalSize = 0;
2251   };
2252   using UsageMap = llvm::MapVector<const FileEntry*, Info>;
2253 
2254   UsageMap Usage;
2255   uint64_t CountedSize = 0;
2256 
2257   auto AddUsageForFileID = [&](FileID ID) {
2258     // The +1 here is because getFileIDSize doesn't include the extra byte for
2259     // the one-past-the-end location.
2260     unsigned Size = getFileIDSize(ID) + 1;
2261 
2262     // Find the file that used this address space, either directly or by
2263     // macro expansion.
2264     SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0));
2265     FileID FileLocID = getFileID(FileStart);
2266     const FileEntry *Entry = getFileEntryForID(FileLocID);
2267 
2268     Info &EntryInfo = Usage[Entry];
2269     if (EntryInfo.Loc.isInvalid())
2270       EntryInfo.Loc = FileStart;
2271     if (ID == FileLocID) {
2272       ++EntryInfo.Inclusions;
2273       EntryInfo.DirectSize += Size;
2274     }
2275     EntryInfo.TotalSize += Size;
2276     CountedSize += Size;
2277   };
2278 
2279   // Loaded SLocEntries have indexes counting downwards from -2.
2280   for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2281     AddUsageForFileID(FileID::get(-2 - Index));
2282   }
2283   // Local SLocEntries have indexes counting upwards from 0.
2284   for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) {
2285     AddUsageForFileID(FileID::get(Index));
2286   }
2287 
2288   // Sort the usage by size from largest to smallest. Break ties by raw source
2289   // location.
2290   auto SortedUsage = Usage.takeVector();
2291   auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) {
2292     return A.second.TotalSize > B.second.TotalSize ||
2293            (A.second.TotalSize == B.second.TotalSize &&
2294             A.second.Loc < B.second.Loc);
2295   };
2296   auto SortedEnd = SortedUsage.end();
2297   if (MaxNotes && SortedUsage.size() > *MaxNotes) {
2298     SortedEnd = SortedUsage.begin() + *MaxNotes;
2299     std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp);
2300   }
2301   std::sort(SortedUsage.begin(), SortedEnd, Cmp);
2302 
2303   // Produce note on sloc address space usage total.
2304   uint64_t LocalUsage = NextLocalOffset;
2305   uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset;
2306   int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) /
2307                                       MaxLoadedOffset);
2308   Diag.Report(SourceLocation(), diag::note_total_sloc_usage)
2309     << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent;
2310 
2311   // Produce notes on sloc address space usage for each file with a high usage.
2312   uint64_t ReportedSize = 0;
2313   for (auto &[Entry, FileInfo] :
2314        llvm::make_range(SortedUsage.begin(), SortedEnd)) {
2315     Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage)
2316         << FileInfo.Inclusions << FileInfo.DirectSize
2317         << (FileInfo.TotalSize - FileInfo.DirectSize);
2318     ReportedSize += FileInfo.TotalSize;
2319   }
2320 
2321   // Describe any remaining usage not reported in the per-file usage.
2322   if (ReportedSize != CountedSize) {
2323     Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage)
2324         << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize;
2325   }
2326 }
2327 
2328 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2329 
2330 /// Return the amount of memory used by memory buffers, breaking down
2331 /// by heap-backed versus mmap'ed memory.
2332 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2333   size_t malloc_bytes = 0;
2334   size_t mmap_bytes = 0;
2335 
2336   for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2337     if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2338       switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2339         case llvm::MemoryBuffer::MemoryBuffer_MMap:
2340           mmap_bytes += sized_mapped;
2341           break;
2342         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2343           malloc_bytes += sized_mapped;
2344           break;
2345       }
2346 
2347   return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2348 }
2349 
2350 size_t SourceManager::getDataStructureSizes() const {
2351   size_t size = llvm::capacity_in_bytes(MemBufferInfos) +
2352                 llvm::capacity_in_bytes(LocalSLocEntryTable) +
2353                 llvm::capacity_in_bytes(LoadedSLocEntryTable) +
2354                 llvm::capacity_in_bytes(SLocEntryLoaded) +
2355                 llvm::capacity_in_bytes(FileInfos);
2356 
2357   if (OverriddenFilesInfo)
2358     size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2359 
2360   return size;
2361 }
2362 
2363 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2364                                            StringRef Content) {
2365   // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2366   // is deleted.
2367   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2368       new llvm::vfs::InMemoryFileSystem);
2369   InMemoryFileSystem->addFile(
2370       FileName, 0,
2371       llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2372                                        /*RequiresNullTerminator=*/false));
2373   // This is passed to `SM` as reference, so the pointer has to be referenced
2374   // in `Environment` so that `FileMgr` can out-live this function scope.
2375   FileMgr =
2376       std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2377   // This is passed to `SM` as reference, so the pointer has to be referenced
2378   // by `Environment` due to the same reason above.
2379   Diagnostics = std::make_unique<DiagnosticsEngine>(
2380       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2381       new DiagnosticOptions);
2382   SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2383   FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName));
2384   FileID ID =
2385       SourceMgr->createFileID(FE, SourceLocation(), clang::SrcMgr::C_User);
2386   assert(ID.isValid());
2387   SourceMgr->setMainFileID(ID);
2388 }
2389