1 //===- SourceManager.cpp - Track and cache source files -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SourceManager interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LLVM.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManagerInternals.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Capacity.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
46 using namespace SrcMgr;
47 using llvm::MemoryBuffer;
49 //===----------------------------------------------------------------------===//
50 // SourceManager Helper Classes
51 //===----------------------------------------------------------------------===//
53 ContentCache::~ContentCache() {
54 if (shouldFreeBuffer())
55 delete Buffer.getPointer();
58 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
59 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
60 unsigned ContentCache::getSizeBytesMapped() const {
61 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
64 /// Returns the kind of memory used to back the memory buffer for
65 /// this content cache. This is used for performance analysis.
66 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
67 assert(Buffer.getPointer());
69 // Should be unreachable, but keep for sanity.
70 if (!Buffer.getPointer())
71 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
73 llvm::MemoryBuffer *buf = Buffer.getPointer();
74 return buf->getBufferKind();
77 /// getSize - Returns the size of the content encapsulated by this ContentCache.
78 /// This can be the size of the source file or the size of an arbitrary
79 /// scratch buffer. If the ContentCache encapsulates a source file, that
80 /// file is not lazily brought in from disk to satisfy this query.
81 unsigned ContentCache::getSize() const {
82 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
83 : (unsigned) ContentsEntry->getSize();
86 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
87 if (B && B == Buffer.getPointer()) {
88 assert(0 && "Replacing with the same buffer");
89 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
93 if (shouldFreeBuffer())
94 delete Buffer.getPointer();
96 Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
99 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
100 const SourceManager &SM,
102 bool *Invalid) const {
103 // Lazily create the Buffer for ContentCaches that wrap files. If we already
104 // computed it, just return what we have.
105 if (Buffer.getPointer() || !ContentsEntry) {
107 *Invalid = isBufferInvalid();
109 return Buffer.getPointer();
112 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
114 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
116 // If we were unable to open the file, then we are in an inconsistent
117 // situation where the content cache referenced a file which no longer
118 // exists. Most likely, we were using a stat cache with an invalid entry but
119 // the file could also have been removed during processing. Since we can't
120 // really deal with this situation, just create an empty buffer.
122 // FIXME: This is definitely not ideal, but our immediate clients can't
123 // currently handle returning a null entry here. Ideally we should detect
124 // that we are in an inconsistent situation and error out as quickly as
126 if (!BufferOrError) {
127 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
128 auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
129 ContentsEntry->getSize(), "<invalid>");
130 char *Ptr = BackupBuffer->getBufferStart();
131 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
132 Ptr[i] = FillStr[i % FillStr.size()];
133 Buffer.setPointer(BackupBuffer.release());
135 if (Diag.isDiagnosticInFlight())
136 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
137 ContentsEntry->getName(),
138 BufferOrError.getError().message());
140 Diag.Report(Loc, diag::err_cannot_open_file)
141 << ContentsEntry->getName() << BufferOrError.getError().message();
143 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
149 Buffer.setPointer(BufferOrError->release());
151 // Check that the file's size is the same as in the file entry (which may
152 // have come from a stat cache).
153 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
154 if (Diag.isDiagnosticInFlight())
155 Diag.SetDelayedDiagnostic(diag::err_file_modified,
156 ContentsEntry->getName());
158 Diag.Report(Loc, diag::err_file_modified)
159 << ContentsEntry->getName();
161 Buffer.setInt(Buffer.getInt() | InvalidFlag);
162 if (Invalid) *Invalid = true;
163 return Buffer.getPointer();
166 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
167 // (BOM). We only support UTF-8 with and without a BOM right now. See
168 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
169 StringRef BufStr = Buffer.getPointer()->getBuffer();
170 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
171 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
172 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
173 .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
175 .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
177 .StartsWith("\x2B\x2F\x76", "UTF-7")
178 .StartsWith("\xF7\x64\x4C", "UTF-1")
179 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
180 .StartsWith("\x0E\xFE\xFF", "SDSU")
181 .StartsWith("\xFB\xEE\x28", "BOCU-1")
182 .StartsWith("\x84\x31\x95\x33", "GB-18030")
186 Diag.Report(Loc, diag::err_unsupported_bom)
187 << InvalidBOM << ContentsEntry->getName();
188 Buffer.setInt(Buffer.getInt() | InvalidFlag);
192 *Invalid = isBufferInvalid();
194 return Buffer.getPointer();
197 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
198 auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
200 FilenamesByID.push_back(&*IterBool.first);
201 return IterBool.first->second;
204 /// Add a line note to the line table that indicates that there is a \#line or
205 /// GNU line marker at the specified FID/Offset location which changes the
206 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
207 /// change the presumed \#include stack. If it is 1, this is a file entry, if
208 /// it is 2 then this is a file exit. FileKind specifies whether this is a
209 /// system header or extern C system header.
210 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
211 int FilenameID, unsigned EntryExit,
212 SrcMgr::CharacteristicKind FileKind) {
213 std::vector<LineEntry> &Entries = LineEntries[FID];
215 // An unspecified FilenameID means use the last filename if available, or the
216 // main source file otherwise.
217 if (FilenameID == -1 && !Entries.empty())
218 FilenameID = Entries.back().FilenameID;
220 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
221 "Adding line entries out of order!");
223 unsigned IncludeOffset = 0;
224 if (EntryExit == 0) { // No #include stack change.
225 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
226 } else if (EntryExit == 1) {
227 IncludeOffset = Offset-1;
228 } else if (EntryExit == 2) {
229 assert(!Entries.empty() && Entries.back().IncludeOffset &&
230 "PPDirectives should have caught case when popping empty include stack");
232 // Get the include loc of the last entries' include loc as our include loc.
234 if (const LineEntry *PrevEntry =
235 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
236 IncludeOffset = PrevEntry->IncludeOffset;
239 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
243 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
244 /// it. If there is no line entry before Offset in FID, return null.
245 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
247 const std::vector<LineEntry> &Entries = LineEntries[FID];
248 assert(!Entries.empty() && "No #line entries for this FID after all!");
250 // It is very common for the query to be after the last #line, check this
252 if (Entries.back().FileOffset <= Offset)
253 return &Entries.back();
255 // Do a binary search to find the maximal element that is still before Offset.
256 std::vector<LineEntry>::const_iterator I =
257 std::upper_bound(Entries.begin(), Entries.end(), Offset);
258 if (I == Entries.begin()) return nullptr;
262 /// Add a new line entry that has already been encoded into
263 /// the internal representation of the line table.
264 void LineTableInfo::AddEntry(FileID FID,
265 const std::vector<LineEntry> &Entries) {
266 LineEntries[FID] = Entries;
269 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
270 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
271 return getLineTable().getLineTableFilenameID(Name);
274 /// AddLineNote - Add a line note to the line table for the FileID and offset
275 /// specified by Loc. If FilenameID is -1, it is considered to be
277 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
278 int FilenameID, bool IsFileEntry,
280 SrcMgr::CharacteristicKind FileKind) {
281 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
283 bool Invalid = false;
284 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
285 if (!Entry.isFile() || Invalid)
288 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
290 // Remember that this file has #line directives now if it doesn't already.
291 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
293 (void) getLineTable();
295 unsigned EntryExit = 0;
301 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
302 EntryExit, FileKind);
305 LineTableInfo &SourceManager::getLineTable() {
307 LineTable = new LineTableInfo();
311 //===----------------------------------------------------------------------===//
312 // Private 'Create' methods.
313 //===----------------------------------------------------------------------===//
315 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
316 bool UserFilesAreVolatile)
317 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
319 Diag.setSourceManager(this);
322 SourceManager::~SourceManager() {
325 // Delete FileEntry objects corresponding to content caches. Since the actual
326 // content cache objects are bump pointer allocated, we just have to run the
327 // dtors, but we call the deallocate method for completeness.
328 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
329 if (MemBufferInfos[i]) {
330 MemBufferInfos[i]->~ContentCache();
331 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
334 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
335 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
337 I->second->~ContentCache();
338 ContentCacheAlloc.Deallocate(I->second);
343 void SourceManager::clearIDTables() {
344 MainFileID = FileID();
345 LocalSLocEntryTable.clear();
346 LoadedSLocEntryTable.clear();
347 SLocEntryLoaded.clear();
348 LastLineNoFileIDQuery = FileID();
349 LastLineNoContentCache = nullptr;
350 LastFileIDLookup = FileID();
355 // Use up FileID #0 as an invalid expansion.
357 CurrentLoadedOffset = MaxLoadedOffset;
358 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
361 void SourceManager::initializeForReplay(const SourceManager &Old) {
362 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
364 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
365 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
366 Clone->OrigEntry = Cache->OrigEntry;
367 Clone->ContentsEntry = Cache->ContentsEntry;
368 Clone->BufferOverridden = Cache->BufferOverridden;
369 Clone->IsSystemFile = Cache->IsSystemFile;
370 Clone->IsTransient = Cache->IsTransient;
371 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
375 // Ensure all SLocEntries are loaded from the external source.
376 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
377 if (!Old.SLocEntryLoaded[I])
378 Old.loadSLocEntry(I, nullptr);
380 // Inherit any content cache data from the old source manager.
381 for (auto &FileInfo : Old.FileInfos) {
382 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
385 Slot = CloneContentCache(FileInfo.second);
389 /// getOrCreateContentCache - Create or return a cached ContentCache for the
392 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
394 assert(FileEnt && "Didn't specify a file entry to use?");
396 // Do we already have information about this file?
397 ContentCache *&Entry = FileInfos[FileEnt];
398 if (Entry) return Entry;
400 // Nope, create a new Cache entry.
401 Entry = ContentCacheAlloc.Allocate<ContentCache>();
403 if (OverriddenFilesInfo) {
404 // If the file contents are overridden with contents from another file,
405 // pass that file to ContentCache.
406 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
407 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
408 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
409 new (Entry) ContentCache(FileEnt);
411 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
415 new (Entry) ContentCache(FileEnt);
418 Entry->IsSystemFile = isSystemFile;
419 Entry->IsTransient = FilesAreTransient;
424 /// Create a new ContentCache for the specified memory buffer.
425 /// This does no caching.
427 SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer,
429 // Add a new ContentCache to the MemBufferInfos list and return it.
430 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
431 new (Entry) ContentCache();
432 MemBufferInfos.push_back(Entry);
433 Entry->replaceBuffer(Buffer, DoNotFree);
437 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
438 bool *Invalid) const {
439 assert(!SLocEntryLoaded[Index]);
440 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
443 // If the file of the SLocEntry changed we could still have loaded it.
444 if (!SLocEntryLoaded[Index]) {
445 // Try to recover; create a SLocEntry so the rest of clang can handle it.
446 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
447 FileInfo::get(SourceLocation(),
448 getFakeContentCacheForRecovery(),
453 return LoadedSLocEntryTable[Index];
456 std::pair<int, unsigned>
457 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
458 unsigned TotalSize) {
459 assert(ExternalSLocEntries && "Don't have an external sloc source");
460 // Make sure we're not about to run out of source locations.
461 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
462 return std::make_pair(0, 0);
463 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
464 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
465 CurrentLoadedOffset -= TotalSize;
466 int ID = LoadedSLocEntryTable.size();
467 return std::make_pair(-ID - 1, CurrentLoadedOffset);
470 /// As part of recovering from missing or changed content, produce a
471 /// fake, non-empty buffer.
472 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
473 if (!FakeBufferForRecovery)
474 FakeBufferForRecovery =
475 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
477 return FakeBufferForRecovery.get();
480 /// As part of recovering from missing or changed content, produce a
481 /// fake content cache.
482 const SrcMgr::ContentCache *
483 SourceManager::getFakeContentCacheForRecovery() const {
484 if (!FakeContentCacheForRecovery) {
485 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
486 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
489 return FakeContentCacheForRecovery.get();
492 /// Returns the previous in-order FileID or an invalid FileID if there
493 /// is no previous one.
494 FileID SourceManager::getPreviousFileID(FileID FID) const {
505 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
509 return FileID::get(ID-1);
512 /// Returns the next in-order FileID or an invalid FileID if there is
514 FileID SourceManager::getNextFileID(FileID FID) const {
520 if (unsigned(ID+1) >= local_sloc_entry_size())
522 } else if (ID+1 >= -1) {
526 return FileID::get(ID+1);
529 //===----------------------------------------------------------------------===//
530 // Methods to create new FileID's and macro expansions.
531 //===----------------------------------------------------------------------===//
533 /// createFileID - Create a new FileID for the specified ContentCache and
534 /// include position. This works regardless of whether the ContentCache
535 /// corresponds to a file or some other input source.
536 FileID SourceManager::createFileID(const ContentCache *File,
537 SourceLocation IncludePos,
538 SrcMgr::CharacteristicKind FileCharacter,
539 int LoadedID, unsigned LoadedOffset) {
541 assert(LoadedID != -1 && "Loading sentinel FileID");
542 unsigned Index = unsigned(-LoadedID) - 2;
543 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
544 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
545 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
546 FileInfo::get(IncludePos, File, FileCharacter));
547 SLocEntryLoaded[Index] = true;
548 return FileID::get(LoadedID);
550 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
551 FileInfo::get(IncludePos, File,
553 unsigned FileSize = File->getSize();
554 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
555 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
556 "Ran out of source locations!");
557 // We do a +1 here because we want a SourceLocation that means "the end of the
558 // file", e.g. for the "no newline at the end of the file" diagnostic.
559 NextLocalOffset += FileSize + 1;
561 // Set LastFileIDLookup to the newly created file. The next getFileID call is
562 // almost guaranteed to be from that file.
563 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
564 return LastFileIDLookup = FID;
568 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
569 SourceLocation ExpansionLoc,
570 unsigned TokLength) {
571 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
573 return createExpansionLocImpl(Info, TokLength);
577 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
578 SourceLocation ExpansionLocStart,
579 SourceLocation ExpansionLocEnd,
581 bool ExpansionIsTokenRange,
583 unsigned LoadedOffset) {
584 ExpansionInfo Info = ExpansionInfo::create(
585 SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
586 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
589 SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
590 SourceLocation TokenStart,
591 SourceLocation TokenEnd) {
592 assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
593 "token spans multiple files");
594 return createExpansionLocImpl(
595 ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
596 TokenEnd.getOffset() - TokenStart.getOffset());
600 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
603 unsigned LoadedOffset) {
605 assert(LoadedID != -1 && "Loading sentinel FileID");
606 unsigned Index = unsigned(-LoadedID) - 2;
607 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
608 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
609 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
610 SLocEntryLoaded[Index] = true;
611 return SourceLocation::getMacroLoc(LoadedOffset);
613 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
614 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
615 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
616 "Ran out of source locations!");
617 // See createFileID for that +1.
618 NextLocalOffset += TokLength + 1;
619 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
622 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
624 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
625 assert(IR && "getOrCreateContentCache() cannot return NULL");
626 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
629 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
630 llvm::MemoryBuffer *Buffer,
632 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
633 assert(IR && "getOrCreateContentCache() cannot return NULL");
635 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
636 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
638 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
641 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
642 const FileEntry *NewFile) {
643 assert(SourceFile->getSize() == NewFile->getSize() &&
644 "Different sizes, use the FileManager to create a virtual file with "
646 assert(FileInfos.count(SourceFile) == 0 &&
647 "This function should be called at the initialization stage, before "
648 "any parsing occurs.");
649 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
652 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
653 if (!isFileOverridden(File))
656 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
657 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
658 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
660 assert(OverriddenFilesInfo);
661 OverriddenFilesInfo->OverriddenFiles.erase(File);
662 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
665 void SourceManager::setFileIsTransient(const FileEntry *File) {
666 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
667 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
670 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
671 bool MyInvalid = false;
672 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
673 if (!SLoc.isFile() || MyInvalid) {
676 return "<<<<<INVALID SOURCE LOCATION>>>>>";
679 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
680 Diag, *this, SourceLocation(), &MyInvalid);
682 *Invalid = MyInvalid;
685 return "<<<<<INVALID SOURCE LOCATION>>>>>";
687 return Buf->getBuffer();
690 //===----------------------------------------------------------------------===//
691 // SourceLocation manipulation methods.
692 //===----------------------------------------------------------------------===//
694 /// Return the FileID for a SourceLocation.
696 /// This is the cache-miss path of getFileID. Not as hot as that function, but
697 /// still very important. It is responsible for finding the entry in the
698 /// SLocEntry tables that contains the specified location.
699 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
701 return FileID::get(0);
703 // Now it is time to search for the correct file. See where the SLocOffset
704 // sits in the global view and consult local or loaded buffers for it.
705 if (SLocOffset < NextLocalOffset)
706 return getFileIDLocal(SLocOffset);
707 return getFileIDLoaded(SLocOffset);
710 /// Return the FileID for a SourceLocation with a low offset.
712 /// This function knows that the SourceLocation is in a local buffer, not a
714 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
715 assert(SLocOffset < NextLocalOffset && "Bad function choice");
717 // After the first and second level caches, I see two common sorts of
718 // behavior: 1) a lot of searched FileID's are "near" the cached file
719 // location or are "near" the cached expansion location. 2) others are just
720 // completely random and may be a very long way away.
722 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
723 // then we fall back to a less cache efficient, but more scalable, binary
724 // search to find the location.
726 // See if this is near the file point - worst case we start scanning from the
727 // most newly created FileID.
728 const SrcMgr::SLocEntry *I;
730 if (LastFileIDLookup.ID < 0 ||
731 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
732 // Neither loc prunes our search.
733 I = LocalSLocEntryTable.end();
735 // Perhaps it is near the file point.
736 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
739 // Find the FileID that contains this. "I" is an iterator that points to a
740 // FileID whose offset is known to be larger than SLocOffset.
741 unsigned NumProbes = 0;
744 if (I->getOffset() <= SLocOffset) {
745 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
747 // If this isn't an expansion, remember it. We have good locality across
749 if (!I->isExpansion())
750 LastFileIDLookup = Res;
751 NumLinearScans += NumProbes+1;
754 if (++NumProbes == 8)
758 // Convert "I" back into an index. We know that it is an entry whose index is
759 // larger than the offset we are looking for.
760 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
761 // LessIndex - This is the lower bound of the range that we're searching.
762 // We know that the offset corresponding to the FileID is is less than
764 unsigned LessIndex = 0;
767 bool Invalid = false;
768 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
769 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
771 return FileID::get(0);
775 // If the offset of the midpoint is too large, chop the high side of the
776 // range to the midpoint.
777 if (MidOffset > SLocOffset) {
778 GreaterIndex = MiddleIndex;
782 // If the middle index contains the value, succeed and return.
783 // FIXME: This could be made faster by using a function that's aware of
784 // being in the local area.
785 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
786 FileID Res = FileID::get(MiddleIndex);
788 // If this isn't a macro expansion, remember it. We have good locality
789 // across FileID lookups.
790 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
791 LastFileIDLookup = Res;
792 NumBinaryProbes += NumProbes;
796 // Otherwise, move the low-side up to the middle index.
797 LessIndex = MiddleIndex;
801 /// Return the FileID for a SourceLocation with a high offset.
803 /// This function knows that the SourceLocation is in a loaded buffer, not a
805 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
806 // Sanity checking, otherwise a bug may lead to hanging in release build.
807 if (SLocOffset < CurrentLoadedOffset) {
808 assert(0 && "Invalid SLocOffset or bad function choice");
812 // Essentially the same as the local case, but the loaded array is sorted
813 // in the other direction.
815 // First do a linear scan from the last lookup position, if possible.
817 int LastID = LastFileIDLookup.ID;
818 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
821 I = (-LastID - 2) + 1;
824 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
825 // Make sure the entry is loaded!
826 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
827 if (E.getOffset() <= SLocOffset) {
828 FileID Res = FileID::get(-int(I) - 2);
830 if (!E.isExpansion())
831 LastFileIDLookup = Res;
832 NumLinearScans += NumProbes + 1;
837 // Linear scan failed. Do the binary search. Note the reverse sorting of the
838 // table: GreaterIndex is the one where the offset is greater, which is
839 // actually a lower index!
840 unsigned GreaterIndex = I;
841 unsigned LessIndex = LoadedSLocEntryTable.size();
845 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
846 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
847 if (E.getOffset() == 0)
848 return FileID(); // invalid entry.
852 if (E.getOffset() > SLocOffset) {
853 // Sanity checking, otherwise a bug may lead to hanging in release build.
854 if (GreaterIndex == MiddleIndex) {
855 assert(0 && "binary search missed the entry");
858 GreaterIndex = MiddleIndex;
862 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
863 FileID Res = FileID::get(-int(MiddleIndex) - 2);
864 if (!E.isExpansion())
865 LastFileIDLookup = Res;
866 NumBinaryProbes += NumProbes;
870 // Sanity checking, otherwise a bug may lead to hanging in release build.
871 if (LessIndex == MiddleIndex) {
872 assert(0 && "binary search missed the entry");
875 LessIndex = MiddleIndex;
879 SourceLocation SourceManager::
880 getExpansionLocSlowCase(SourceLocation Loc) const {
882 // Note: If Loc indicates an offset into a token that came from a macro
883 // expansion (e.g. the 5th character of the token) we do not want to add
884 // this offset when going to the expansion location. The expansion
885 // location is the macro invocation, which the offset has nothing to do
886 // with. This is unlike when we get the spelling loc, because the offset
887 // directly correspond to the token whose spelling we're inspecting.
888 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
889 } while (!Loc.isFileID());
894 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
896 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
897 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
898 Loc = Loc.getLocWithOffset(LocInfo.second);
899 } while (!Loc.isFileID());
903 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
905 if (isMacroArgExpansion(Loc))
906 Loc = getImmediateSpellingLoc(Loc);
908 Loc = getImmediateExpansionRange(Loc).getBegin();
909 } while (!Loc.isFileID());
914 std::pair<FileID, unsigned>
915 SourceManager::getDecomposedExpansionLocSlowCase(
916 const SrcMgr::SLocEntry *E) const {
917 // If this is an expansion record, walk through all the expansion points.
922 Loc = E->getExpansion().getExpansionLocStart();
924 FID = getFileID(Loc);
925 E = &getSLocEntry(FID);
926 Offset = Loc.getOffset()-E->getOffset();
927 } while (!Loc.isFileID());
929 return std::make_pair(FID, Offset);
932 std::pair<FileID, unsigned>
933 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
934 unsigned Offset) const {
935 // If this is an expansion record, walk through all the expansion points.
939 Loc = E->getExpansion().getSpellingLoc();
940 Loc = Loc.getLocWithOffset(Offset);
942 FID = getFileID(Loc);
943 E = &getSLocEntry(FID);
944 Offset = Loc.getOffset()-E->getOffset();
945 } while (!Loc.isFileID());
947 return std::make_pair(FID, Offset);
950 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
951 /// spelling location referenced by the ID. This is the first level down
952 /// towards the place where the characters that make up the lexed token can be
953 /// found. This should not generally be used by clients.
954 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
955 if (Loc.isFileID()) return Loc;
956 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
957 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
958 return Loc.getLocWithOffset(LocInfo.second);
961 /// getImmediateExpansionRange - Loc is required to be an expansion location.
962 /// Return the start/end of the expansion information.
964 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
965 assert(Loc.isMacroID() && "Not a macro expansion loc!");
966 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
967 return Expansion.getExpansionLocRange();
970 SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
971 while (isMacroArgExpansion(Loc))
972 Loc = getImmediateSpellingLoc(Loc);
976 /// getExpansionRange - Given a SourceLocation object, return the range of
977 /// tokens covered by the expansion in the ultimate file.
978 CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
980 return CharSourceRange(SourceRange(Loc, Loc), true);
982 CharSourceRange Res = getImmediateExpansionRange(Loc);
984 // Fully resolve the start and end locations to their ultimate expansion
986 while (!Res.getBegin().isFileID())
987 Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
988 while (!Res.getEnd().isFileID()) {
989 CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
990 Res.setEnd(EndRange.getEnd());
991 Res.setTokenRange(EndRange.isTokenRange());
996 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
997 SourceLocation *StartLoc) const {
998 if (!Loc.isMacroID()) return false;
1000 FileID FID = getFileID(Loc);
1001 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1002 if (!Expansion.isMacroArgExpansion()) return false;
1005 *StartLoc = Expansion.getExpansionLocStart();
1009 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1010 if (!Loc.isMacroID()) return false;
1012 FileID FID = getFileID(Loc);
1013 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1014 return Expansion.isMacroBodyExpansion();
1017 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1018 SourceLocation *MacroBegin) const {
1019 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1021 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1022 if (DecompLoc.second > 0)
1023 return false; // Does not point at the start of expansion range.
1025 bool Invalid = false;
1026 const SrcMgr::ExpansionInfo &ExpInfo =
1027 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1030 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1032 if (ExpInfo.isMacroArgExpansion()) {
1033 // For macro argument expansions, check if the previous FileID is part of
1034 // the same argument expansion, in which case this Loc is not at the
1035 // beginning of the expansion.
1036 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1037 if (!PrevFID.isInvalid()) {
1038 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1041 if (PrevEntry.isExpansion() &&
1042 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1048 *MacroBegin = ExpLoc;
1052 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1053 SourceLocation *MacroEnd) const {
1054 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1056 FileID FID = getFileID(Loc);
1057 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1058 if (isInFileID(NextLoc, FID))
1059 return false; // Does not point at the end of expansion range.
1061 bool Invalid = false;
1062 const SrcMgr::ExpansionInfo &ExpInfo =
1063 getSLocEntry(FID, &Invalid).getExpansion();
1067 if (ExpInfo.isMacroArgExpansion()) {
1068 // For macro argument expansions, check if the next FileID is part of the
1069 // same argument expansion, in which case this Loc is not at the end of the
1071 FileID NextFID = getNextFileID(FID);
1072 if (!NextFID.isInvalid()) {
1073 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1076 if (NextEntry.isExpansion() &&
1077 NextEntry.getExpansion().getExpansionLocStart() ==
1078 ExpInfo.getExpansionLocStart())
1084 *MacroEnd = ExpInfo.getExpansionLocEnd();
1088 //===----------------------------------------------------------------------===//
1089 // Queries about the code at a SourceLocation.
1090 //===----------------------------------------------------------------------===//
1092 /// getCharacterData - Return a pointer to the start of the specified location
1093 /// in the appropriate MemoryBuffer.
1094 const char *SourceManager::getCharacterData(SourceLocation SL,
1095 bool *Invalid) const {
1096 // Note that this is a hot function in the getSpelling() path, which is
1097 // heavily used by -E mode.
1098 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1100 // Note that calling 'getBuffer()' may lazily page in a source file.
1101 bool CharDataInvalid = false;
1102 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1103 if (CharDataInvalid || !Entry.isFile()) {
1107 return "<<<<INVALID BUFFER>>>>";
1109 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1110 Diag, *this, SourceLocation(), &CharDataInvalid);
1112 *Invalid = CharDataInvalid;
1113 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1116 /// getColumnNumber - Return the column # for the specified file position.
1117 /// this is significantly cheaper to compute than the line number.
1118 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1119 bool *Invalid) const {
1120 bool MyInvalid = false;
1121 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1123 *Invalid = MyInvalid;
1128 // It is okay to request a position just past the end of the buffer.
1129 if (FilePos > MemBuf->getBufferSize()) {
1135 const char *Buf = MemBuf->getBufferStart();
1136 // See if we just calculated the line number for this FilePos and can use
1137 // that to lookup the start of the line instead of searching for it.
1138 if (LastLineNoFileIDQuery == FID &&
1139 LastLineNoContentCache->SourceLineCache != nullptr &&
1140 LastLineNoResult < LastLineNoContentCache->NumLines) {
1141 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1142 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1143 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1144 if (FilePos >= LineStart && FilePos < LineEnd) {
1145 // LineEnd is the LineStart of the next line.
1146 // A line ends with separator LF or CR+LF on Windows.
1147 // FilePos might point to the last separator,
1148 // but we need a column number at most 1 + the last column.
1149 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1150 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1153 return FilePos - LineStart + 1;
1157 unsigned LineStart = FilePos;
1158 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1160 return FilePos-LineStart+1;
1163 // isInvalid - Return the result of calling loc.isInvalid(), and
1164 // if Invalid is not null, set its value to same.
1165 template<typename LocType>
1166 static bool isInvalid(LocType Loc, bool *Invalid) {
1167 bool MyInvalid = Loc.isInvalid();
1169 *Invalid = MyInvalid;
1173 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1174 bool *Invalid) const {
1175 if (isInvalid(Loc, Invalid)) return 0;
1176 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1177 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1180 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1181 bool *Invalid) const {
1182 if (isInvalid(Loc, Invalid)) return 0;
1183 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1184 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1187 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1188 bool *Invalid) const {
1189 PresumedLoc PLoc = getPresumedLoc(Loc);
1190 if (isInvalid(PLoc, Invalid)) return 0;
1191 return PLoc.getColumn();
1195 #include <emmintrin.h>
1198 static LLVM_ATTRIBUTE_NOINLINE void
1199 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1200 llvm::BumpPtrAllocator &Alloc,
1201 const SourceManager &SM, bool &Invalid);
1202 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1203 llvm::BumpPtrAllocator &Alloc,
1204 const SourceManager &SM, bool &Invalid) {
1205 // Note that calling 'getBuffer()' may lazily page in the file.
1206 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1210 // Find the file offsets of all of the *physical* source lines. This does
1211 // not look at trigraphs, escaped newlines, or anything else tricky.
1212 SmallVector<unsigned, 256> LineOffsets;
1214 // Line #1 starts at char 0.
1215 LineOffsets.push_back(0);
1217 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1218 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1221 // Skip over the contents of the line.
1222 while (Buf[I] != '\n' && Buf[I] != '\r' && Buf[I] != '\0')
1225 if (Buf[I] == '\n' || Buf[I] == '\r') {
1226 // If this is \r\n, skip both characters.
1227 if (Buf[I] == '\r' && Buf[I+1] == '\n')
1230 LineOffsets.push_back(I);
1232 // Otherwise, this is a NUL. If end of file, exit.
1233 if (Buf+I == End) break;
1238 // Copy the offsets into the FileInfo structure.
1239 FI->NumLines = LineOffsets.size();
1240 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1241 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1244 /// getLineNumber - Given a SourceLocation, return the spelling line number
1245 /// for the position indicated. This requires building and caching a table of
1246 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1247 /// about to emit a diagnostic.
1248 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1249 bool *Invalid) const {
1250 if (FID.isInvalid()) {
1256 ContentCache *Content;
1257 if (LastLineNoFileIDQuery == FID)
1258 Content = LastLineNoContentCache;
1260 bool MyInvalid = false;
1261 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1262 if (MyInvalid || !Entry.isFile()) {
1268 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1271 // If this is the first use of line information for this buffer, compute the
1272 /// SourceLineCache for it on demand.
1273 if (!Content->SourceLineCache) {
1274 bool MyInvalid = false;
1275 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1277 *Invalid = MyInvalid;
1283 // Okay, we know we have a line number table. Do a binary search to find the
1284 // line number that this character position lands on.
1285 unsigned *SourceLineCache = Content->SourceLineCache;
1286 unsigned *SourceLineCacheStart = SourceLineCache;
1287 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1289 unsigned QueriedFilePos = FilePos+1;
1291 // FIXME: I would like to be convinced that this code is worth being as
1292 // complicated as it is, binary search isn't that slow.
1294 // If it is worth being optimized, then in my opinion it could be more
1295 // performant, simpler, and more obviously correct by just "galloping" outward
1296 // from the queried file position. In fact, this could be incorporated into a
1297 // generic algorithm such as lower_bound_with_hint.
1299 // If someone gives me a test case where this matters, and I will do it! - DWD
1301 // If the previous query was to the same file, we know both the file pos from
1302 // that query and the line number returned. This allows us to narrow the
1303 // search space from the entire file to something near the match.
1304 if (LastLineNoFileIDQuery == FID) {
1305 if (QueriedFilePos >= LastLineNoFilePos) {
1306 // FIXME: Potential overflow?
1307 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1309 // The query is likely to be nearby the previous one. Here we check to
1310 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1311 // where big comment blocks and vertical whitespace eat up lines but
1312 // contribute no tokens.
1313 if (SourceLineCache+5 < SourceLineCacheEnd) {
1314 if (SourceLineCache[5] > QueriedFilePos)
1315 SourceLineCacheEnd = SourceLineCache+5;
1316 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1317 if (SourceLineCache[10] > QueriedFilePos)
1318 SourceLineCacheEnd = SourceLineCache+10;
1319 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1320 if (SourceLineCache[20] > QueriedFilePos)
1321 SourceLineCacheEnd = SourceLineCache+20;
1326 if (LastLineNoResult < Content->NumLines)
1327 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1332 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1333 unsigned LineNo = Pos-SourceLineCacheStart;
1335 LastLineNoFileIDQuery = FID;
1336 LastLineNoContentCache = Content;
1337 LastLineNoFilePos = QueriedFilePos;
1338 LastLineNoResult = LineNo;
1342 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1343 bool *Invalid) const {
1344 if (isInvalid(Loc, Invalid)) return 0;
1345 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1346 return getLineNumber(LocInfo.first, LocInfo.second);
1348 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1349 bool *Invalid) const {
1350 if (isInvalid(Loc, Invalid)) return 0;
1351 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1352 return getLineNumber(LocInfo.first, LocInfo.second);
1354 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1355 bool *Invalid) const {
1356 PresumedLoc PLoc = getPresumedLoc(Loc);
1357 if (isInvalid(PLoc, Invalid)) return 0;
1358 return PLoc.getLine();
1361 /// getFileCharacteristic - return the file characteristic of the specified
1362 /// source location, indicating whether this is a normal file, a system
1363 /// header, or an "implicit extern C" system header.
1365 /// This state can be modified with flags on GNU linemarker directives like:
1367 /// which changes all source locations in the current file after that to be
1368 /// considered to be from a system header.
1369 SrcMgr::CharacteristicKind
1370 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1371 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1372 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1373 bool Invalid = false;
1374 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1375 if (Invalid || !SEntry.isFile())
1378 const SrcMgr::FileInfo &FI = SEntry.getFile();
1380 // If there are no #line directives in this file, just return the whole-file
1382 if (!FI.hasLineDirectives())
1383 return FI.getFileCharacteristic();
1385 assert(LineTable && "Can't have linetable entries without a LineTable!");
1386 // See if there is a #line directive before the location.
1387 const LineEntry *Entry =
1388 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1390 // If this is before the first line marker, use the file characteristic.
1392 return FI.getFileCharacteristic();
1394 return Entry->FileKind;
1397 /// Return the filename or buffer identifier of the buffer the location is in.
1398 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1399 /// for normal clients.
1400 StringRef SourceManager::getBufferName(SourceLocation Loc,
1401 bool *Invalid) const {
1402 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1404 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1407 /// getPresumedLoc - This method returns the "presumed" location of a
1408 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1409 /// or GNU line marker directives. This provides a view on the data that a
1410 /// user should see in diagnostics, for example.
1412 /// Note that a presumed location is always given as the expansion point of an
1413 /// expansion location, not at the spelling location.
1414 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1415 bool UseLineDirectives) const {
1416 if (Loc.isInvalid()) return PresumedLoc();
1418 // Presumed locations are always for expansion points.
1419 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1421 bool Invalid = false;
1422 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1423 if (Invalid || !Entry.isFile())
1424 return PresumedLoc();
1426 const SrcMgr::FileInfo &FI = Entry.getFile();
1427 const SrcMgr::ContentCache *C = FI.getContentCache();
1429 // To get the source name, first consult the FileEntry (if one exists)
1430 // before the MemBuffer as this will avoid unnecessarily paging in the
1434 Filename = C->OrigEntry->getName();
1436 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1438 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1440 return PresumedLoc();
1441 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1443 return PresumedLoc();
1445 SourceLocation IncludeLoc = FI.getIncludeLoc();
1447 // If we have #line directives in this file, update and overwrite the physical
1448 // location info if appropriate.
1449 if (UseLineDirectives && FI.hasLineDirectives()) {
1450 assert(LineTable && "Can't have linetable entries without a LineTable!");
1451 // See if there is a #line directive before this. If so, get it.
1452 if (const LineEntry *Entry =
1453 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1454 // If the LineEntry indicates a filename, use it.
1455 if (Entry->FilenameID != -1)
1456 Filename = LineTable->getFilename(Entry->FilenameID);
1458 // Use the line number specified by the LineEntry. This line number may
1459 // be multiple lines down from the line entry. Add the difference in
1460 // physical line numbers from the query point and the line marker to the
1462 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1463 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1465 // Note that column numbers are not molested by line markers.
1467 // Handle virtual #include manipulation.
1468 if (Entry->IncludeOffset) {
1469 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1470 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1475 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1478 /// Returns whether the PresumedLoc for a given SourceLocation is
1479 /// in the main file.
1481 /// This computes the "presumed" location for a SourceLocation, then checks
1482 /// whether it came from a file other than the main file. This is different
1483 /// from isWrittenInMainFile() because it takes line marker directives into
1485 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1486 if (Loc.isInvalid()) return false;
1488 // Presumed locations are always for expansion points.
1489 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1491 bool Invalid = false;
1492 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1493 if (Invalid || !Entry.isFile())
1496 const SrcMgr::FileInfo &FI = Entry.getFile();
1498 // Check if there is a line directive for this location.
1499 if (FI.hasLineDirectives())
1500 if (const LineEntry *Entry =
1501 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1502 if (Entry->IncludeOffset)
1505 return FI.getIncludeLoc().isInvalid();
1508 /// The size of the SLocEntry that \p FID represents.
1509 unsigned SourceManager::getFileIDSize(FileID FID) const {
1510 bool Invalid = false;
1511 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1516 unsigned NextOffset;
1517 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1518 NextOffset = getNextLocalOffset();
1519 else if (ID+1 == -1)
1520 NextOffset = MaxLoadedOffset;
1522 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1524 return NextOffset - Entry.getOffset() - 1;
1527 //===----------------------------------------------------------------------===//
1528 // Other miscellaneous methods.
1529 //===----------------------------------------------------------------------===//
1531 /// Retrieve the inode for the given file entry, if possible.
1533 /// This routine involves a system call, and therefore should only be used
1534 /// in non-performance-critical code.
1535 static Optional<llvm::sys::fs::UniqueID>
1536 getActualFileUID(const FileEntry *File) {
1540 llvm::sys::fs::UniqueID ID;
1541 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1547 /// Get the source location for the given file:line:col triplet.
1549 /// If the source file is included multiple times, the source location will
1550 /// be based upon an arbitrary inclusion.
1551 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1553 unsigned Col) const {
1554 assert(SourceFile && "Null source file!");
1555 assert(Line && Col && "Line and column should start from 1!");
1557 FileID FirstFID = translateFile(SourceFile);
1558 return translateLineCol(FirstFID, Line, Col);
1561 /// Get the FileID for the given file.
1563 /// If the source file is included multiple times, the FileID will be the
1564 /// first inclusion.
1565 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1566 assert(SourceFile && "Null source file!");
1568 // Find the first file ID that corresponds to the given file.
1571 // First, check the main file ID, since it is common to look for a
1572 // location in the main file.
1573 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1574 Optional<StringRef> SourceFileName;
1575 if (MainFileID.isValid()) {
1576 bool Invalid = false;
1577 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1581 if (MainSLoc.isFile()) {
1582 const ContentCache *MainContentCache
1583 = MainSLoc.getFile().getContentCache();
1584 if (!MainContentCache) {
1585 // Can't do anything
1586 } else if (MainContentCache->OrigEntry == SourceFile) {
1587 FirstFID = MainFileID;
1589 // Fall back: check whether we have the same base name and inode
1590 // as the main file.
1591 const FileEntry *MainFile = MainContentCache->OrigEntry;
1592 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1593 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1594 SourceFileUID = getActualFileUID(SourceFile);
1595 if (SourceFileUID) {
1596 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1597 getActualFileUID(MainFile)) {
1598 if (*SourceFileUID == *MainFileUID) {
1599 FirstFID = MainFileID;
1600 SourceFile = MainFile;
1609 if (FirstFID.isInvalid()) {
1610 // The location we're looking for isn't in the main file; look
1611 // through all of the local source locations.
1612 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1613 bool Invalid = false;
1614 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1618 if (SLoc.isFile() &&
1619 SLoc.getFile().getContentCache() &&
1620 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1621 FirstFID = FileID::get(I);
1625 // If that still didn't help, try the modules.
1626 if (FirstFID.isInvalid()) {
1627 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1628 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1629 if (SLoc.isFile() &&
1630 SLoc.getFile().getContentCache() &&
1631 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1632 FirstFID = FileID::get(-int(I) - 2);
1639 // If we haven't found what we want yet, try again, but this time stat()
1640 // each of the files in case the files have changed since we originally
1642 if (FirstFID.isInvalid() &&
1644 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1645 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1646 bool Invalid = false;
1647 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1650 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1654 if (SLoc.isFile()) {
1655 const ContentCache *FileContentCache
1656 = SLoc.getFile().getContentCache();
1657 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1660 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1661 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1662 getActualFileUID(Entry)) {
1663 if (*SourceFileUID == *EntryUID) {
1664 FirstFID = FileID::get(I);
1678 /// Get the source location in \arg FID for the given line:col.
1679 /// Returns null location if \arg FID is not a file SLocEntry.
1680 SourceLocation SourceManager::translateLineCol(FileID FID,
1682 unsigned Col) const {
1683 // Lines are used as a one-based index into a zero-based array. This assert
1684 // checks for possible buffer underruns.
1685 assert(Line && Col && "Line and column should start from 1!");
1687 if (FID.isInvalid())
1688 return SourceLocation();
1690 bool Invalid = false;
1691 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1693 return SourceLocation();
1695 if (!Entry.isFile())
1696 return SourceLocation();
1698 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1700 if (Line == 1 && Col == 1)
1703 ContentCache *Content
1704 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1706 return SourceLocation();
1708 // If this is the first use of line information for this buffer, compute the
1709 // SourceLineCache for it on demand.
1710 if (!Content->SourceLineCache) {
1711 bool MyInvalid = false;
1712 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1714 return SourceLocation();
1717 if (Line > Content->NumLines) {
1718 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1721 return FileLoc.getLocWithOffset(Size);
1724 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1725 unsigned FilePos = Content->SourceLineCache[Line - 1];
1726 const char *Buf = Buffer->getBufferStart() + FilePos;
1727 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1729 return FileLoc.getLocWithOffset(FilePos);
1733 // Check that the given column is valid.
1734 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1736 return FileLoc.getLocWithOffset(FilePos + i);
1739 /// Compute a map of macro argument chunks to their expanded source
1740 /// location. Chunks that are not part of a macro argument will map to an
1741 /// invalid source location. e.g. if a file contains one macro argument at
1742 /// offset 100 with length 10, this is how the map will be formed:
1743 /// 0 -> SourceLocation()
1744 /// 100 -> Expanded macro arg location
1745 /// 110 -> SourceLocation()
1746 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1748 assert(FID.isValid());
1750 // Initially no macro argument chunk is present.
1751 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1756 // Stop if there are no more FileIDs to check.
1758 if (unsigned(ID) >= local_sloc_entry_size())
1760 } else if (ID == -1) {
1764 bool Invalid = false;
1765 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1768 if (Entry.isFile()) {
1769 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1770 if (IncludeLoc.isInvalid())
1772 if (!isInFileID(IncludeLoc, FID))
1773 return; // No more files/macros that may be "contained" in this file.
1775 // Skip the files/macros of the #include'd file, we only care about macros
1776 // that lexed macro arguments from our file.
1777 if (Entry.getFile().NumCreatedFIDs)
1778 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1782 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1784 if (ExpInfo.getExpansionLocStart().isFileID()) {
1785 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1786 return; // No more files/macros that may be "contained" in this file.
1789 if (!ExpInfo.isMacroArgExpansion())
1792 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1793 ExpInfo.getSpellingLoc(),
1794 SourceLocation::getMacroLoc(Entry.getOffset()),
1795 getFileIDSize(FileID::get(ID)));
1799 void SourceManager::associateFileChunkWithMacroArgExp(
1800 MacroArgsMap &MacroArgsCache,
1802 SourceLocation SpellLoc,
1803 SourceLocation ExpansionLoc,
1804 unsigned ExpansionLength) const {
1805 if (!SpellLoc.isFileID()) {
1806 unsigned SpellBeginOffs = SpellLoc.getOffset();
1807 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1809 // The spelling range for this macro argument expansion can span multiple
1810 // consecutive FileID entries. Go through each entry contained in the
1811 // spelling range and if one is itself a macro argument expansion, recurse
1812 // and associate the file chunk that it represents.
1814 FileID SpellFID; // Current FileID in the spelling range.
1815 unsigned SpellRelativeOffs;
1816 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1818 const SLocEntry &Entry = getSLocEntry(SpellFID);
1819 unsigned SpellFIDBeginOffs = Entry.getOffset();
1820 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1821 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1822 const ExpansionInfo &Info = Entry.getExpansion();
1823 if (Info.isMacroArgExpansion()) {
1824 unsigned CurrSpellLength;
1825 if (SpellFIDEndOffs < SpellEndOffs)
1826 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1828 CurrSpellLength = ExpansionLength;
1829 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1830 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1831 ExpansionLoc, CurrSpellLength);
1834 if (SpellFIDEndOffs >= SpellEndOffs)
1835 return; // we covered all FileID entries in the spelling range.
1837 // Move to the next FileID entry in the spelling range.
1838 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1839 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1840 ExpansionLength -= advance;
1842 SpellRelativeOffs = 0;
1846 assert(SpellLoc.isFileID());
1849 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1852 unsigned EndOffs = BeginOffs + ExpansionLength;
1854 // Add a new chunk for this macro argument. A previous macro argument chunk
1855 // may have been lexed again, so e.g. if the map is
1856 // 0 -> SourceLocation()
1857 // 100 -> Expanded loc #1
1858 // 110 -> SourceLocation()
1859 // and we found a new macro FileID that lexed from offset 105 with length 3,
1860 // the new map will be:
1861 // 0 -> SourceLocation()
1862 // 100 -> Expanded loc #1
1863 // 105 -> Expanded loc #2
1864 // 108 -> Expanded loc #1
1865 // 110 -> SourceLocation()
1867 // Since re-lexed macro chunks will always be the same size or less of
1868 // previous chunks, we only need to find where the ending of the new macro
1869 // chunk is mapped to and update the map with new begin/end mappings.
1871 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1873 SourceLocation EndOffsMappedLoc = I->second;
1874 MacroArgsCache[BeginOffs] = ExpansionLoc;
1875 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1878 /// If \arg Loc points inside a function macro argument, the returned
1879 /// location will be the macro location in which the argument was expanded.
1880 /// If a macro argument is used multiple times, the expanded location will
1881 /// be at the first expansion of the argument.
1885 /// Passing a file location pointing at 'foo', will yield a macro location
1886 /// where 'foo' was expanded into.
1888 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1889 if (Loc.isInvalid() || !Loc.isFileID())
1894 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1895 if (FID.isInvalid())
1898 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1899 if (!MacroArgsCache) {
1900 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1901 computeMacroArgsCache(*MacroArgsCache, FID);
1904 assert(!MacroArgsCache->empty());
1905 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1908 unsigned MacroArgBeginOffs = I->first;
1909 SourceLocation MacroArgExpandedLoc = I->second;
1910 if (MacroArgExpandedLoc.isValid())
1911 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1916 std::pair<FileID, unsigned>
1917 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1918 if (FID.isInvalid())
1919 return std::make_pair(FileID(), 0);
1921 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1923 using DecompTy = std::pair<FileID, unsigned>;
1924 auto InsertOp = IncludedLocMap.try_emplace(FID);
1925 DecompTy &DecompLoc = InsertOp.first->second;
1926 if (!InsertOp.second)
1927 return DecompLoc; // already in map.
1929 SourceLocation UpperLoc;
1930 bool Invalid = false;
1931 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1933 if (Entry.isExpansion())
1934 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1936 UpperLoc = Entry.getFile().getIncludeLoc();
1939 if (UpperLoc.isValid())
1940 DecompLoc = getDecomposedLoc(UpperLoc);
1945 /// Given a decomposed source location, move it up the include/expansion stack
1946 /// to the parent source location. If this is possible, return the decomposed
1947 /// version of the parent in Loc and return false. If Loc is the top-level
1948 /// entry, return true and don't modify it.
1949 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1950 const SourceManager &SM) {
1951 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1952 if (UpperLoc.first.isInvalid())
1953 return true; // We reached the top.
1959 /// Return the cache entry for comparing the given file IDs
1960 /// for isBeforeInTranslationUnit.
1961 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1962 FileID RFID) const {
1963 // This is a magic number for limiting the cache size. It was experimentally
1964 // derived from a small Objective-C project (where the cache filled
1965 // out to ~250 items). We can make it larger if necessary.
1966 enum { MagicCacheSize = 300 };
1967 IsBeforeInTUCacheKey Key(LFID, RFID);
1969 // If the cache size isn't too large, do a lookup and if necessary default
1970 // construct an entry. We can then return it to the caller for direct
1971 // use. When they update the value, the cache will get automatically
1973 if (IBTUCache.size() < MagicCacheSize)
1974 return IBTUCache[Key];
1976 // Otherwise, do a lookup that will not construct a new value.
1977 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
1978 if (I != IBTUCache.end())
1981 // Fall back to the overflow value.
1982 return IBTUCacheOverflow;
1985 /// Determines the order of 2 source locations in the translation unit.
1987 /// \returns true if LHS source location comes before RHS, false otherwise.
1988 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1989 SourceLocation RHS) const {
1990 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1994 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1995 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
1997 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
1998 // is a serialized one referring to a file that was removed after we loaded
2000 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2001 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2003 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2005 return InSameTU.second;
2007 // If we arrived here, the location is either in a built-ins buffer or
2008 // associated with global inline asm. PR5662 and PR22576 are examples.
2010 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2011 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2012 bool LIsBuiltins = LB == "<built-in>";
2013 bool RIsBuiltins = RB == "<built-in>";
2014 // Sort built-in before non-built-in.
2015 if (LIsBuiltins || RIsBuiltins) {
2016 if (LIsBuiltins != RIsBuiltins)
2018 // Both are in built-in buffers, but from different files. We just claim that
2019 // lower IDs come first.
2020 return LOffs.first < ROffs.first;
2022 bool LIsAsm = LB == "<inline asm>";
2023 bool RIsAsm = RB == "<inline asm>";
2024 // Sort assembler after built-ins, but before the rest.
2025 if (LIsAsm || RIsAsm) {
2026 if (LIsAsm != RIsAsm)
2028 assert(LOffs.first == ROffs.first);
2031 bool LIsScratch = LB == "<scratch space>";
2032 bool RIsScratch = RB == "<scratch space>";
2033 // Sort scratch after inline asm, but before the rest.
2034 if (LIsScratch || RIsScratch) {
2035 if (LIsScratch != RIsScratch)
2037 return LOffs.second < ROffs.second;
2039 llvm_unreachable("Unsortable locations found");
2042 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2043 std::pair<FileID, unsigned> &LOffs,
2044 std::pair<FileID, unsigned> &ROffs) const {
2045 // If the source locations are in the same file, just compare offsets.
2046 if (LOffs.first == ROffs.first)
2047 return std::make_pair(true, LOffs.second < ROffs.second);
2049 // If we are comparing a source location with multiple locations in the same
2050 // file, we get a big win by caching the result.
2051 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2052 getInBeforeInTUCache(LOffs.first, ROffs.first);
2054 // If we are comparing a source location with multiple locations in the same
2055 // file, we get a big win by caching the result.
2056 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2057 return std::make_pair(
2058 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2060 // Okay, we missed in the cache, start updating the cache for this query.
2061 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2062 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2064 // We need to find the common ancestor. The only way of doing this is to
2065 // build the complete include chain for one and then walking up the chain
2066 // of the other looking for a match.
2067 // We use a map from FileID to Offset to store the chain. Easier than writing
2068 // a custom set hash info that only depends on the first part of a pair.
2069 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2072 LChain.insert(LOffs);
2073 // We catch the case where LOffs is in a file included by ROffs and
2074 // quit early. The other way round unfortunately remains suboptimal.
2075 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2077 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2078 if (MoveUpIncludeHierarchy(ROffs, *this))
2079 break; // Met at topmost file.
2081 if (I != LChain.end())
2084 // If we exited because we found a nearest common ancestor, compare the
2085 // locations within the common file and cache them.
2086 if (LOffs.first == ROffs.first) {
2087 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2088 return std::make_pair(
2089 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2091 // Clear the lookup cache, it depends on a common location.
2092 IsBeforeInTUCache.clear();
2093 return std::make_pair(false, false);
2096 void SourceManager::PrintStats() const {
2097 llvm::errs() << "\n*** Source Manager Stats:\n";
2098 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2099 << " mem buffers mapped.\n";
2100 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2101 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2102 << " bytes of capacity), "
2103 << NextLocalOffset << "B of Sloc address space used.\n";
2104 llvm::errs() << LoadedSLocEntryTable.size()
2105 << " loaded SLocEntries allocated, "
2106 << MaxLoadedOffset - CurrentLoadedOffset
2107 << "B of Sloc address space used.\n";
2109 unsigned NumLineNumsComputed = 0;
2110 unsigned NumFileBytesMapped = 0;
2111 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2112 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2113 NumFileBytesMapped += I->second->getSizeBytesMapped();
2115 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2117 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2118 << NumLineNumsComputed << " files with line #'s computed, "
2119 << NumMacroArgsComputed << " files with macro args computed.\n";
2120 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2121 << NumBinaryProbes << " binary.\n";
2124 LLVM_DUMP_METHOD void SourceManager::dump() const {
2125 llvm::raw_ostream &out = llvm::errs();
2127 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2128 llvm::Optional<unsigned> NextStart) {
2129 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2130 << " <SourceLocation " << Entry.getOffset() << ":";
2132 out << *NextStart << ">\n";
2135 if (Entry.isFile()) {
2136 auto &FI = Entry.getFile();
2137 if (FI.NumCreatedFIDs)
2138 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2140 if (FI.getIncludeLoc().isValid())
2141 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2142 if (auto *CC = FI.getContentCache()) {
2143 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2145 if (CC->BufferOverridden)
2146 out << " contents overridden\n";
2147 if (CC->ContentsEntry != CC->OrigEntry) {
2148 out << " contents from "
2149 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2154 auto &EI = Entry.getExpansion();
2155 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2156 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2157 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2158 << EI.getExpansionLocEnd().getOffset() << ">\n";
2162 // Dump local SLocEntries.
2163 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2164 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2165 ID == NumIDs - 1 ? NextLocalOffset
2166 : LocalSLocEntryTable[ID + 1].getOffset());
2168 // Dump loaded SLocEntries.
2169 llvm::Optional<unsigned> NextStart;
2170 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2171 int ID = -(int)Index - 2;
2172 if (SLocEntryLoaded[Index]) {
2173 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2174 NextStart = LoadedSLocEntryTable[Index].getOffset();
2181 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2183 /// Return the amount of memory used by memory buffers, breaking down
2184 /// by heap-backed versus mmap'ed memory.
2185 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2186 size_t malloc_bytes = 0;
2187 size_t mmap_bytes = 0;
2189 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2190 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2191 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2192 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2193 mmap_bytes += sized_mapped;
2195 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2196 malloc_bytes += sized_mapped;
2200 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2203 size_t SourceManager::getDataStructureSizes() const {
2204 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2205 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2206 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2207 + llvm::capacity_in_bytes(SLocEntryLoaded)
2208 + llvm::capacity_in_bytes(FileInfos);
2210 if (OverriddenFilesInfo)
2211 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2216 SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2217 StringRef Content) {
2218 // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2220 IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2221 new llvm::vfs::InMemoryFileSystem);
2222 InMemoryFileSystem->addFile(
2224 llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2225 /*RequiresNullTerminator=*/false));
2226 // This is passed to `SM` as reference, so the pointer has to be referenced
2227 // in `Environment` so that `FileMgr` can out-live this function scope.
2229 llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2230 // This is passed to `SM` as reference, so the pointer has to be referenced
2231 // by `Environment` due to the same reason above.
2232 Diagnostics = llvm::make_unique<DiagnosticsEngine>(
2233 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2234 new DiagnosticOptions);
2235 SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2236 FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
2237 SourceLocation(), clang::SrcMgr::C_User);
2238 assert(ID.isValid());
2239 SourceMgr->setMainFileID(ID);