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