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