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