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("\x00\x00\xFE\xFF", "UTF-32 (BE)")
174 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
175 .StartsWith("\x2B\x2F\x76", "UTF-7")
176 .StartsWith("\xF7\x64\x4C", "UTF-1")
177 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
178 .StartsWith("\x0E\xFE\xFF", "SDSU")
179 .StartsWith("\xFB\xEE\x28", "BOCU-1")
180 .StartsWith("\x84\x31\x95\x33", "GB-18030")
184 Diag.Report(Loc, diag::err_unsupported_bom)
185 << InvalidBOM << ContentsEntry->getName();
186 Buffer.setInt(Buffer.getInt() | InvalidFlag);
190 *Invalid = isBufferInvalid();
192 return Buffer.getPointer();
195 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
197 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
199 FilenamesByID.push_back(&*IterBool.first);
200 return IterBool.first->second;
203 /// Add a line note to the line table that indicates that there is a \#line or
204 /// GNU line marker at the specified FID/Offset location which changes the
205 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
206 /// change the presumed \#include stack. If it is 1, this is a file entry, if
207 /// it is 2 then this is a file exit. FileKind specifies whether this is a
208 /// system header or extern C system header.
209 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
210 int FilenameID, unsigned EntryExit,
211 SrcMgr::CharacteristicKind FileKind) {
212 std::vector<LineEntry> &Entries = LineEntries[FID];
214 // An unspecified FilenameID means use the last filename if available, or the
215 // main source file otherwise.
216 if (FilenameID == -1 && !Entries.empty())
217 FilenameID = Entries.back().FilenameID;
219 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
220 "Adding line entries out of order!");
222 unsigned IncludeOffset = 0;
223 if (EntryExit == 0) { // No #include stack change.
224 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
225 } else if (EntryExit == 1) {
226 IncludeOffset = Offset-1;
227 } else if (EntryExit == 2) {
228 assert(!Entries.empty() && Entries.back().IncludeOffset &&
229 "PPDirectives should have caught case when popping empty include stack");
231 // Get the include loc of the last entries' include loc as our include loc.
233 if (const LineEntry *PrevEntry =
234 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
235 IncludeOffset = PrevEntry->IncludeOffset;
238 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
242 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
243 /// it. If there is no line entry before Offset in FID, return null.
244 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
246 const std::vector<LineEntry> &Entries = LineEntries[FID];
247 assert(!Entries.empty() && "No #line entries for this FID after all!");
249 // It is very common for the query to be after the last #line, check this
251 if (Entries.back().FileOffset <= Offset)
252 return &Entries.back();
254 // Do a binary search to find the maximal element that is still before Offset.
255 std::vector<LineEntry>::const_iterator I =
256 std::upper_bound(Entries.begin(), Entries.end(), Offset);
257 if (I == Entries.begin()) return nullptr;
261 /// \brief Add a new line entry that has already been encoded into
262 /// the internal representation of the line table.
263 void LineTableInfo::AddEntry(FileID FID,
264 const std::vector<LineEntry> &Entries) {
265 LineEntries[FID] = Entries;
268 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
269 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
270 return getLineTable().getLineTableFilenameID(Name);
273 /// AddLineNote - Add a line note to the line table for the FileID and offset
274 /// specified by Loc. If FilenameID is -1, it is considered to be
276 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
277 int FilenameID, bool IsFileEntry,
279 SrcMgr::CharacteristicKind FileKind) {
280 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
282 bool Invalid = false;
283 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
284 if (!Entry.isFile() || Invalid)
287 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
289 // Remember that this file has #line directives now if it doesn't already.
290 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
292 (void) getLineTable();
294 unsigned EntryExit = 0;
300 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
301 EntryExit, FileKind);
304 LineTableInfo &SourceManager::getLineTable() {
306 LineTable = new LineTableInfo();
310 //===----------------------------------------------------------------------===//
311 // Private 'Create' methods.
312 //===----------------------------------------------------------------------===//
314 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
315 bool UserFilesAreVolatile)
316 : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
318 Diag.setSourceManager(this);
321 SourceManager::~SourceManager() {
324 // Delete FileEntry objects corresponding to content caches. Since the actual
325 // content cache objects are bump pointer allocated, we just have to run the
326 // dtors, but we call the deallocate method for completeness.
327 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
328 if (MemBufferInfos[i]) {
329 MemBufferInfos[i]->~ContentCache();
330 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
333 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
334 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
336 I->second->~ContentCache();
337 ContentCacheAlloc.Deallocate(I->second);
342 void SourceManager::clearIDTables() {
343 MainFileID = FileID();
344 LocalSLocEntryTable.clear();
345 LoadedSLocEntryTable.clear();
346 SLocEntryLoaded.clear();
347 LastLineNoFileIDQuery = FileID();
348 LastLineNoContentCache = nullptr;
349 LastFileIDLookup = FileID();
354 // Use up FileID #0 as an invalid expansion.
356 CurrentLoadedOffset = MaxLoadedOffset;
357 createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
360 void SourceManager::initializeForReplay(const SourceManager &Old) {
361 assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
363 auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
364 auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
365 Clone->OrigEntry = Cache->OrigEntry;
366 Clone->ContentsEntry = Cache->ContentsEntry;
367 Clone->BufferOverridden = Cache->BufferOverridden;
368 Clone->IsSystemFile = Cache->IsSystemFile;
369 Clone->IsTransient = Cache->IsTransient;
370 Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
374 // Ensure all SLocEntries are loaded from the external source.
375 for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
376 if (!Old.SLocEntryLoaded[I])
377 Old.loadSLocEntry(I, nullptr);
379 // Inherit any content cache data from the old source manager.
380 for (auto &FileInfo : Old.FileInfos) {
381 SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
384 Slot = CloneContentCache(FileInfo.second);
388 /// getOrCreateContentCache - Create or return a cached ContentCache for the
391 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
393 assert(FileEnt && "Didn't specify a file entry to use?");
395 // Do we already have information about this file?
396 ContentCache *&Entry = FileInfos[FileEnt];
397 if (Entry) return Entry;
399 // Nope, create a new Cache entry.
400 Entry = ContentCacheAlloc.Allocate<ContentCache>();
402 if (OverriddenFilesInfo) {
403 // If the file contents are overridden with contents from another file,
404 // pass that file to ContentCache.
405 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
406 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
407 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
408 new (Entry) ContentCache(FileEnt);
410 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
414 new (Entry) ContentCache(FileEnt);
417 Entry->IsSystemFile = isSystemFile;
418 Entry->IsTransient = FilesAreTransient;
423 /// Create a new ContentCache for the specified memory buffer.
424 /// This does no caching.
426 SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer,
428 // Add a new ContentCache to the MemBufferInfos list and return it.
429 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
430 new (Entry) ContentCache();
431 MemBufferInfos.push_back(Entry);
432 Entry->replaceBuffer(Buffer, DoNotFree);
436 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
437 bool *Invalid) const {
438 assert(!SLocEntryLoaded[Index]);
439 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
442 // If the file of the SLocEntry changed we could still have loaded it.
443 if (!SLocEntryLoaded[Index]) {
444 // Try to recover; create a SLocEntry so the rest of clang can handle it.
445 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
446 FileInfo::get(SourceLocation(),
447 getFakeContentCacheForRecovery(),
452 return LoadedSLocEntryTable[Index];
455 std::pair<int, unsigned>
456 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
457 unsigned TotalSize) {
458 assert(ExternalSLocEntries && "Don't have an external sloc source");
459 // Make sure we're not about to run out of source locations.
460 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
461 return std::make_pair(0, 0);
462 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
463 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
464 CurrentLoadedOffset -= TotalSize;
465 int ID = LoadedSLocEntryTable.size();
466 return std::make_pair(-ID - 1, CurrentLoadedOffset);
469 /// \brief As part of recovering from missing or changed content, produce a
470 /// fake, non-empty buffer.
471 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
472 if (!FakeBufferForRecovery)
473 FakeBufferForRecovery =
474 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
476 return FakeBufferForRecovery.get();
479 /// \brief As part of recovering from missing or changed content, produce a
480 /// fake content cache.
481 const SrcMgr::ContentCache *
482 SourceManager::getFakeContentCacheForRecovery() const {
483 if (!FakeContentCacheForRecovery) {
484 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
485 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
488 return FakeContentCacheForRecovery.get();
491 /// \brief Returns the previous in-order FileID or an invalid FileID if there
492 /// is no previous one.
493 FileID SourceManager::getPreviousFileID(FileID FID) const {
504 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
508 return FileID::get(ID-1);
511 /// \brief Returns the next in-order FileID or an invalid FileID if there is
513 FileID SourceManager::getNextFileID(FileID FID) const {
519 if (unsigned(ID+1) >= local_sloc_entry_size())
521 } else if (ID+1 >= -1) {
525 return FileID::get(ID+1);
528 //===----------------------------------------------------------------------===//
529 // Methods to create new FileID's and macro expansions.
530 //===----------------------------------------------------------------------===//
532 /// createFileID - Create a new FileID for the specified ContentCache and
533 /// include position. This works regardless of whether the ContentCache
534 /// corresponds to a file or some other input source.
535 FileID SourceManager::createFileID(const ContentCache *File,
536 SourceLocation IncludePos,
537 SrcMgr::CharacteristicKind FileCharacter,
538 int LoadedID, unsigned LoadedOffset) {
540 assert(LoadedID != -1 && "Loading sentinel FileID");
541 unsigned Index = unsigned(-LoadedID) - 2;
542 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
543 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
544 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
545 FileInfo::get(IncludePos, File, FileCharacter));
546 SLocEntryLoaded[Index] = true;
547 return FileID::get(LoadedID);
549 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
550 FileInfo::get(IncludePos, File,
552 unsigned FileSize = File->getSize();
553 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
554 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
555 "Ran out of source locations!");
556 // We do a +1 here because we want a SourceLocation that means "the end of the
557 // file", e.g. for the "no newline at the end of the file" diagnostic.
558 NextLocalOffset += FileSize + 1;
560 // Set LastFileIDLookup to the newly created file. The next getFileID call is
561 // almost guaranteed to be from that file.
562 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
563 return LastFileIDLookup = FID;
567 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
568 SourceLocation ExpansionLoc,
569 unsigned TokLength) {
570 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
572 return createExpansionLocImpl(Info, TokLength);
576 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
577 SourceLocation ExpansionLocStart,
578 SourceLocation ExpansionLocEnd,
581 unsigned LoadedOffset) {
582 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
584 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
588 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
591 unsigned LoadedOffset) {
593 assert(LoadedID != -1 && "Loading sentinel FileID");
594 unsigned Index = unsigned(-LoadedID) - 2;
595 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
596 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
597 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
598 SLocEntryLoaded[Index] = true;
599 return SourceLocation::getMacroLoc(LoadedOffset);
601 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
602 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
603 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
604 "Ran out of source locations!");
605 // See createFileID for that +1.
606 NextLocalOffset += TokLength + 1;
607 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
610 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
612 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
613 assert(IR && "getOrCreateContentCache() cannot return NULL");
614 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
617 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
618 llvm::MemoryBuffer *Buffer,
620 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
621 assert(IR && "getOrCreateContentCache() cannot return NULL");
623 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
624 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
626 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
629 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
630 const FileEntry *NewFile) {
631 assert(SourceFile->getSize() == NewFile->getSize() &&
632 "Different sizes, use the FileManager to create a virtual file with "
634 assert(FileInfos.count(SourceFile) == 0 &&
635 "This function should be called at the initialization stage, before "
636 "any parsing occurs.");
637 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
640 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
641 if (!isFileOverridden(File))
644 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
645 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
646 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
648 assert(OverriddenFilesInfo);
649 OverriddenFilesInfo->OverriddenFiles.erase(File);
650 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
653 void SourceManager::setFileIsTransient(const FileEntry *File) {
654 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
655 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
658 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
659 bool MyInvalid = false;
660 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
661 if (!SLoc.isFile() || MyInvalid) {
664 return "<<<<<INVALID SOURCE LOCATION>>>>>";
667 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
668 Diag, *this, SourceLocation(), &MyInvalid);
670 *Invalid = MyInvalid;
673 return "<<<<<INVALID SOURCE LOCATION>>>>>";
675 return Buf->getBuffer();
678 //===----------------------------------------------------------------------===//
679 // SourceLocation manipulation methods.
680 //===----------------------------------------------------------------------===//
682 /// \brief Return the FileID for a SourceLocation.
684 /// This is the cache-miss path of getFileID. Not as hot as that function, but
685 /// still very important. It is responsible for finding the entry in the
686 /// SLocEntry tables that contains the specified location.
687 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
689 return FileID::get(0);
691 // Now it is time to search for the correct file. See where the SLocOffset
692 // sits in the global view and consult local or loaded buffers for it.
693 if (SLocOffset < NextLocalOffset)
694 return getFileIDLocal(SLocOffset);
695 return getFileIDLoaded(SLocOffset);
698 /// \brief Return the FileID for a SourceLocation with a low offset.
700 /// This function knows that the SourceLocation is in a local buffer, not a
702 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
703 assert(SLocOffset < NextLocalOffset && "Bad function choice");
705 // After the first and second level caches, I see two common sorts of
706 // behavior: 1) a lot of searched FileID's are "near" the cached file
707 // location or are "near" the cached expansion location. 2) others are just
708 // completely random and may be a very long way away.
710 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
711 // then we fall back to a less cache efficient, but more scalable, binary
712 // search to find the location.
714 // See if this is near the file point - worst case we start scanning from the
715 // most newly created FileID.
716 const SrcMgr::SLocEntry *I;
718 if (LastFileIDLookup.ID < 0 ||
719 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
720 // Neither loc prunes our search.
721 I = LocalSLocEntryTable.end();
723 // Perhaps it is near the file point.
724 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
727 // Find the FileID that contains this. "I" is an iterator that points to a
728 // FileID whose offset is known to be larger than SLocOffset.
729 unsigned NumProbes = 0;
732 if (I->getOffset() <= SLocOffset) {
733 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
735 // If this isn't an expansion, remember it. We have good locality across
737 if (!I->isExpansion())
738 LastFileIDLookup = Res;
739 NumLinearScans += NumProbes+1;
742 if (++NumProbes == 8)
746 // Convert "I" back into an index. We know that it is an entry whose index is
747 // larger than the offset we are looking for.
748 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
749 // LessIndex - This is the lower bound of the range that we're searching.
750 // We know that the offset corresponding to the FileID is is less than
752 unsigned LessIndex = 0;
755 bool Invalid = false;
756 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
757 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
759 return FileID::get(0);
763 // If the offset of the midpoint is too large, chop the high side of the
764 // range to the midpoint.
765 if (MidOffset > SLocOffset) {
766 GreaterIndex = MiddleIndex;
770 // If the middle index contains the value, succeed and return.
771 // FIXME: This could be made faster by using a function that's aware of
772 // being in the local area.
773 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
774 FileID Res = FileID::get(MiddleIndex);
776 // If this isn't a macro expansion, remember it. We have good locality
777 // across FileID lookups.
778 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
779 LastFileIDLookup = Res;
780 NumBinaryProbes += NumProbes;
784 // Otherwise, move the low-side up to the middle index.
785 LessIndex = MiddleIndex;
789 /// \brief Return the FileID for a SourceLocation with a high offset.
791 /// This function knows that the SourceLocation is in a loaded buffer, not a
793 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
794 // Sanity checking, otherwise a bug may lead to hanging in release build.
795 if (SLocOffset < CurrentLoadedOffset) {
796 assert(0 && "Invalid SLocOffset or bad function choice");
800 // Essentially the same as the local case, but the loaded array is sorted
801 // in the other direction.
803 // First do a linear scan from the last lookup position, if possible.
805 int LastID = LastFileIDLookup.ID;
806 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
809 I = (-LastID - 2) + 1;
812 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
813 // Make sure the entry is loaded!
814 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
815 if (E.getOffset() <= SLocOffset) {
816 FileID Res = FileID::get(-int(I) - 2);
818 if (!E.isExpansion())
819 LastFileIDLookup = Res;
820 NumLinearScans += NumProbes + 1;
825 // Linear scan failed. Do the binary search. Note the reverse sorting of the
826 // table: GreaterIndex is the one where the offset is greater, which is
827 // actually a lower index!
828 unsigned GreaterIndex = I;
829 unsigned LessIndex = LoadedSLocEntryTable.size();
833 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
834 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
835 if (E.getOffset() == 0)
836 return FileID(); // invalid entry.
840 if (E.getOffset() > SLocOffset) {
841 // Sanity checking, otherwise a bug may lead to hanging in release build.
842 if (GreaterIndex == MiddleIndex) {
843 assert(0 && "binary search missed the entry");
846 GreaterIndex = MiddleIndex;
850 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
851 FileID Res = FileID::get(-int(MiddleIndex) - 2);
852 if (!E.isExpansion())
853 LastFileIDLookup = Res;
854 NumBinaryProbes += NumProbes;
858 // Sanity checking, otherwise a bug may lead to hanging in release build.
859 if (LessIndex == MiddleIndex) {
860 assert(0 && "binary search missed the entry");
863 LessIndex = MiddleIndex;
867 SourceLocation SourceManager::
868 getExpansionLocSlowCase(SourceLocation Loc) const {
870 // Note: If Loc indicates an offset into a token that came from a macro
871 // expansion (e.g. the 5th character of the token) we do not want to add
872 // this offset when going to the expansion location. The expansion
873 // location is the macro invocation, which the offset has nothing to do
874 // with. This is unlike when we get the spelling loc, because the offset
875 // directly correspond to the token whose spelling we're inspecting.
876 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
877 } while (!Loc.isFileID());
882 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
884 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
885 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
886 Loc = Loc.getLocWithOffset(LocInfo.second);
887 } while (!Loc.isFileID());
891 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
893 if (isMacroArgExpansion(Loc))
894 Loc = getImmediateSpellingLoc(Loc);
896 Loc = getImmediateExpansionRange(Loc).first;
897 } while (!Loc.isFileID());
902 std::pair<FileID, unsigned>
903 SourceManager::getDecomposedExpansionLocSlowCase(
904 const SrcMgr::SLocEntry *E) const {
905 // If this is an expansion record, walk through all the expansion points.
910 Loc = E->getExpansion().getExpansionLocStart();
912 FID = getFileID(Loc);
913 E = &getSLocEntry(FID);
914 Offset = Loc.getOffset()-E->getOffset();
915 } while (!Loc.isFileID());
917 return std::make_pair(FID, Offset);
920 std::pair<FileID, unsigned>
921 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
922 unsigned Offset) const {
923 // If this is an expansion record, walk through all the expansion points.
927 Loc = E->getExpansion().getSpellingLoc();
928 Loc = Loc.getLocWithOffset(Offset);
930 FID = getFileID(Loc);
931 E = &getSLocEntry(FID);
932 Offset = Loc.getOffset()-E->getOffset();
933 } while (!Loc.isFileID());
935 return std::make_pair(FID, Offset);
938 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
939 /// spelling location referenced by the ID. This is the first level down
940 /// towards the place where the characters that make up the lexed token can be
941 /// found. This should not generally be used by clients.
942 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
943 if (Loc.isFileID()) return Loc;
944 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
945 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
946 return Loc.getLocWithOffset(LocInfo.second);
949 /// getImmediateExpansionRange - Loc is required to be an expansion location.
950 /// Return the start/end of the expansion information.
951 std::pair<SourceLocation,SourceLocation>
952 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
953 assert(Loc.isMacroID() && "Not a macro expansion loc!");
954 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
955 return Expansion.getExpansionLocRange();
958 /// getExpansionRange - Given a SourceLocation object, return the range of
959 /// tokens covered by the expansion in the ultimate file.
960 std::pair<SourceLocation,SourceLocation>
961 SourceManager::getExpansionRange(SourceLocation Loc) const {
962 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
964 std::pair<SourceLocation,SourceLocation> Res =
965 getImmediateExpansionRange(Loc);
967 // Fully resolve the start and end locations to their ultimate expansion
969 while (!Res.first.isFileID())
970 Res.first = getImmediateExpansionRange(Res.first).first;
971 while (!Res.second.isFileID())
972 Res.second = getImmediateExpansionRange(Res.second).second;
976 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
977 SourceLocation *StartLoc) const {
978 if (!Loc.isMacroID()) return false;
980 FileID FID = getFileID(Loc);
981 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
982 if (!Expansion.isMacroArgExpansion()) return false;
985 *StartLoc = Expansion.getExpansionLocStart();
989 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
990 if (!Loc.isMacroID()) return false;
992 FileID FID = getFileID(Loc);
993 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
994 return Expansion.isMacroBodyExpansion();
997 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
998 SourceLocation *MacroBegin) const {
999 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1001 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1002 if (DecompLoc.second > 0)
1003 return false; // Does not point at the start of expansion range.
1005 bool Invalid = false;
1006 const SrcMgr::ExpansionInfo &ExpInfo =
1007 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1010 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1012 if (ExpInfo.isMacroArgExpansion()) {
1013 // For macro argument expansions, check if the previous FileID is part of
1014 // the same argument expansion, in which case this Loc is not at the
1015 // beginning of the expansion.
1016 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1017 if (!PrevFID.isInvalid()) {
1018 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1021 if (PrevEntry.isExpansion() &&
1022 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1028 *MacroBegin = ExpLoc;
1032 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1033 SourceLocation *MacroEnd) const {
1034 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1036 FileID FID = getFileID(Loc);
1037 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1038 if (isInFileID(NextLoc, FID))
1039 return false; // Does not point at the end of expansion range.
1041 bool Invalid = false;
1042 const SrcMgr::ExpansionInfo &ExpInfo =
1043 getSLocEntry(FID, &Invalid).getExpansion();
1047 if (ExpInfo.isMacroArgExpansion()) {
1048 // For macro argument expansions, check if the next FileID is part of the
1049 // same argument expansion, in which case this Loc is not at the end of the
1051 FileID NextFID = getNextFileID(FID);
1052 if (!NextFID.isInvalid()) {
1053 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1056 if (NextEntry.isExpansion() &&
1057 NextEntry.getExpansion().getExpansionLocStart() ==
1058 ExpInfo.getExpansionLocStart())
1064 *MacroEnd = ExpInfo.getExpansionLocEnd();
1068 //===----------------------------------------------------------------------===//
1069 // Queries about the code at a SourceLocation.
1070 //===----------------------------------------------------------------------===//
1072 /// getCharacterData - Return a pointer to the start of the specified location
1073 /// in the appropriate MemoryBuffer.
1074 const char *SourceManager::getCharacterData(SourceLocation SL,
1075 bool *Invalid) const {
1076 // Note that this is a hot function in the getSpelling() path, which is
1077 // heavily used by -E mode.
1078 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1080 // Note that calling 'getBuffer()' may lazily page in a source file.
1081 bool CharDataInvalid = false;
1082 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1083 if (CharDataInvalid || !Entry.isFile()) {
1087 return "<<<<INVALID BUFFER>>>>";
1089 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1090 Diag, *this, SourceLocation(), &CharDataInvalid);
1092 *Invalid = CharDataInvalid;
1093 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1096 /// getColumnNumber - Return the column # for the specified file position.
1097 /// this is significantly cheaper to compute than the line number.
1098 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1099 bool *Invalid) const {
1100 bool MyInvalid = false;
1101 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1103 *Invalid = MyInvalid;
1108 // It is okay to request a position just past the end of the buffer.
1109 if (FilePos > MemBuf->getBufferSize()) {
1115 const char *Buf = MemBuf->getBufferStart();
1116 // See if we just calculated the line number for this FilePos and can use
1117 // that to lookup the start of the line instead of searching for it.
1118 if (LastLineNoFileIDQuery == FID &&
1119 LastLineNoContentCache->SourceLineCache != nullptr &&
1120 LastLineNoResult < LastLineNoContentCache->NumLines) {
1121 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1122 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1123 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1124 if (FilePos >= LineStart && FilePos < LineEnd) {
1125 // LineEnd is the LineStart of the next line.
1126 // A line ends with separator LF or CR+LF on Windows.
1127 // FilePos might point to the last separator,
1128 // but we need a column number at most 1 + the last column.
1129 if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1130 if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1133 return FilePos - LineStart + 1;
1137 unsigned LineStart = FilePos;
1138 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1140 return FilePos-LineStart+1;
1143 // isInvalid - Return the result of calling loc.isInvalid(), and
1144 // if Invalid is not null, set its value to same.
1145 template<typename LocType>
1146 static bool isInvalid(LocType Loc, bool *Invalid) {
1147 bool MyInvalid = Loc.isInvalid();
1149 *Invalid = MyInvalid;
1153 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1154 bool *Invalid) const {
1155 if (isInvalid(Loc, Invalid)) return 0;
1156 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1157 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1160 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1161 bool *Invalid) const {
1162 if (isInvalid(Loc, Invalid)) return 0;
1163 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1164 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1167 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1168 bool *Invalid) const {
1169 PresumedLoc PLoc = getPresumedLoc(Loc);
1170 if (isInvalid(PLoc, Invalid)) return 0;
1171 return PLoc.getColumn();
1175 #include <emmintrin.h>
1178 static LLVM_ATTRIBUTE_NOINLINE void
1179 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1180 llvm::BumpPtrAllocator &Alloc,
1181 const SourceManager &SM, bool &Invalid);
1182 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1183 llvm::BumpPtrAllocator &Alloc,
1184 const SourceManager &SM, bool &Invalid) {
1185 // Note that calling 'getBuffer()' may lazily page in the file.
1186 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1190 // Find the file offsets of all of the *physical* source lines. This does
1191 // not look at trigraphs, escaped newlines, or anything else tricky.
1192 SmallVector<unsigned, 256> LineOffsets;
1194 // Line #1 starts at char 0.
1195 LineOffsets.push_back(0);
1197 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1198 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1201 // Skip over the contents of the line.
1202 const unsigned char *NextBuf = (const unsigned char *)Buf;
1205 // Try to skip to the next newline using SSE instructions. This is very
1206 // performance sensitive for programs with lots of diagnostics and in -E
1208 __m128i CRs = _mm_set1_epi8('\r');
1209 __m128i LFs = _mm_set1_epi8('\n');
1211 // First fix up the alignment to 16 bytes.
1212 while (((uintptr_t)NextBuf & 0xF) != 0) {
1213 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1214 goto FoundSpecialChar;
1218 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1219 while (NextBuf+16 <= End) {
1220 const __m128i Chunk = *(const __m128i*)NextBuf;
1221 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1222 _mm_cmpeq_epi8(Chunk, LFs));
1223 unsigned Mask = _mm_movemask_epi8(Cmp);
1225 // If we found a newline, adjust the pointer and jump to the handling code.
1227 NextBuf += llvm::countTrailingZeros(Mask);
1228 goto FoundSpecialChar;
1234 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1240 Offs += NextBuf-Buf;
1243 if (Buf[0] == '\n' || Buf[0] == '\r') {
1244 // If this is \n\r or \r\n, skip both characters.
1245 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1251 LineOffsets.push_back(Offs);
1253 // Otherwise, this is a null. If end of file, exit.
1254 if (Buf == End) break;
1255 // Otherwise, skip the null.
1261 // Copy the offsets into the FileInfo structure.
1262 FI->NumLines = LineOffsets.size();
1263 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1264 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1267 /// getLineNumber - Given a SourceLocation, return the spelling line number
1268 /// for the position indicated. This requires building and caching a table of
1269 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1270 /// about to emit a diagnostic.
1271 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1272 bool *Invalid) const {
1273 if (FID.isInvalid()) {
1279 ContentCache *Content;
1280 if (LastLineNoFileIDQuery == FID)
1281 Content = LastLineNoContentCache;
1283 bool MyInvalid = false;
1284 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1285 if (MyInvalid || !Entry.isFile()) {
1291 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1294 // If this is the first use of line information for this buffer, compute the
1295 /// SourceLineCache for it on demand.
1296 if (!Content->SourceLineCache) {
1297 bool MyInvalid = false;
1298 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1300 *Invalid = MyInvalid;
1306 // Okay, we know we have a line number table. Do a binary search to find the
1307 // line number that this character position lands on.
1308 unsigned *SourceLineCache = Content->SourceLineCache;
1309 unsigned *SourceLineCacheStart = SourceLineCache;
1310 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1312 unsigned QueriedFilePos = FilePos+1;
1314 // FIXME: I would like to be convinced that this code is worth being as
1315 // complicated as it is, binary search isn't that slow.
1317 // If it is worth being optimized, then in my opinion it could be more
1318 // performant, simpler, and more obviously correct by just "galloping" outward
1319 // from the queried file position. In fact, this could be incorporated into a
1320 // generic algorithm such as lower_bound_with_hint.
1322 // If someone gives me a test case where this matters, and I will do it! - DWD
1324 // If the previous query was to the same file, we know both the file pos from
1325 // that query and the line number returned. This allows us to narrow the
1326 // search space from the entire file to something near the match.
1327 if (LastLineNoFileIDQuery == FID) {
1328 if (QueriedFilePos >= LastLineNoFilePos) {
1329 // FIXME: Potential overflow?
1330 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1332 // The query is likely to be nearby the previous one. Here we check to
1333 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1334 // where big comment blocks and vertical whitespace eat up lines but
1335 // contribute no tokens.
1336 if (SourceLineCache+5 < SourceLineCacheEnd) {
1337 if (SourceLineCache[5] > QueriedFilePos)
1338 SourceLineCacheEnd = SourceLineCache+5;
1339 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1340 if (SourceLineCache[10] > QueriedFilePos)
1341 SourceLineCacheEnd = SourceLineCache+10;
1342 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1343 if (SourceLineCache[20] > QueriedFilePos)
1344 SourceLineCacheEnd = SourceLineCache+20;
1349 if (LastLineNoResult < Content->NumLines)
1350 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1355 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1356 unsigned LineNo = Pos-SourceLineCacheStart;
1358 LastLineNoFileIDQuery = FID;
1359 LastLineNoContentCache = Content;
1360 LastLineNoFilePos = QueriedFilePos;
1361 LastLineNoResult = LineNo;
1365 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1366 bool *Invalid) const {
1367 if (isInvalid(Loc, Invalid)) return 0;
1368 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1369 return getLineNumber(LocInfo.first, LocInfo.second);
1371 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1372 bool *Invalid) const {
1373 if (isInvalid(Loc, Invalid)) return 0;
1374 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1375 return getLineNumber(LocInfo.first, LocInfo.second);
1377 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1378 bool *Invalid) const {
1379 PresumedLoc PLoc = getPresumedLoc(Loc);
1380 if (isInvalid(PLoc, Invalid)) return 0;
1381 return PLoc.getLine();
1384 /// getFileCharacteristic - return the file characteristic of the specified
1385 /// source location, indicating whether this is a normal file, a system
1386 /// header, or an "implicit extern C" system header.
1388 /// This state can be modified with flags on GNU linemarker directives like:
1390 /// which changes all source locations in the current file after that to be
1391 /// considered to be from a system header.
1392 SrcMgr::CharacteristicKind
1393 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1394 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1395 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1396 bool Invalid = false;
1397 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1398 if (Invalid || !SEntry.isFile())
1401 const SrcMgr::FileInfo &FI = SEntry.getFile();
1403 // If there are no #line directives in this file, just return the whole-file
1405 if (!FI.hasLineDirectives())
1406 return FI.getFileCharacteristic();
1408 assert(LineTable && "Can't have linetable entries without a LineTable!");
1409 // See if there is a #line directive before the location.
1410 const LineEntry *Entry =
1411 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1413 // If this is before the first line marker, use the file characteristic.
1415 return FI.getFileCharacteristic();
1417 return Entry->FileKind;
1420 /// Return the filename or buffer identifier of the buffer the location is in.
1421 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1422 /// for normal clients.
1423 StringRef SourceManager::getBufferName(SourceLocation Loc,
1424 bool *Invalid) const {
1425 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1427 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1430 /// getPresumedLoc - This method returns the "presumed" location of a
1431 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1432 /// or GNU line marker directives. This provides a view on the data that a
1433 /// user should see in diagnostics, for example.
1435 /// Note that a presumed location is always given as the expansion point of an
1436 /// expansion location, not at the spelling location.
1437 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1438 bool UseLineDirectives) const {
1439 if (Loc.isInvalid()) return PresumedLoc();
1441 // Presumed locations are always for expansion points.
1442 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1444 bool Invalid = false;
1445 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1446 if (Invalid || !Entry.isFile())
1447 return PresumedLoc();
1449 const SrcMgr::FileInfo &FI = Entry.getFile();
1450 const SrcMgr::ContentCache *C = FI.getContentCache();
1452 // To get the source name, first consult the FileEntry (if one exists)
1453 // before the MemBuffer as this will avoid unnecessarily paging in the
1457 Filename = C->OrigEntry->getName();
1459 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1461 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1463 return PresumedLoc();
1464 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1466 return PresumedLoc();
1468 SourceLocation IncludeLoc = FI.getIncludeLoc();
1470 // If we have #line directives in this file, update and overwrite the physical
1471 // location info if appropriate.
1472 if (UseLineDirectives && FI.hasLineDirectives()) {
1473 assert(LineTable && "Can't have linetable entries without a LineTable!");
1474 // See if there is a #line directive before this. If so, get it.
1475 if (const LineEntry *Entry =
1476 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1477 // If the LineEntry indicates a filename, use it.
1478 if (Entry->FilenameID != -1)
1479 Filename = LineTable->getFilename(Entry->FilenameID);
1481 // Use the line number specified by the LineEntry. This line number may
1482 // be multiple lines down from the line entry. Add the difference in
1483 // physical line numbers from the query point and the line marker to the
1485 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1486 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1488 // Note that column numbers are not molested by line markers.
1490 // Handle virtual #include manipulation.
1491 if (Entry->IncludeOffset) {
1492 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1493 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1498 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1501 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1502 /// in the main file.
1504 /// This computes the "presumed" location for a SourceLocation, then checks
1505 /// whether it came from a file other than the main file. This is different
1506 /// from isWrittenInMainFile() because it takes line marker directives into
1508 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1509 if (Loc.isInvalid()) return false;
1511 // Presumed locations are always for expansion points.
1512 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1514 bool Invalid = false;
1515 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1516 if (Invalid || !Entry.isFile())
1519 const SrcMgr::FileInfo &FI = Entry.getFile();
1521 // Check if there is a line directive for this location.
1522 if (FI.hasLineDirectives())
1523 if (const LineEntry *Entry =
1524 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1525 if (Entry->IncludeOffset)
1528 return FI.getIncludeLoc().isInvalid();
1531 /// \brief The size of the SLocEntry that \p FID represents.
1532 unsigned SourceManager::getFileIDSize(FileID FID) const {
1533 bool Invalid = false;
1534 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1539 unsigned NextOffset;
1540 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1541 NextOffset = getNextLocalOffset();
1542 else if (ID+1 == -1)
1543 NextOffset = MaxLoadedOffset;
1545 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1547 return NextOffset - Entry.getOffset() - 1;
1550 //===----------------------------------------------------------------------===//
1551 // Other miscellaneous methods.
1552 //===----------------------------------------------------------------------===//
1554 /// \brief Retrieve the inode for the given file entry, if possible.
1556 /// This routine involves a system call, and therefore should only be used
1557 /// in non-performance-critical code.
1558 static Optional<llvm::sys::fs::UniqueID>
1559 getActualFileUID(const FileEntry *File) {
1563 llvm::sys::fs::UniqueID ID;
1564 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1570 /// \brief Get the source location for the given file:line:col triplet.
1572 /// If the source file is included multiple times, the source location will
1573 /// be based upon an arbitrary inclusion.
1574 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1576 unsigned Col) const {
1577 assert(SourceFile && "Null source file!");
1578 assert(Line && Col && "Line and column should start from 1!");
1580 FileID FirstFID = translateFile(SourceFile);
1581 return translateLineCol(FirstFID, Line, Col);
1584 /// \brief Get the FileID for the given file.
1586 /// If the source file is included multiple times, the FileID will be the
1587 /// first inclusion.
1588 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1589 assert(SourceFile && "Null source file!");
1591 // Find the first file ID that corresponds to the given file.
1594 // First, check the main file ID, since it is common to look for a
1595 // location in the main file.
1596 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1597 Optional<StringRef> SourceFileName;
1598 if (MainFileID.isValid()) {
1599 bool Invalid = false;
1600 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1604 if (MainSLoc.isFile()) {
1605 const ContentCache *MainContentCache
1606 = MainSLoc.getFile().getContentCache();
1607 if (!MainContentCache) {
1608 // Can't do anything
1609 } else if (MainContentCache->OrigEntry == SourceFile) {
1610 FirstFID = MainFileID;
1612 // Fall back: check whether we have the same base name and inode
1613 // as the main file.
1614 const FileEntry *MainFile = MainContentCache->OrigEntry;
1615 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1616 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1617 SourceFileUID = getActualFileUID(SourceFile);
1618 if (SourceFileUID) {
1619 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1620 getActualFileUID(MainFile)) {
1621 if (*SourceFileUID == *MainFileUID) {
1622 FirstFID = MainFileID;
1623 SourceFile = MainFile;
1632 if (FirstFID.isInvalid()) {
1633 // The location we're looking for isn't in the main file; look
1634 // through all of the local source locations.
1635 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1636 bool Invalid = false;
1637 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1641 if (SLoc.isFile() &&
1642 SLoc.getFile().getContentCache() &&
1643 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1644 FirstFID = FileID::get(I);
1648 // If that still didn't help, try the modules.
1649 if (FirstFID.isInvalid()) {
1650 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1651 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1652 if (SLoc.isFile() &&
1653 SLoc.getFile().getContentCache() &&
1654 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1655 FirstFID = FileID::get(-int(I) - 2);
1662 // If we haven't found what we want yet, try again, but this time stat()
1663 // each of the files in case the files have changed since we originally
1665 if (FirstFID.isInvalid() &&
1667 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1668 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1669 bool Invalid = false;
1670 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1673 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1677 if (SLoc.isFile()) {
1678 const ContentCache *FileContentCache
1679 = SLoc.getFile().getContentCache();
1680 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1683 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1684 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1685 getActualFileUID(Entry)) {
1686 if (*SourceFileUID == *EntryUID) {
1687 FirstFID = FileID::get(I);
1701 /// \brief Get the source location in \arg FID for the given line:col.
1702 /// Returns null location if \arg FID is not a file SLocEntry.
1703 SourceLocation SourceManager::translateLineCol(FileID FID,
1705 unsigned Col) const {
1706 // Lines are used as a one-based index into a zero-based array. This assert
1707 // checks for possible buffer underruns.
1708 assert(Line && Col && "Line and column should start from 1!");
1710 if (FID.isInvalid())
1711 return SourceLocation();
1713 bool Invalid = false;
1714 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1716 return SourceLocation();
1718 if (!Entry.isFile())
1719 return SourceLocation();
1721 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1723 if (Line == 1 && Col == 1)
1726 ContentCache *Content
1727 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1729 return SourceLocation();
1731 // If this is the first use of line information for this buffer, compute the
1732 // SourceLineCache for it on demand.
1733 if (!Content->SourceLineCache) {
1734 bool MyInvalid = false;
1735 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1737 return SourceLocation();
1740 if (Line > Content->NumLines) {
1741 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1744 return FileLoc.getLocWithOffset(Size);
1747 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1748 unsigned FilePos = Content->SourceLineCache[Line - 1];
1749 const char *Buf = Buffer->getBufferStart() + FilePos;
1750 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1752 return FileLoc.getLocWithOffset(FilePos);
1756 // Check that the given column is valid.
1757 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1759 return FileLoc.getLocWithOffset(FilePos + i);
1762 /// \brief Compute a map of macro argument chunks to their expanded source
1763 /// location. Chunks that are not part of a macro argument will map to an
1764 /// invalid source location. e.g. if a file contains one macro argument at
1765 /// offset 100 with length 10, this is how the map will be formed:
1766 /// 0 -> SourceLocation()
1767 /// 100 -> Expanded macro arg location
1768 /// 110 -> SourceLocation()
1769 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1771 assert(FID.isValid());
1773 // Initially no macro argument chunk is present.
1774 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1779 // Stop if there are no more FileIDs to check.
1781 if (unsigned(ID) >= local_sloc_entry_size())
1783 } else if (ID == -1) {
1787 bool Invalid = false;
1788 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1791 if (Entry.isFile()) {
1792 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1793 if (IncludeLoc.isInvalid())
1795 if (!isInFileID(IncludeLoc, FID))
1796 return; // No more files/macros that may be "contained" in this file.
1798 // Skip the files/macros of the #include'd file, we only care about macros
1799 // that lexed macro arguments from our file.
1800 if (Entry.getFile().NumCreatedFIDs)
1801 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1805 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1807 if (ExpInfo.getExpansionLocStart().isFileID()) {
1808 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1809 return; // No more files/macros that may be "contained" in this file.
1812 if (!ExpInfo.isMacroArgExpansion())
1815 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1816 ExpInfo.getSpellingLoc(),
1817 SourceLocation::getMacroLoc(Entry.getOffset()),
1818 getFileIDSize(FileID::get(ID)));
1822 void SourceManager::associateFileChunkWithMacroArgExp(
1823 MacroArgsMap &MacroArgsCache,
1825 SourceLocation SpellLoc,
1826 SourceLocation ExpansionLoc,
1827 unsigned ExpansionLength) const {
1828 if (!SpellLoc.isFileID()) {
1829 unsigned SpellBeginOffs = SpellLoc.getOffset();
1830 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1832 // The spelling range for this macro argument expansion can span multiple
1833 // consecutive FileID entries. Go through each entry contained in the
1834 // spelling range and if one is itself a macro argument expansion, recurse
1835 // and associate the file chunk that it represents.
1837 FileID SpellFID; // Current FileID in the spelling range.
1838 unsigned SpellRelativeOffs;
1839 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1841 const SLocEntry &Entry = getSLocEntry(SpellFID);
1842 unsigned SpellFIDBeginOffs = Entry.getOffset();
1843 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1844 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1845 const ExpansionInfo &Info = Entry.getExpansion();
1846 if (Info.isMacroArgExpansion()) {
1847 unsigned CurrSpellLength;
1848 if (SpellFIDEndOffs < SpellEndOffs)
1849 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1851 CurrSpellLength = ExpansionLength;
1852 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1853 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1854 ExpansionLoc, CurrSpellLength);
1857 if (SpellFIDEndOffs >= SpellEndOffs)
1858 return; // we covered all FileID entries in the spelling range.
1860 // Move to the next FileID entry in the spelling range.
1861 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1862 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1863 ExpansionLength -= advance;
1865 SpellRelativeOffs = 0;
1869 assert(SpellLoc.isFileID());
1872 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1875 unsigned EndOffs = BeginOffs + ExpansionLength;
1877 // Add a new chunk for this macro argument. A previous macro argument chunk
1878 // may have been lexed again, so e.g. if the map is
1879 // 0 -> SourceLocation()
1880 // 100 -> Expanded loc #1
1881 // 110 -> SourceLocation()
1882 // and we found a new macro FileID that lexed from offet 105 with length 3,
1883 // the new map will be:
1884 // 0 -> SourceLocation()
1885 // 100 -> Expanded loc #1
1886 // 105 -> Expanded loc #2
1887 // 108 -> Expanded loc #1
1888 // 110 -> SourceLocation()
1890 // Since re-lexed macro chunks will always be the same size or less of
1891 // previous chunks, we only need to find where the ending of the new macro
1892 // chunk is mapped to and update the map with new begin/end mappings.
1894 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1896 SourceLocation EndOffsMappedLoc = I->second;
1897 MacroArgsCache[BeginOffs] = ExpansionLoc;
1898 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1901 /// \brief If \arg Loc points inside a function macro argument, the returned
1902 /// location will be the macro location in which the argument was expanded.
1903 /// If a macro argument is used multiple times, the expanded location will
1904 /// be at the first expansion of the argument.
1908 /// Passing a file location pointing at 'foo', will yield a macro location
1909 /// where 'foo' was expanded into.
1911 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1912 if (Loc.isInvalid() || !Loc.isFileID())
1917 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1918 if (FID.isInvalid())
1921 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1922 if (!MacroArgsCache) {
1923 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1924 computeMacroArgsCache(*MacroArgsCache, FID);
1927 assert(!MacroArgsCache->empty());
1928 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1931 unsigned MacroArgBeginOffs = I->first;
1932 SourceLocation MacroArgExpandedLoc = I->second;
1933 if (MacroArgExpandedLoc.isValid())
1934 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1939 std::pair<FileID, unsigned>
1940 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1941 if (FID.isInvalid())
1942 return std::make_pair(FileID(), 0);
1944 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1946 using DecompTy = std::pair<FileID, unsigned>;
1947 using MapTy = llvm::DenseMap<FileID, DecompTy>;
1948 std::pair<MapTy::iterator, bool>
1949 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1950 DecompTy &DecompLoc = InsertOp.first->second;
1951 if (!InsertOp.second)
1952 return DecompLoc; // already in map.
1954 SourceLocation UpperLoc;
1955 bool Invalid = false;
1956 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1958 if (Entry.isExpansion())
1959 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1961 UpperLoc = Entry.getFile().getIncludeLoc();
1964 if (UpperLoc.isValid())
1965 DecompLoc = getDecomposedLoc(UpperLoc);
1970 /// Given a decomposed source location, move it up the include/expansion stack
1971 /// to the parent source location. If this is possible, return the decomposed
1972 /// version of the parent in Loc and return false. If Loc is the top-level
1973 /// entry, return true and don't modify it.
1974 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1975 const SourceManager &SM) {
1976 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1977 if (UpperLoc.first.isInvalid())
1978 return true; // We reached the top.
1984 /// Return the cache entry for comparing the given file IDs
1985 /// for isBeforeInTranslationUnit.
1986 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1987 FileID RFID) const {
1988 // This is a magic number for limiting the cache size. It was experimentally
1989 // derived from a small Objective-C project (where the cache filled
1990 // out to ~250 items). We can make it larger if necessary.
1991 enum { MagicCacheSize = 300 };
1992 IsBeforeInTUCacheKey Key(LFID, RFID);
1994 // If the cache size isn't too large, do a lookup and if necessary default
1995 // construct an entry. We can then return it to the caller for direct
1996 // use. When they update the value, the cache will get automatically
1998 if (IBTUCache.size() < MagicCacheSize)
1999 return IBTUCache[Key];
2001 // Otherwise, do a lookup that will not construct a new value.
2002 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2003 if (I != IBTUCache.end())
2006 // Fall back to the overflow value.
2007 return IBTUCacheOverflow;
2010 /// \brief Determines the order of 2 source locations in the translation unit.
2012 /// \returns true if LHS source location comes before RHS, false otherwise.
2013 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2014 SourceLocation RHS) const {
2015 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2019 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2020 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2022 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2023 // is a serialized one referring to a file that was removed after we loaded
2025 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2026 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2028 std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2030 return InSameTU.second;
2032 // If we arrived here, the location is either in a built-ins buffer or
2033 // associated with global inline asm. PR5662 and PR22576 are examples.
2035 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2036 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2037 bool LIsBuiltins = LB == "<built-in>";
2038 bool RIsBuiltins = RB == "<built-in>";
2039 // Sort built-in before non-built-in.
2040 if (LIsBuiltins || RIsBuiltins) {
2041 if (LIsBuiltins != RIsBuiltins)
2043 // Both are in built-in buffers, but from different files. We just claim that
2044 // lower IDs come first.
2045 return LOffs.first < ROffs.first;
2047 bool LIsAsm = LB == "<inline asm>";
2048 bool RIsAsm = RB == "<inline asm>";
2049 // Sort assembler after built-ins, but before the rest.
2050 if (LIsAsm || RIsAsm) {
2051 if (LIsAsm != RIsAsm)
2053 assert(LOffs.first == ROffs.first);
2056 bool LIsScratch = LB == "<scratch space>";
2057 bool RIsScratch = RB == "<scratch space>";
2058 // Sort scratch after inline asm, but before the rest.
2059 if (LIsScratch || RIsScratch) {
2060 if (LIsScratch != RIsScratch)
2062 return LOffs.second < ROffs.second;
2064 llvm_unreachable("Unsortable locations found");
2067 std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2068 std::pair<FileID, unsigned> &LOffs,
2069 std::pair<FileID, unsigned> &ROffs) const {
2070 // If the source locations are in the same file, just compare offsets.
2071 if (LOffs.first == ROffs.first)
2072 return std::make_pair(true, LOffs.second < ROffs.second);
2074 // If we are comparing a source location with multiple locations in the same
2075 // file, we get a big win by caching the result.
2076 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2077 getInBeforeInTUCache(LOffs.first, ROffs.first);
2079 // If we are comparing a source location with multiple locations in the same
2080 // file, we get a big win by caching the result.
2081 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2082 return std::make_pair(
2083 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2085 // Okay, we missed in the cache, start updating the cache for this query.
2086 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2087 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2089 // We need to find the common ancestor. The only way of doing this is to
2090 // build the complete include chain for one and then walking up the chain
2091 // of the other looking for a match.
2092 // We use a map from FileID to Offset to store the chain. Easier than writing
2093 // a custom set hash info that only depends on the first part of a pair.
2094 using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2097 LChain.insert(LOffs);
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 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2102 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2103 if (MoveUpIncludeHierarchy(ROffs, *this))
2104 break; // Met at topmost file.
2106 if (I != LChain.end())
2109 // If we exited because we found a nearest common ancestor, compare the
2110 // locations within the common file and cache them.
2111 if (LOffs.first == ROffs.first) {
2112 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2113 return std::make_pair(
2114 true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2116 // Clear the lookup cache, it depends on a common location.
2117 IsBeforeInTUCache.clear();
2118 return std::make_pair(false, false);
2121 void SourceManager::PrintStats() const {
2122 llvm::errs() << "\n*** Source Manager Stats:\n";
2123 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2124 << " mem buffers mapped.\n";
2125 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2126 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2127 << " bytes of capacity), "
2128 << NextLocalOffset << "B of Sloc address space used.\n";
2129 llvm::errs() << LoadedSLocEntryTable.size()
2130 << " loaded SLocEntries allocated, "
2131 << MaxLoadedOffset - CurrentLoadedOffset
2132 << "B of Sloc address space used.\n";
2134 unsigned NumLineNumsComputed = 0;
2135 unsigned NumFileBytesMapped = 0;
2136 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2137 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2138 NumFileBytesMapped += I->second->getSizeBytesMapped();
2140 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2142 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2143 << NumLineNumsComputed << " files with line #'s computed, "
2144 << NumMacroArgsComputed << " files with macro args computed.\n";
2145 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2146 << NumBinaryProbes << " binary.\n";
2149 LLVM_DUMP_METHOD void SourceManager::dump() const {
2150 llvm::raw_ostream &out = llvm::errs();
2152 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2153 llvm::Optional<unsigned> NextStart) {
2154 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2155 << " <SourceLocation " << Entry.getOffset() << ":";
2157 out << *NextStart << ">\n";
2160 if (Entry.isFile()) {
2161 auto &FI = Entry.getFile();
2162 if (FI.NumCreatedFIDs)
2163 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2165 if (FI.getIncludeLoc().isValid())
2166 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2167 if (auto *CC = FI.getContentCache()) {
2168 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2170 if (CC->BufferOverridden)
2171 out << " contents overridden\n";
2172 if (CC->ContentsEntry != CC->OrigEntry) {
2173 out << " contents from "
2174 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2179 auto &EI = Entry.getExpansion();
2180 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2181 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2182 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2183 << EI.getExpansionLocEnd().getOffset() << ">\n";
2187 // Dump local SLocEntries.
2188 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2189 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2190 ID == NumIDs - 1 ? NextLocalOffset
2191 : LocalSLocEntryTable[ID + 1].getOffset());
2193 // Dump loaded SLocEntries.
2194 llvm::Optional<unsigned> NextStart;
2195 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2196 int ID = -(int)Index - 2;
2197 if (SLocEntryLoaded[Index]) {
2198 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2199 NextStart = LoadedSLocEntryTable[Index].getOffset();
2206 ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2208 /// Return the amount of memory used by memory buffers, breaking down
2209 /// by heap-backed versus mmap'ed memory.
2210 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2211 size_t malloc_bytes = 0;
2212 size_t mmap_bytes = 0;
2214 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2215 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2216 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2217 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2218 mmap_bytes += sized_mapped;
2220 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2221 malloc_bytes += sized_mapped;
2225 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2228 size_t SourceManager::getDataStructureSizes() const {
2229 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2230 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2231 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2232 + llvm::capacity_in_bytes(SLocEntryLoaded)
2233 + llvm::capacity_in_bytes(FileInfos);
2235 if (OverriddenFilesInfo)
2236 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);