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