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