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/SourceManagerInternals.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Capacity.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
30 using namespace SrcMgr;
31 using llvm::MemoryBuffer;
33 //===----------------------------------------------------------------------===//
34 // SourceManager Helper Classes
35 //===----------------------------------------------------------------------===//
37 ContentCache::~ContentCache() {
38 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
42 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
44 unsigned ContentCache::getSizeBytesMapped() const {
45 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
48 /// Returns the kind of memory used to back the memory buffer for
49 /// this content cache. This is used for performance analysis.
50 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51 assert(Buffer.getPointer());
53 // Should be unreachable, but keep for sanity.
54 if (!Buffer.getPointer())
55 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57 llvm::MemoryBuffer *buf = Buffer.getPointer();
58 return buf->getBufferKind();
61 /// getSize - Returns the size of the content encapsulated by this ContentCache.
62 /// This can be the size of the source file or the size of an arbitrary
63 /// scratch buffer. If the ContentCache encapsulates a source file, that
64 /// file is not lazily brought in from disk to satisfy this query.
65 unsigned ContentCache::getSize() const {
66 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
67 : (unsigned) ContentsEntry->getSize();
70 void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
71 if (B && B == Buffer.getPointer()) {
72 assert(0 && "Replacing with the same buffer");
73 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
77 if (shouldFreeBuffer())
78 delete Buffer.getPointer();
80 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
83 llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
84 const SourceManager &SM,
86 bool *Invalid) const {
87 // Lazily create the Buffer for ContentCaches that wrap files. If we already
88 // computed it, just return what we have.
89 if (Buffer.getPointer() || !ContentsEntry) {
91 *Invalid = isBufferInvalid();
93 return Buffer.getPointer();
96 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
98 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
100 // If we were unable to open the file, then we are in an inconsistent
101 // situation where the content cache referenced a file which no longer
102 // exists. Most likely, we were using a stat cache with an invalid entry but
103 // the file could also have been removed during processing. Since we can't
104 // really deal with this situation, just create an empty buffer.
106 // FIXME: This is definitely not ideal, but our immediate clients can't
107 // currently handle returning a null entry here. Ideally we should detect
108 // that we are in an inconsistent situation and error out as quickly as
110 if (!BufferOrError) {
111 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
112 Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer(
113 ContentsEntry->getSize(), "<invalid>").release());
114 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
115 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
116 Ptr[i] = FillStr[i % FillStr.size()];
118 if (Diag.isDiagnosticInFlight())
119 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
120 ContentsEntry->getName(),
121 BufferOrError.getError().message());
123 Diag.Report(Loc, diag::err_cannot_open_file)
124 << ContentsEntry->getName() << BufferOrError.getError().message();
126 Buffer.setInt(Buffer.getInt() | InvalidFlag);
128 if (Invalid) *Invalid = true;
129 return Buffer.getPointer();
132 Buffer.setPointer(BufferOrError->release());
134 // Check that the file's size is the same as in the file entry (which may
135 // have come from a stat cache).
136 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
137 if (Diag.isDiagnosticInFlight())
138 Diag.SetDelayedDiagnostic(diag::err_file_modified,
139 ContentsEntry->getName());
141 Diag.Report(Loc, diag::err_file_modified)
142 << ContentsEntry->getName();
144 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
149 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
150 // (BOM). We only support UTF-8 with and without a BOM right now. See
151 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
152 StringRef BufStr = Buffer.getPointer()->getBuffer();
153 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
154 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
155 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
156 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
157 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
158 .StartsWith("\x2B\x2F\x76", "UTF-7")
159 .StartsWith("\xF7\x64\x4C", "UTF-1")
160 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
161 .StartsWith("\x0E\xFE\xFF", "SDSU")
162 .StartsWith("\xFB\xEE\x28", "BOCU-1")
163 .StartsWith("\x84\x31\x95\x33", "GB-18030")
167 Diag.Report(Loc, diag::err_unsupported_bom)
168 << InvalidBOM << ContentsEntry->getName();
169 Buffer.setInt(Buffer.getInt() | InvalidFlag);
173 *Invalid = isBufferInvalid();
175 return Buffer.getPointer();
178 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
180 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
182 FilenamesByID.push_back(&*IterBool.first);
183 return IterBool.first->second;
186 /// AddLineNote - Add a line note to the line table that indicates that there
187 /// is a \#line at the specified FID/Offset location which changes the presumed
188 /// location to LineNo/FilenameID.
189 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
190 unsigned LineNo, int FilenameID) {
191 std::vector<LineEntry> &Entries = LineEntries[FID];
193 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194 "Adding line entries out of order!");
196 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
197 unsigned IncludeOffset = 0;
199 if (!Entries.empty()) {
200 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201 // that we are still in "foo.h".
202 if (FilenameID == -1)
203 FilenameID = Entries.back().FilenameID;
205 // If we are after a line marker that switched us to system header mode, or
206 // that set #include information, preserve it.
207 Kind = Entries.back().FileKind;
208 IncludeOffset = Entries.back().IncludeOffset;
211 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
215 /// AddLineNote This is the same as the previous version of AddLineNote, but is
216 /// used for GNU line markers. If EntryExit is 0, then this doesn't change the
217 /// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
218 /// this is a file exit. FileKind specifies whether this is a system header or
219 /// extern C system header.
220 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
221 unsigned LineNo, int FilenameID,
223 SrcMgr::CharacteristicKind FileKind) {
224 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
226 std::vector<LineEntry> &Entries = LineEntries[FID];
228 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229 "Adding line entries out of order!");
231 unsigned IncludeOffset = 0;
232 if (EntryExit == 0) { // No #include stack change.
233 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234 } else if (EntryExit == 1) {
235 IncludeOffset = Offset-1;
236 } else if (EntryExit == 2) {
237 assert(!Entries.empty() && Entries.back().IncludeOffset &&
238 "PPDirectives should have caught case when popping empty include stack");
240 // Get the include loc of the last entries' include loc as our include loc.
242 if (const LineEntry *PrevEntry =
243 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244 IncludeOffset = PrevEntry->IncludeOffset;
247 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
252 /// FindNearestLineEntry - Find the line entry nearest to FID that is before
253 /// it. If there is no line entry before Offset in FID, return null.
254 const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
256 const std::vector<LineEntry> &Entries = LineEntries[FID];
257 assert(!Entries.empty() && "No #line entries for this FID after all!");
259 // It is very common for the query to be after the last #line, check this
261 if (Entries.back().FileOffset <= Offset)
262 return &Entries.back();
264 // Do a binary search to find the maximal element that is still before Offset.
265 std::vector<LineEntry>::const_iterator I =
266 std::upper_bound(Entries.begin(), Entries.end(), Offset);
267 if (I == Entries.begin()) return nullptr;
271 /// \brief Add a new line entry that has already been encoded into
272 /// the internal representation of the line table.
273 void LineTableInfo::AddEntry(FileID FID,
274 const std::vector<LineEntry> &Entries) {
275 LineEntries[FID] = Entries;
278 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
280 unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
281 return getLineTable().getLineTableFilenameID(Name);
285 /// AddLineNote - Add a line note to the line table for the FileID and offset
286 /// specified by Loc. If FilenameID is -1, it is considered to be
288 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
290 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
292 bool Invalid = false;
293 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
294 if (!Entry.isFile() || Invalid)
297 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
299 // Remember that this file has #line directives now if it doesn't already.
300 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
302 getLineTable().AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
305 /// AddLineNote - Add a GNU line marker to the line table.
306 void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
307 int FilenameID, bool IsFileEntry,
308 bool IsFileExit, bool IsSystemHeader,
309 bool IsExternCHeader) {
310 // If there is no filename and no flags, this is treated just like a #line,
311 // which does not change the flags of the previous line marker.
312 if (FilenameID == -1) {
313 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
314 "Can't set flags without setting the filename!");
315 return AddLineNote(Loc, LineNo, FilenameID);
318 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
320 bool Invalid = false;
321 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
322 if (!Entry.isFile() || Invalid)
325 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
327 // Remember that this file has #line directives now if it doesn't already.
328 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
330 (void) getLineTable();
332 SrcMgr::CharacteristicKind FileKind;
334 FileKind = SrcMgr::C_ExternCSystem;
335 else if (IsSystemHeader)
336 FileKind = SrcMgr::C_System;
338 FileKind = SrcMgr::C_User;
340 unsigned EntryExit = 0;
346 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
347 EntryExit, FileKind);
350 LineTableInfo &SourceManager::getLineTable() {
352 LineTable = new LineTableInfo();
356 //===----------------------------------------------------------------------===//
357 // Private 'Create' methods.
358 //===----------------------------------------------------------------------===//
360 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
361 bool UserFilesAreVolatile)
362 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
363 UserFilesAreVolatile(UserFilesAreVolatile), FilesAreTransient(false),
364 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
367 Diag.setSourceManager(this);
370 SourceManager::~SourceManager() {
373 // Delete FileEntry objects corresponding to content caches. Since the actual
374 // content cache objects are bump pointer allocated, we just have to run the
375 // dtors, but we call the deallocate method for completeness.
376 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
377 if (MemBufferInfos[i]) {
378 MemBufferInfos[i]->~ContentCache();
379 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
382 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
383 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
385 I->second->~ContentCache();
386 ContentCacheAlloc.Deallocate(I->second);
391 void SourceManager::clearIDTables() {
392 MainFileID = FileID();
393 LocalSLocEntryTable.clear();
394 LoadedSLocEntryTable.clear();
395 SLocEntryLoaded.clear();
396 LastLineNoFileIDQuery = FileID();
397 LastLineNoContentCache = nullptr;
398 LastFileIDLookup = FileID();
403 // Use up FileID #0 as an invalid expansion.
405 CurrentLoadedOffset = MaxLoadedOffset;
406 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
409 /// getOrCreateContentCache - Create or return a cached ContentCache for the
412 SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
414 assert(FileEnt && "Didn't specify a file entry to use?");
416 // Do we already have information about this file?
417 ContentCache *&Entry = FileInfos[FileEnt];
418 if (Entry) return Entry;
420 // Nope, create a new Cache entry.
421 Entry = ContentCacheAlloc.Allocate<ContentCache>();
423 if (OverriddenFilesInfo) {
424 // If the file contents are overridden with contents from another file,
425 // pass that file to ContentCache.
426 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
427 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
428 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
429 new (Entry) ContentCache(FileEnt);
431 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
435 new (Entry) ContentCache(FileEnt);
438 Entry->IsSystemFile = isSystemFile;
439 Entry->IsTransient = FilesAreTransient;
445 /// createMemBufferContentCache - Create a new ContentCache for the specified
446 /// memory buffer. This does no caching.
447 const ContentCache *SourceManager::createMemBufferContentCache(
448 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
449 // Add a new ContentCache to the MemBufferInfos list and return it.
450 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
451 new (Entry) ContentCache();
452 MemBufferInfos.push_back(Entry);
453 Entry->setBuffer(std::move(Buffer));
457 const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
458 bool *Invalid) const {
459 assert(!SLocEntryLoaded[Index]);
460 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
463 // If the file of the SLocEntry changed we could still have loaded it.
464 if (!SLocEntryLoaded[Index]) {
465 // Try to recover; create a SLocEntry so the rest of clang can handle it.
466 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
467 FileInfo::get(SourceLocation(),
468 getFakeContentCacheForRecovery(),
473 return LoadedSLocEntryTable[Index];
476 std::pair<int, unsigned>
477 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
478 unsigned TotalSize) {
479 assert(ExternalSLocEntries && "Don't have an external sloc source");
480 // Make sure we're not about to run out of source locations.
481 if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
482 return std::make_pair(0, 0);
483 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
484 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
485 CurrentLoadedOffset -= TotalSize;
486 int ID = LoadedSLocEntryTable.size();
487 return std::make_pair(-ID - 1, CurrentLoadedOffset);
490 /// \brief As part of recovering from missing or changed content, produce a
491 /// fake, non-empty buffer.
492 llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
493 if (!FakeBufferForRecovery)
494 FakeBufferForRecovery =
495 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
497 return FakeBufferForRecovery.get();
500 /// \brief As part of recovering from missing or changed content, produce a
501 /// fake content cache.
502 const SrcMgr::ContentCache *
503 SourceManager::getFakeContentCacheForRecovery() const {
504 if (!FakeContentCacheForRecovery) {
505 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
506 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
509 return FakeContentCacheForRecovery.get();
512 /// \brief Returns the previous in-order FileID or an invalid FileID if there
513 /// is no previous one.
514 FileID SourceManager::getPreviousFileID(FileID FID) const {
525 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
529 return FileID::get(ID-1);
532 /// \brief Returns the next in-order FileID or an invalid FileID if there is
534 FileID SourceManager::getNextFileID(FileID FID) const {
540 if (unsigned(ID+1) >= local_sloc_entry_size())
542 } else if (ID+1 >= -1) {
546 return FileID::get(ID+1);
549 //===----------------------------------------------------------------------===//
550 // Methods to create new FileID's and macro expansions.
551 //===----------------------------------------------------------------------===//
553 /// createFileID - Create a new FileID for the specified ContentCache and
554 /// include position. This works regardless of whether the ContentCache
555 /// corresponds to a file or some other input source.
556 FileID SourceManager::createFileID(const ContentCache *File,
557 SourceLocation IncludePos,
558 SrcMgr::CharacteristicKind FileCharacter,
559 int LoadedID, unsigned LoadedOffset) {
561 assert(LoadedID != -1 && "Loading sentinel FileID");
562 unsigned Index = unsigned(-LoadedID) - 2;
563 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
564 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
565 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
566 FileInfo::get(IncludePos, File, FileCharacter));
567 SLocEntryLoaded[Index] = true;
568 return FileID::get(LoadedID);
570 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
571 FileInfo::get(IncludePos, File,
573 unsigned FileSize = File->getSize();
574 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
575 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
576 "Ran out of source locations!");
577 // We do a +1 here because we want a SourceLocation that means "the end of the
578 // file", e.g. for the "no newline at the end of the file" diagnostic.
579 NextLocalOffset += FileSize + 1;
581 // Set LastFileIDLookup to the newly created file. The next getFileID call is
582 // almost guaranteed to be from that file.
583 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
584 return LastFileIDLookup = FID;
588 SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
589 SourceLocation ExpansionLoc,
590 unsigned TokLength) {
591 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
593 return createExpansionLocImpl(Info, TokLength);
597 SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
598 SourceLocation ExpansionLocStart,
599 SourceLocation ExpansionLocEnd,
602 unsigned LoadedOffset) {
603 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
605 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
609 SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
612 unsigned LoadedOffset) {
614 assert(LoadedID != -1 && "Loading sentinel FileID");
615 unsigned Index = unsigned(-LoadedID) - 2;
616 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
617 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
618 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
619 SLocEntryLoaded[Index] = true;
620 return SourceLocation::getMacroLoc(LoadedOffset);
622 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
623 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
624 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
625 "Ran out of source locations!");
626 // See createFileID for that +1.
627 NextLocalOffset += TokLength + 1;
628 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
631 llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
633 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
634 assert(IR && "getOrCreateContentCache() cannot return NULL");
635 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
638 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
639 llvm::MemoryBuffer *Buffer,
641 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
642 assert(IR && "getOrCreateContentCache() cannot return NULL");
644 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
645 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
647 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
650 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
651 const FileEntry *NewFile) {
652 assert(SourceFile->getSize() == NewFile->getSize() &&
653 "Different sizes, use the FileManager to create a virtual file with "
655 assert(FileInfos.count(SourceFile) == 0 &&
656 "This function should be called at the initialization stage, before "
657 "any parsing occurs.");
658 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
661 void SourceManager::disableFileContentsOverride(const FileEntry *File) {
662 if (!isFileOverridden(File))
665 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
666 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
667 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
669 assert(OverriddenFilesInfo);
670 OverriddenFilesInfo->OverriddenFiles.erase(File);
671 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
674 void SourceManager::setFileIsTransient(const FileEntry *File) {
675 const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
676 const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
679 StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
680 bool MyInvalid = false;
681 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
682 if (!SLoc.isFile() || MyInvalid) {
685 return "<<<<<INVALID SOURCE LOCATION>>>>>";
688 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
689 Diag, *this, SourceLocation(), &MyInvalid);
691 *Invalid = MyInvalid;
694 return "<<<<<INVALID SOURCE LOCATION>>>>>";
696 return Buf->getBuffer();
699 //===----------------------------------------------------------------------===//
700 // SourceLocation manipulation methods.
701 //===----------------------------------------------------------------------===//
703 /// \brief Return the FileID for a SourceLocation.
705 /// This is the cache-miss path of getFileID. Not as hot as that function, but
706 /// still very important. It is responsible for finding the entry in the
707 /// SLocEntry tables that contains the specified location.
708 FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
710 return FileID::get(0);
712 // Now it is time to search for the correct file. See where the SLocOffset
713 // sits in the global view and consult local or loaded buffers for it.
714 if (SLocOffset < NextLocalOffset)
715 return getFileIDLocal(SLocOffset);
716 return getFileIDLoaded(SLocOffset);
719 /// \brief Return the FileID for a SourceLocation with a low offset.
721 /// This function knows that the SourceLocation is in a local buffer, not a
723 FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
724 assert(SLocOffset < NextLocalOffset && "Bad function choice");
726 // After the first and second level caches, I see two common sorts of
727 // behavior: 1) a lot of searched FileID's are "near" the cached file
728 // location or are "near" the cached expansion location. 2) others are just
729 // completely random and may be a very long way away.
731 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
732 // then we fall back to a less cache efficient, but more scalable, binary
733 // search to find the location.
735 // See if this is near the file point - worst case we start scanning from the
736 // most newly created FileID.
737 const SrcMgr::SLocEntry *I;
739 if (LastFileIDLookup.ID < 0 ||
740 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
741 // Neither loc prunes our search.
742 I = LocalSLocEntryTable.end();
744 // Perhaps it is near the file point.
745 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
748 // Find the FileID that contains this. "I" is an iterator that points to a
749 // FileID whose offset is known to be larger than SLocOffset.
750 unsigned NumProbes = 0;
753 if (I->getOffset() <= SLocOffset) {
754 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
756 // If this isn't an expansion, remember it. We have good locality across
758 if (!I->isExpansion())
759 LastFileIDLookup = Res;
760 NumLinearScans += NumProbes+1;
763 if (++NumProbes == 8)
767 // Convert "I" back into an index. We know that it is an entry whose index is
768 // larger than the offset we are looking for.
769 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
770 // LessIndex - This is the lower bound of the range that we're searching.
771 // We know that the offset corresponding to the FileID is is less than
773 unsigned LessIndex = 0;
776 bool Invalid = false;
777 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
778 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
780 return FileID::get(0);
784 // If the offset of the midpoint is too large, chop the high side of the
785 // range to the midpoint.
786 if (MidOffset > SLocOffset) {
787 GreaterIndex = MiddleIndex;
791 // If the middle index contains the value, succeed and return.
792 // FIXME: This could be made faster by using a function that's aware of
793 // being in the local area.
794 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
795 FileID Res = FileID::get(MiddleIndex);
797 // If this isn't a macro expansion, remember it. We have good locality
798 // across FileID lookups.
799 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
800 LastFileIDLookup = Res;
801 NumBinaryProbes += NumProbes;
805 // Otherwise, move the low-side up to the middle index.
806 LessIndex = MiddleIndex;
810 /// \brief Return the FileID for a SourceLocation with a high offset.
812 /// This function knows that the SourceLocation is in a loaded buffer, not a
814 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
815 // Sanity checking, otherwise a bug may lead to hanging in release build.
816 if (SLocOffset < CurrentLoadedOffset) {
817 assert(0 && "Invalid SLocOffset or bad function choice");
821 // Essentially the same as the local case, but the loaded array is sorted
822 // in the other direction.
824 // First do a linear scan from the last lookup position, if possible.
826 int LastID = LastFileIDLookup.ID;
827 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
830 I = (-LastID - 2) + 1;
833 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
834 // Make sure the entry is loaded!
835 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
836 if (E.getOffset() <= SLocOffset) {
837 FileID Res = FileID::get(-int(I) - 2);
839 if (!E.isExpansion())
840 LastFileIDLookup = Res;
841 NumLinearScans += NumProbes + 1;
846 // Linear scan failed. Do the binary search. Note the reverse sorting of the
847 // table: GreaterIndex is the one where the offset is greater, which is
848 // actually a lower index!
849 unsigned GreaterIndex = I;
850 unsigned LessIndex = LoadedSLocEntryTable.size();
854 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
855 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
856 if (E.getOffset() == 0)
857 return FileID(); // invalid entry.
861 if (E.getOffset() > SLocOffset) {
862 // Sanity checking, otherwise a bug may lead to hanging in release build.
863 if (GreaterIndex == MiddleIndex) {
864 assert(0 && "binary search missed the entry");
867 GreaterIndex = MiddleIndex;
871 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
872 FileID Res = FileID::get(-int(MiddleIndex) - 2);
873 if (!E.isExpansion())
874 LastFileIDLookup = Res;
875 NumBinaryProbes += NumProbes;
879 // Sanity checking, otherwise a bug may lead to hanging in release build.
880 if (LessIndex == MiddleIndex) {
881 assert(0 && "binary search missed the entry");
884 LessIndex = MiddleIndex;
888 SourceLocation SourceManager::
889 getExpansionLocSlowCase(SourceLocation Loc) const {
891 // Note: If Loc indicates an offset into a token that came from a macro
892 // expansion (e.g. the 5th character of the token) we do not want to add
893 // this offset when going to the expansion location. The expansion
894 // location is the macro invocation, which the offset has nothing to do
895 // with. This is unlike when we get the spelling loc, because the offset
896 // directly correspond to the token whose spelling we're inspecting.
897 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
898 } while (!Loc.isFileID());
903 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
905 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
906 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
907 Loc = Loc.getLocWithOffset(LocInfo.second);
908 } while (!Loc.isFileID());
912 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
914 if (isMacroArgExpansion(Loc))
915 Loc = getImmediateSpellingLoc(Loc);
917 Loc = getImmediateExpansionRange(Loc).first;
918 } while (!Loc.isFileID());
923 std::pair<FileID, unsigned>
924 SourceManager::getDecomposedExpansionLocSlowCase(
925 const SrcMgr::SLocEntry *E) const {
926 // If this is an expansion record, walk through all the expansion points.
931 Loc = E->getExpansion().getExpansionLocStart();
933 FID = getFileID(Loc);
934 E = &getSLocEntry(FID);
935 Offset = Loc.getOffset()-E->getOffset();
936 } while (!Loc.isFileID());
938 return std::make_pair(FID, Offset);
941 std::pair<FileID, unsigned>
942 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
943 unsigned Offset) const {
944 // If this is an expansion record, walk through all the expansion points.
948 Loc = E->getExpansion().getSpellingLoc();
949 Loc = Loc.getLocWithOffset(Offset);
951 FID = getFileID(Loc);
952 E = &getSLocEntry(FID);
953 Offset = Loc.getOffset()-E->getOffset();
954 } while (!Loc.isFileID());
956 return std::make_pair(FID, Offset);
959 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
960 /// spelling location referenced by the ID. This is the first level down
961 /// towards the place where the characters that make up the lexed token can be
962 /// found. This should not generally be used by clients.
963 SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
964 if (Loc.isFileID()) return Loc;
965 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
966 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
967 return Loc.getLocWithOffset(LocInfo.second);
971 /// getImmediateExpansionRange - Loc is required to be an expansion location.
972 /// Return the start/end of the expansion information.
973 std::pair<SourceLocation,SourceLocation>
974 SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
975 assert(Loc.isMacroID() && "Not a macro expansion loc!");
976 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
977 return Expansion.getExpansionLocRange();
980 /// getExpansionRange - Given a SourceLocation object, return the range of
981 /// tokens covered by the expansion in the ultimate file.
982 std::pair<SourceLocation,SourceLocation>
983 SourceManager::getExpansionRange(SourceLocation Loc) const {
984 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
986 std::pair<SourceLocation,SourceLocation> Res =
987 getImmediateExpansionRange(Loc);
989 // Fully resolve the start and end locations to their ultimate expansion
991 while (!Res.first.isFileID())
992 Res.first = getImmediateExpansionRange(Res.first).first;
993 while (!Res.second.isFileID())
994 Res.second = getImmediateExpansionRange(Res.second).second;
998 bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
999 SourceLocation *StartLoc) const {
1000 if (!Loc.isMacroID()) return false;
1002 FileID FID = getFileID(Loc);
1003 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1004 if (!Expansion.isMacroArgExpansion()) return false;
1007 *StartLoc = Expansion.getExpansionLocStart();
1011 bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1012 if (!Loc.isMacroID()) return false;
1014 FileID FID = getFileID(Loc);
1015 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1016 return Expansion.isMacroBodyExpansion();
1019 bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1020 SourceLocation *MacroBegin) const {
1021 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1023 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1024 if (DecompLoc.second > 0)
1025 return false; // Does not point at the start of expansion range.
1027 bool Invalid = false;
1028 const SrcMgr::ExpansionInfo &ExpInfo =
1029 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1032 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1034 if (ExpInfo.isMacroArgExpansion()) {
1035 // For macro argument expansions, check if the previous FileID is part of
1036 // the same argument expansion, in which case this Loc is not at the
1037 // beginning of the expansion.
1038 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1039 if (!PrevFID.isInvalid()) {
1040 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1043 if (PrevEntry.isExpansion() &&
1044 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1050 *MacroBegin = ExpLoc;
1054 bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1055 SourceLocation *MacroEnd) const {
1056 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1058 FileID FID = getFileID(Loc);
1059 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1060 if (isInFileID(NextLoc, FID))
1061 return false; // Does not point at the end of expansion range.
1063 bool Invalid = false;
1064 const SrcMgr::ExpansionInfo &ExpInfo =
1065 getSLocEntry(FID, &Invalid).getExpansion();
1069 if (ExpInfo.isMacroArgExpansion()) {
1070 // For macro argument expansions, check if the next FileID is part of the
1071 // same argument expansion, in which case this Loc is not at the end of the
1073 FileID NextFID = getNextFileID(FID);
1074 if (!NextFID.isInvalid()) {
1075 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1078 if (NextEntry.isExpansion() &&
1079 NextEntry.getExpansion().getExpansionLocStart() ==
1080 ExpInfo.getExpansionLocStart())
1086 *MacroEnd = ExpInfo.getExpansionLocEnd();
1091 //===----------------------------------------------------------------------===//
1092 // Queries about the code at a SourceLocation.
1093 //===----------------------------------------------------------------------===//
1095 /// getCharacterData - Return a pointer to the start of the specified location
1096 /// in the appropriate MemoryBuffer.
1097 const char *SourceManager::getCharacterData(SourceLocation SL,
1098 bool *Invalid) const {
1099 // Note that this is a hot function in the getSpelling() path, which is
1100 // heavily used by -E mode.
1101 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1103 // Note that calling 'getBuffer()' may lazily page in a source file.
1104 bool CharDataInvalid = false;
1105 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1106 if (CharDataInvalid || !Entry.isFile()) {
1110 return "<<<<INVALID BUFFER>>>>";
1112 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1113 Diag, *this, SourceLocation(), &CharDataInvalid);
1115 *Invalid = CharDataInvalid;
1116 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
1120 /// getColumnNumber - Return the column # for the specified file position.
1121 /// this is significantly cheaper to compute than the line number.
1122 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1123 bool *Invalid) const {
1124 bool MyInvalid = false;
1125 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1127 *Invalid = MyInvalid;
1132 // It is okay to request a position just past the end of the buffer.
1133 if (FilePos > MemBuf->getBufferSize()) {
1139 // See if we just calculated the line number for this FilePos and can use
1140 // that to lookup the start of the line instead of searching for it.
1141 if (LastLineNoFileIDQuery == FID &&
1142 LastLineNoContentCache->SourceLineCache != nullptr &&
1143 LastLineNoResult < LastLineNoContentCache->NumLines) {
1144 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1145 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1146 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1147 if (FilePos >= LineStart && FilePos < LineEnd)
1148 return FilePos - LineStart + 1;
1151 const char *Buf = MemBuf->getBufferStart();
1152 unsigned LineStart = FilePos;
1153 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1155 return FilePos-LineStart+1;
1158 // isInvalid - Return the result of calling loc.isInvalid(), and
1159 // if Invalid is not null, set its value to same.
1160 template<typename LocType>
1161 static bool isInvalid(LocType Loc, bool *Invalid) {
1162 bool MyInvalid = Loc.isInvalid();
1164 *Invalid = MyInvalid;
1168 unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1169 bool *Invalid) const {
1170 if (isInvalid(Loc, Invalid)) return 0;
1171 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1172 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1175 unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1176 bool *Invalid) const {
1177 if (isInvalid(Loc, Invalid)) return 0;
1178 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1179 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1182 unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1183 bool *Invalid) const {
1184 PresumedLoc PLoc = getPresumedLoc(Loc);
1185 if (isInvalid(PLoc, Invalid)) return 0;
1186 return PLoc.getColumn();
1190 #include <emmintrin.h>
1193 static LLVM_ATTRIBUTE_NOINLINE void
1194 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1195 llvm::BumpPtrAllocator &Alloc,
1196 const SourceManager &SM, bool &Invalid);
1197 static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1198 llvm::BumpPtrAllocator &Alloc,
1199 const SourceManager &SM, bool &Invalid) {
1200 // Note that calling 'getBuffer()' may lazily page in the file.
1201 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1205 // Find the file offsets of all of the *physical* source lines. This does
1206 // not look at trigraphs, escaped newlines, or anything else tricky.
1207 SmallVector<unsigned, 256> LineOffsets;
1209 // Line #1 starts at char 0.
1210 LineOffsets.push_back(0);
1212 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1213 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1216 // Skip over the contents of the line.
1217 const unsigned char *NextBuf = (const unsigned char *)Buf;
1220 // Try to skip to the next newline using SSE instructions. This is very
1221 // performance sensitive for programs with lots of diagnostics and in -E
1223 __m128i CRs = _mm_set1_epi8('\r');
1224 __m128i LFs = _mm_set1_epi8('\n');
1226 // First fix up the alignment to 16 bytes.
1227 while (((uintptr_t)NextBuf & 0xF) != 0) {
1228 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1229 goto FoundSpecialChar;
1233 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1234 while (NextBuf+16 <= End) {
1235 const __m128i Chunk = *(const __m128i*)NextBuf;
1236 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1237 _mm_cmpeq_epi8(Chunk, LFs));
1238 unsigned Mask = _mm_movemask_epi8(Cmp);
1240 // If we found a newline, adjust the pointer and jump to the handling code.
1242 NextBuf += llvm::countTrailingZeros(Mask);
1243 goto FoundSpecialChar;
1249 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1255 Offs += NextBuf-Buf;
1258 if (Buf[0] == '\n' || Buf[0] == '\r') {
1259 // If this is \n\r or \r\n, skip both characters.
1260 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) {
1266 LineOffsets.push_back(Offs);
1268 // Otherwise, this is a null. If end of file, exit.
1269 if (Buf == End) break;
1270 // Otherwise, skip the null.
1276 // Copy the offsets into the FileInfo structure.
1277 FI->NumLines = LineOffsets.size();
1278 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1279 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1282 /// getLineNumber - Given a SourceLocation, return the spelling line number
1283 /// for the position indicated. This requires building and caching a table of
1284 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1285 /// about to emit a diagnostic.
1286 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1287 bool *Invalid) const {
1288 if (FID.isInvalid()) {
1294 ContentCache *Content;
1295 if (LastLineNoFileIDQuery == FID)
1296 Content = LastLineNoContentCache;
1298 bool MyInvalid = false;
1299 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1300 if (MyInvalid || !Entry.isFile()) {
1306 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1309 // If this is the first use of line information for this buffer, compute the
1310 /// SourceLineCache for it on demand.
1311 if (!Content->SourceLineCache) {
1312 bool MyInvalid = false;
1313 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1315 *Invalid = MyInvalid;
1321 // Okay, we know we have a line number table. Do a binary search to find the
1322 // line number that this character position lands on.
1323 unsigned *SourceLineCache = Content->SourceLineCache;
1324 unsigned *SourceLineCacheStart = SourceLineCache;
1325 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1327 unsigned QueriedFilePos = FilePos+1;
1329 // FIXME: I would like to be convinced that this code is worth being as
1330 // complicated as it is, binary search isn't that slow.
1332 // If it is worth being optimized, then in my opinion it could be more
1333 // performant, simpler, and more obviously correct by just "galloping" outward
1334 // from the queried file position. In fact, this could be incorporated into a
1335 // generic algorithm such as lower_bound_with_hint.
1337 // If someone gives me a test case where this matters, and I will do it! - DWD
1339 // If the previous query was to the same file, we know both the file pos from
1340 // that query and the line number returned. This allows us to narrow the
1341 // search space from the entire file to something near the match.
1342 if (LastLineNoFileIDQuery == FID) {
1343 if (QueriedFilePos >= LastLineNoFilePos) {
1344 // FIXME: Potential overflow?
1345 SourceLineCache = SourceLineCache+LastLineNoResult-1;
1347 // The query is likely to be nearby the previous one. Here we check to
1348 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1349 // where big comment blocks and vertical whitespace eat up lines but
1350 // contribute no tokens.
1351 if (SourceLineCache+5 < SourceLineCacheEnd) {
1352 if (SourceLineCache[5] > QueriedFilePos)
1353 SourceLineCacheEnd = SourceLineCache+5;
1354 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1355 if (SourceLineCache[10] > QueriedFilePos)
1356 SourceLineCacheEnd = SourceLineCache+10;
1357 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1358 if (SourceLineCache[20] > QueriedFilePos)
1359 SourceLineCacheEnd = SourceLineCache+20;
1364 if (LastLineNoResult < Content->NumLines)
1365 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1370 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1371 unsigned LineNo = Pos-SourceLineCacheStart;
1373 LastLineNoFileIDQuery = FID;
1374 LastLineNoContentCache = Content;
1375 LastLineNoFilePos = QueriedFilePos;
1376 LastLineNoResult = LineNo;
1380 unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1381 bool *Invalid) const {
1382 if (isInvalid(Loc, Invalid)) return 0;
1383 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1384 return getLineNumber(LocInfo.first, LocInfo.second);
1386 unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1387 bool *Invalid) const {
1388 if (isInvalid(Loc, Invalid)) return 0;
1389 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1390 return getLineNumber(LocInfo.first, LocInfo.second);
1392 unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1393 bool *Invalid) const {
1394 PresumedLoc PLoc = getPresumedLoc(Loc);
1395 if (isInvalid(PLoc, Invalid)) return 0;
1396 return PLoc.getLine();
1399 /// getFileCharacteristic - return the file characteristic of the specified
1400 /// source location, indicating whether this is a normal file, a system
1401 /// header, or an "implicit extern C" system header.
1403 /// This state can be modified with flags on GNU linemarker directives like:
1405 /// which changes all source locations in the current file after that to be
1406 /// considered to be from a system header.
1407 SrcMgr::CharacteristicKind
1408 SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1409 assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1410 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1411 bool Invalid = false;
1412 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1413 if (Invalid || !SEntry.isFile())
1416 const SrcMgr::FileInfo &FI = SEntry.getFile();
1418 // If there are no #line directives in this file, just return the whole-file
1420 if (!FI.hasLineDirectives())
1421 return FI.getFileCharacteristic();
1423 assert(LineTable && "Can't have linetable entries without a LineTable!");
1424 // See if there is a #line directive before the location.
1425 const LineEntry *Entry =
1426 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1428 // If this is before the first line marker, use the file characteristic.
1430 return FI.getFileCharacteristic();
1432 return Entry->FileKind;
1435 /// Return the filename or buffer identifier of the buffer the location is in.
1436 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1437 /// for normal clients.
1438 StringRef SourceManager::getBufferName(SourceLocation Loc,
1439 bool *Invalid) const {
1440 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1442 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1446 /// getPresumedLoc - This method returns the "presumed" location of a
1447 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1448 /// or GNU line marker directives. This provides a view on the data that a
1449 /// user should see in diagnostics, for example.
1451 /// Note that a presumed location is always given as the expansion point of an
1452 /// expansion location, not at the spelling location.
1453 PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1454 bool UseLineDirectives) const {
1455 if (Loc.isInvalid()) return PresumedLoc();
1457 // Presumed locations are always for expansion points.
1458 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1460 bool Invalid = false;
1461 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1462 if (Invalid || !Entry.isFile())
1463 return PresumedLoc();
1465 const SrcMgr::FileInfo &FI = Entry.getFile();
1466 const SrcMgr::ContentCache *C = FI.getContentCache();
1468 // To get the source name, first consult the FileEntry (if one exists)
1469 // before the MemBuffer as this will avoid unnecessarily paging in the
1473 Filename = C->OrigEntry->getName();
1475 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1477 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1479 return PresumedLoc();
1480 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1482 return PresumedLoc();
1484 SourceLocation IncludeLoc = FI.getIncludeLoc();
1486 // If we have #line directives in this file, update and overwrite the physical
1487 // location info if appropriate.
1488 if (UseLineDirectives && FI.hasLineDirectives()) {
1489 assert(LineTable && "Can't have linetable entries without a LineTable!");
1490 // See if there is a #line directive before this. If so, get it.
1491 if (const LineEntry *Entry =
1492 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1493 // If the LineEntry indicates a filename, use it.
1494 if (Entry->FilenameID != -1)
1495 Filename = LineTable->getFilename(Entry->FilenameID);
1497 // Use the line number specified by the LineEntry. This line number may
1498 // be multiple lines down from the line entry. Add the difference in
1499 // physical line numbers from the query point and the line marker to the
1501 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1502 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1504 // Note that column numbers are not molested by line markers.
1506 // Handle virtual #include manipulation.
1507 if (Entry->IncludeOffset) {
1508 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1509 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1514 return PresumedLoc(Filename.data(), LineNo, ColNo, IncludeLoc);
1517 /// \brief Returns whether the PresumedLoc for a given SourceLocation is
1518 /// in the main file.
1520 /// This computes the "presumed" location for a SourceLocation, then checks
1521 /// whether it came from a file other than the main file. This is different
1522 /// from isWrittenInMainFile() because it takes line marker directives into
1524 bool SourceManager::isInMainFile(SourceLocation Loc) const {
1525 if (Loc.isInvalid()) return false;
1527 // Presumed locations are always for expansion points.
1528 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1530 bool Invalid = false;
1531 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1532 if (Invalid || !Entry.isFile())
1535 const SrcMgr::FileInfo &FI = Entry.getFile();
1537 // Check if there is a line directive for this location.
1538 if (FI.hasLineDirectives())
1539 if (const LineEntry *Entry =
1540 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1541 if (Entry->IncludeOffset)
1544 return FI.getIncludeLoc().isInvalid();
1547 /// \brief The size of the SLocEntry that \p FID represents.
1548 unsigned SourceManager::getFileIDSize(FileID FID) const {
1549 bool Invalid = false;
1550 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1555 unsigned NextOffset;
1556 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1557 NextOffset = getNextLocalOffset();
1558 else if (ID+1 == -1)
1559 NextOffset = MaxLoadedOffset;
1561 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1563 return NextOffset - Entry.getOffset() - 1;
1566 //===----------------------------------------------------------------------===//
1567 // Other miscellaneous methods.
1568 //===----------------------------------------------------------------------===//
1570 /// \brief Retrieve the inode for the given file entry, if possible.
1572 /// This routine involves a system call, and therefore should only be used
1573 /// in non-performance-critical code.
1574 static Optional<llvm::sys::fs::UniqueID>
1575 getActualFileUID(const FileEntry *File) {
1579 llvm::sys::fs::UniqueID ID;
1580 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1586 /// \brief Get the source location for the given file:line:col triplet.
1588 /// If the source file is included multiple times, the source location will
1589 /// be based upon an arbitrary inclusion.
1590 SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1592 unsigned Col) const {
1593 assert(SourceFile && "Null source file!");
1594 assert(Line && Col && "Line and column should start from 1!");
1596 FileID FirstFID = translateFile(SourceFile);
1597 return translateLineCol(FirstFID, Line, Col);
1600 /// \brief Get the FileID for the given file.
1602 /// If the source file is included multiple times, the FileID will be the
1603 /// first inclusion.
1604 FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1605 assert(SourceFile && "Null source file!");
1607 // Find the first file ID that corresponds to the given file.
1610 // First, check the main file ID, since it is common to look for a
1611 // location in the main file.
1612 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1613 Optional<StringRef> SourceFileName;
1614 if (MainFileID.isValid()) {
1615 bool Invalid = false;
1616 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1620 if (MainSLoc.isFile()) {
1621 const ContentCache *MainContentCache
1622 = MainSLoc.getFile().getContentCache();
1623 if (!MainContentCache) {
1624 // Can't do anything
1625 } else if (MainContentCache->OrigEntry == SourceFile) {
1626 FirstFID = MainFileID;
1628 // Fall back: check whether we have the same base name and inode
1629 // as the main file.
1630 const FileEntry *MainFile = MainContentCache->OrigEntry;
1631 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1632 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1633 SourceFileUID = getActualFileUID(SourceFile);
1634 if (SourceFileUID) {
1635 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1636 getActualFileUID(MainFile)) {
1637 if (*SourceFileUID == *MainFileUID) {
1638 FirstFID = MainFileID;
1639 SourceFile = MainFile;
1648 if (FirstFID.isInvalid()) {
1649 // The location we're looking for isn't in the main file; look
1650 // through all of the local source locations.
1651 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1652 bool Invalid = false;
1653 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1657 if (SLoc.isFile() &&
1658 SLoc.getFile().getContentCache() &&
1659 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1660 FirstFID = FileID::get(I);
1664 // If that still didn't help, try the modules.
1665 if (FirstFID.isInvalid()) {
1666 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1667 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1668 if (SLoc.isFile() &&
1669 SLoc.getFile().getContentCache() &&
1670 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1671 FirstFID = FileID::get(-int(I) - 2);
1678 // If we haven't found what we want yet, try again, but this time stat()
1679 // each of the files in case the files have changed since we originally
1681 if (FirstFID.isInvalid() &&
1683 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1684 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
1685 bool Invalid = false;
1686 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1689 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1693 if (SLoc.isFile()) {
1694 const ContentCache *FileContentCache
1695 = SLoc.getFile().getContentCache();
1696 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1699 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1700 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1701 getActualFileUID(Entry)) {
1702 if (*SourceFileUID == *EntryUID) {
1703 FirstFID = FileID::get(I);
1717 /// \brief Get the source location in \arg FID for the given line:col.
1718 /// Returns null location if \arg FID is not a file SLocEntry.
1719 SourceLocation SourceManager::translateLineCol(FileID FID,
1721 unsigned Col) const {
1722 // Lines are used as a one-based index into a zero-based array. This assert
1723 // checks for possible buffer underruns.
1724 assert(Line && Col && "Line and column should start from 1!");
1726 if (FID.isInvalid())
1727 return SourceLocation();
1729 bool Invalid = false;
1730 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1732 return SourceLocation();
1734 if (!Entry.isFile())
1735 return SourceLocation();
1737 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1739 if (Line == 1 && Col == 1)
1742 ContentCache *Content
1743 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1745 return SourceLocation();
1747 // If this is the first use of line information for this buffer, compute the
1748 // SourceLineCache for it on demand.
1749 if (!Content->SourceLineCache) {
1750 bool MyInvalid = false;
1751 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1753 return SourceLocation();
1756 if (Line > Content->NumLines) {
1757 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1760 return FileLoc.getLocWithOffset(Size);
1763 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1764 unsigned FilePos = Content->SourceLineCache[Line - 1];
1765 const char *Buf = Buffer->getBufferStart() + FilePos;
1766 unsigned BufLength = Buffer->getBufferSize() - FilePos;
1768 return FileLoc.getLocWithOffset(FilePos);
1772 // Check that the given column is valid.
1773 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1775 return FileLoc.getLocWithOffset(FilePos + i);
1778 /// \brief Compute a map of macro argument chunks to their expanded source
1779 /// location. Chunks that are not part of a macro argument will map to an
1780 /// invalid source location. e.g. if a file contains one macro argument at
1781 /// offset 100 with length 10, this is how the map will be formed:
1782 /// 0 -> SourceLocation()
1783 /// 100 -> Expanded macro arg location
1784 /// 110 -> SourceLocation()
1785 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1787 assert(FID.isValid());
1789 // Initially no macro argument chunk is present.
1790 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1795 // Stop if there are no more FileIDs to check.
1797 if (unsigned(ID) >= local_sloc_entry_size())
1799 } else if (ID == -1) {
1803 bool Invalid = false;
1804 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1807 if (Entry.isFile()) {
1808 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1809 if (IncludeLoc.isInvalid())
1811 if (!isInFileID(IncludeLoc, FID))
1812 return; // No more files/macros that may be "contained" in this file.
1814 // Skip the files/macros of the #include'd file, we only care about macros
1815 // that lexed macro arguments from our file.
1816 if (Entry.getFile().NumCreatedFIDs)
1817 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1821 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1823 if (ExpInfo.getExpansionLocStart().isFileID()) {
1824 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1825 return; // No more files/macros that may be "contained" in this file.
1828 if (!ExpInfo.isMacroArgExpansion())
1831 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1832 ExpInfo.getSpellingLoc(),
1833 SourceLocation::getMacroLoc(Entry.getOffset()),
1834 getFileIDSize(FileID::get(ID)));
1838 void SourceManager::associateFileChunkWithMacroArgExp(
1839 MacroArgsMap &MacroArgsCache,
1841 SourceLocation SpellLoc,
1842 SourceLocation ExpansionLoc,
1843 unsigned ExpansionLength) const {
1844 if (!SpellLoc.isFileID()) {
1845 unsigned SpellBeginOffs = SpellLoc.getOffset();
1846 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1848 // The spelling range for this macro argument expansion can span multiple
1849 // consecutive FileID entries. Go through each entry contained in the
1850 // spelling range and if one is itself a macro argument expansion, recurse
1851 // and associate the file chunk that it represents.
1853 FileID SpellFID; // Current FileID in the spelling range.
1854 unsigned SpellRelativeOffs;
1855 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1857 const SLocEntry &Entry = getSLocEntry(SpellFID);
1858 unsigned SpellFIDBeginOffs = Entry.getOffset();
1859 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1860 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1861 const ExpansionInfo &Info = Entry.getExpansion();
1862 if (Info.isMacroArgExpansion()) {
1863 unsigned CurrSpellLength;
1864 if (SpellFIDEndOffs < SpellEndOffs)
1865 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1867 CurrSpellLength = ExpansionLength;
1868 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1869 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1870 ExpansionLoc, CurrSpellLength);
1873 if (SpellFIDEndOffs >= SpellEndOffs)
1874 return; // we covered all FileID entries in the spelling range.
1876 // Move to the next FileID entry in the spelling range.
1877 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1878 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1879 ExpansionLength -= advance;
1881 SpellRelativeOffs = 0;
1886 assert(SpellLoc.isFileID());
1889 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1892 unsigned EndOffs = BeginOffs + ExpansionLength;
1894 // Add a new chunk for this macro argument. A previous macro argument chunk
1895 // may have been lexed again, so e.g. if the map is
1896 // 0 -> SourceLocation()
1897 // 100 -> Expanded loc #1
1898 // 110 -> SourceLocation()
1899 // and we found a new macro FileID that lexed from offet 105 with length 3,
1900 // the new map will be:
1901 // 0 -> SourceLocation()
1902 // 100 -> Expanded loc #1
1903 // 105 -> Expanded loc #2
1904 // 108 -> Expanded loc #1
1905 // 110 -> SourceLocation()
1907 // Since re-lexed macro chunks will always be the same size or less of
1908 // previous chunks, we only need to find where the ending of the new macro
1909 // chunk is mapped to and update the map with new begin/end mappings.
1911 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1913 SourceLocation EndOffsMappedLoc = I->second;
1914 MacroArgsCache[BeginOffs] = ExpansionLoc;
1915 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1918 /// \brief If \arg Loc points inside a function macro argument, the returned
1919 /// location will be the macro location in which the argument was expanded.
1920 /// If a macro argument is used multiple times, the expanded location will
1921 /// be at the first expansion of the argument.
1925 /// Passing a file location pointing at 'foo', will yield a macro location
1926 /// where 'foo' was expanded into.
1928 SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1929 if (Loc.isInvalid() || !Loc.isFileID())
1934 std::tie(FID, Offset) = getDecomposedLoc(Loc);
1935 if (FID.isInvalid())
1938 std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1939 if (!MacroArgsCache) {
1940 MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1941 computeMacroArgsCache(*MacroArgsCache, FID);
1944 assert(!MacroArgsCache->empty());
1945 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1948 unsigned MacroArgBeginOffs = I->first;
1949 SourceLocation MacroArgExpandedLoc = I->second;
1950 if (MacroArgExpandedLoc.isValid())
1951 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1956 std::pair<FileID, unsigned>
1957 SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1958 if (FID.isInvalid())
1959 return std::make_pair(FileID(), 0);
1961 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1963 typedef std::pair<FileID, unsigned> DecompTy;
1964 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1965 std::pair<MapTy::iterator, bool>
1966 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1967 DecompTy &DecompLoc = InsertOp.first->second;
1968 if (!InsertOp.second)
1969 return DecompLoc; // already in map.
1971 SourceLocation UpperLoc;
1972 bool Invalid = false;
1973 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1975 if (Entry.isExpansion())
1976 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1978 UpperLoc = Entry.getFile().getIncludeLoc();
1981 if (UpperLoc.isValid())
1982 DecompLoc = getDecomposedLoc(UpperLoc);
1987 /// Given a decomposed source location, move it up the include/expansion stack
1988 /// to the parent source location. If this is possible, return the decomposed
1989 /// version of the parent in Loc and return false. If Loc is the top-level
1990 /// entry, return true and don't modify it.
1991 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1992 const SourceManager &SM) {
1993 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1994 if (UpperLoc.first.isInvalid())
1995 return true; // We reached the top.
2001 /// Return the cache entry for comparing the given file IDs
2002 /// for isBeforeInTranslationUnit.
2003 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2004 FileID RFID) const {
2005 // This is a magic number for limiting the cache size. It was experimentally
2006 // derived from a small Objective-C project (where the cache filled
2007 // out to ~250 items). We can make it larger if necessary.
2008 enum { MagicCacheSize = 300 };
2009 IsBeforeInTUCacheKey Key(LFID, RFID);
2011 // If the cache size isn't too large, do a lookup and if necessary default
2012 // construct an entry. We can then return it to the caller for direct
2013 // use. When they update the value, the cache will get automatically
2015 if (IBTUCache.size() < MagicCacheSize)
2016 return IBTUCache[Key];
2018 // Otherwise, do a lookup that will not construct a new value.
2019 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2020 if (I != IBTUCache.end())
2023 // Fall back to the overflow value.
2024 return IBTUCacheOverflow;
2027 /// \brief Determines the order of 2 source locations in the translation unit.
2029 /// \returns true if LHS source location comes before RHS, false otherwise.
2030 bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2031 SourceLocation RHS) const {
2032 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2036 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2037 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2039 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2040 // is a serialized one referring to a file that was removed after we loaded
2042 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2043 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2045 // If the source locations are in the same file, just compare offsets.
2046 if (LOffs.first == ROffs.first)
2047 return 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 IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2059 // Okay, we missed in the cache, start updating the cache for this query.
2060 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2061 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2063 // We need to find the common ancestor. The only way of doing this is to
2064 // build the complete include chain for one and then walking up the chain
2065 // of the other looking for a match.
2066 // We use a map from FileID to Offset to store the chain. Easier than writing
2067 // a custom set hash info that only depends on the first part of a pair.
2068 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
2071 LChain.insert(LOffs);
2072 // We catch the case where LOffs is in a file included by ROffs and
2073 // quit early. The other way round unfortunately remains suboptimal.
2074 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2076 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2077 if (MoveUpIncludeHierarchy(ROffs, *this))
2078 break; // Met at topmost file.
2080 if (I != LChain.end())
2083 // If we exited because we found a nearest common ancestor, compare the
2084 // locations within the common file and cache them.
2085 if (LOffs.first == ROffs.first) {
2086 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2087 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
2090 // If we arrived here, the location is either in a built-ins buffer or
2091 // associated with global inline asm. PR5662 and PR22576 are examples.
2093 // Clear the lookup cache, it depends on a common location.
2094 IsBeforeInTUCache.clear();
2095 StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2096 StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2097 bool LIsBuiltins = LB == "<built-in>";
2098 bool RIsBuiltins = RB == "<built-in>";
2099 // Sort built-in before non-built-in.
2100 if (LIsBuiltins || RIsBuiltins) {
2101 if (LIsBuiltins != RIsBuiltins)
2103 // Both are in built-in buffers, but from different files. We just claim that
2104 // lower IDs come first.
2105 return LOffs.first < ROffs.first;
2107 bool LIsAsm = LB == "<inline asm>";
2108 bool RIsAsm = RB == "<inline asm>";
2109 // Sort assembler after built-ins, but before the rest.
2110 if (LIsAsm || RIsAsm) {
2111 if (LIsAsm != RIsAsm)
2113 assert(LOffs.first == ROffs.first);
2116 bool LIsScratch = LB == "<scratch space>";
2117 bool RIsScratch = RB == "<scratch space>";
2118 // Sort scratch after inline asm, but before the rest.
2119 if (LIsScratch || RIsScratch) {
2120 if (LIsScratch != RIsScratch)
2122 return LOffs.second < ROffs.second;
2124 llvm_unreachable("Unsortable locations found");
2127 void SourceManager::PrintStats() const {
2128 llvm::errs() << "\n*** Source Manager Stats:\n";
2129 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2130 << " mem buffers mapped.\n";
2131 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2132 << llvm::capacity_in_bytes(LocalSLocEntryTable)
2133 << " bytes of capacity), "
2134 << NextLocalOffset << "B of Sloc address space used.\n";
2135 llvm::errs() << LoadedSLocEntryTable.size()
2136 << " loaded SLocEntries allocated, "
2137 << MaxLoadedOffset - CurrentLoadedOffset
2138 << "B of Sloc address space used.\n";
2140 unsigned NumLineNumsComputed = 0;
2141 unsigned NumFileBytesMapped = 0;
2142 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2143 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2144 NumFileBytesMapped += I->second->getSizeBytesMapped();
2146 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2148 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2149 << NumLineNumsComputed << " files with line #'s computed, "
2150 << NumMacroArgsComputed << " files with macro args computed.\n";
2151 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2152 << NumBinaryProbes << " binary.\n";
2155 LLVM_DUMP_METHOD void SourceManager::dump() const {
2156 llvm::raw_ostream &out = llvm::errs();
2158 auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2159 llvm::Optional<unsigned> NextStart) {
2160 out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2161 << " <SourceLocation " << Entry.getOffset() << ":";
2163 out << *NextStart << ">\n";
2166 if (Entry.isFile()) {
2167 auto &FI = Entry.getFile();
2168 if (FI.NumCreatedFIDs)
2169 out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2171 if (FI.getIncludeLoc().isValid())
2172 out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2173 if (auto *CC = FI.getContentCache()) {
2174 out << " for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2176 if (CC->BufferOverridden)
2177 out << " contents overridden\n";
2178 if (CC->ContentsEntry != CC->OrigEntry) {
2179 out << " contents from "
2180 << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2185 auto &EI = Entry.getExpansion();
2186 out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2187 out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2188 << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2189 << EI.getExpansionLocEnd().getOffset() << ">\n";
2193 // Dump local SLocEntries.
2194 for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2195 DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2196 ID == NumIDs - 1 ? NextLocalOffset
2197 : LocalSLocEntryTable[ID + 1].getOffset());
2199 // Dump loaded SLocEntries.
2200 llvm::Optional<unsigned> NextStart;
2201 for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2202 int ID = -(int)Index - 2;
2203 if (SLocEntryLoaded[Index]) {
2204 DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2205 NextStart = LoadedSLocEntryTable[Index].getOffset();
2212 ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
2214 /// Return the amount of memory used by memory buffers, breaking down
2215 /// by heap-backed versus mmap'ed memory.
2216 SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2217 size_t malloc_bytes = 0;
2218 size_t mmap_bytes = 0;
2220 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2221 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2222 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2223 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2224 mmap_bytes += sized_mapped;
2226 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2227 malloc_bytes += sized_mapped;
2231 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2234 size_t SourceManager::getDataStructureSizes() const {
2235 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2236 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2237 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2238 + llvm::capacity_in_bytes(SLocEntryLoaded)
2239 + llvm::capacity_in_bytes(FileInfos);
2241 if (OverriddenFilesInfo)
2242 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);