10b57cec5SDimitry Andric //===- SourceManager.cpp - Track and cache source files -------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the SourceManager interface. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 140b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 150b57cec5SDimitry Andric #include "clang/Basic/FileManager.h" 160b57cec5SDimitry Andric #include "clang/Basic/LLVM.h" 170b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h" 180b57cec5SDimitry Andric #include "clang/Basic/SourceManagerInternals.h" 190b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 20bdd1243dSDimitry Andric #include "llvm/ADT/MapVector.h" 210b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 220b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 23*0fca6ea1SDimitry Andric #include "llvm/ADT/Statistic.h" 240b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 255ffd83dbSDimitry Andric #include "llvm/ADT/StringSwitch.h" 260b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 270b57cec5SDimitry Andric #include "llvm/Support/Capacity.h" 280b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 29fe6060f1SDimitry Andric #include "llvm/Support/Endian.h" 300b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 310b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h" 320b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 330b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h" 340b57cec5SDimitry Andric #include "llvm/Support/Path.h" 350b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 360b57cec5SDimitry Andric #include <algorithm> 370b57cec5SDimitry Andric #include <cassert> 380b57cec5SDimitry Andric #include <cstddef> 390b57cec5SDimitry Andric #include <cstdint> 400b57cec5SDimitry Andric #include <memory> 41bdd1243dSDimitry Andric #include <optional> 420b57cec5SDimitry Andric #include <tuple> 430b57cec5SDimitry Andric #include <utility> 440b57cec5SDimitry Andric #include <vector> 450b57cec5SDimitry Andric 460b57cec5SDimitry Andric using namespace clang; 470b57cec5SDimitry Andric using namespace SrcMgr; 480b57cec5SDimitry Andric using llvm::MemoryBuffer; 490b57cec5SDimitry Andric 50*0fca6ea1SDimitry Andric #define DEBUG_TYPE "source-manager" 51*0fca6ea1SDimitry Andric 52*0fca6ea1SDimitry Andric // Reaching a limit of 2^31 results in a hard error. This metric allows to track 53*0fca6ea1SDimitry Andric // if particular invocation of the compiler is close to it. 54*0fca6ea1SDimitry Andric STATISTIC(MaxUsedSLocBytes, "Maximum number of bytes used by source locations " 55*0fca6ea1SDimitry Andric "(both loaded and local)."); 56*0fca6ea1SDimitry Andric 570b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 580b57cec5SDimitry Andric // SourceManager Helper Classes 590b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 600b57cec5SDimitry Andric 610b57cec5SDimitry Andric /// getSizeBytesMapped - Returns the number of bytes actually mapped for this 620b57cec5SDimitry Andric /// ContentCache. This can be 0 if the MemBuffer was not actually expanded. 630b57cec5SDimitry Andric unsigned ContentCache::getSizeBytesMapped() const { 64e8d8bef9SDimitry Andric return Buffer ? Buffer->getBufferSize() : 0; 650b57cec5SDimitry Andric } 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric /// Returns the kind of memory used to back the memory buffer for 680b57cec5SDimitry Andric /// this content cache. This is used for performance analysis. 690b57cec5SDimitry Andric llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const { 705e801ac6SDimitry Andric if (Buffer == nullptr) { 715e801ac6SDimitry Andric assert(0 && "Buffer should never be null"); 720b57cec5SDimitry Andric return llvm::MemoryBuffer::MemoryBuffer_Malloc; 735e801ac6SDimitry Andric } 74e8d8bef9SDimitry Andric return Buffer->getBufferKind(); 750b57cec5SDimitry Andric } 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric /// getSize - Returns the size of the content encapsulated by this ContentCache. 780b57cec5SDimitry Andric /// This can be the size of the source file or the size of an arbitrary 790b57cec5SDimitry Andric /// scratch buffer. If the ContentCache encapsulates a source file, that 800b57cec5SDimitry Andric /// file is not lazily brought in from disk to satisfy this query. 810b57cec5SDimitry Andric unsigned ContentCache::getSize() const { 82e8d8bef9SDimitry Andric return Buffer ? (unsigned)Buffer->getBufferSize() 830b57cec5SDimitry Andric : (unsigned)ContentsEntry->getSize(); 840b57cec5SDimitry Andric } 850b57cec5SDimitry Andric 86480093f4SDimitry Andric const char *ContentCache::getInvalidBOM(StringRef BufStr) { 87480093f4SDimitry Andric // If the buffer is valid, check to see if it has a UTF Byte Order Mark 88480093f4SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See 89480093f4SDimitry Andric // http://en.wikipedia.org/wiki/Byte_order_mark for more information. 90480093f4SDimitry Andric const char *InvalidBOM = 91480093f4SDimitry Andric llvm::StringSwitch<const char *>(BufStr) 92480093f4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"), 93480093f4SDimitry Andric "UTF-32 (BE)") 94480093f4SDimitry Andric .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"), 95480093f4SDimitry Andric "UTF-32 (LE)") 96480093f4SDimitry Andric .StartsWith("\xFE\xFF", "UTF-16 (BE)") 97480093f4SDimitry Andric .StartsWith("\xFF\xFE", "UTF-16 (LE)") 98480093f4SDimitry Andric .StartsWith("\x2B\x2F\x76", "UTF-7") 99480093f4SDimitry Andric .StartsWith("\xF7\x64\x4C", "UTF-1") 100480093f4SDimitry Andric .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC") 101480093f4SDimitry Andric .StartsWith("\x0E\xFE\xFF", "SCSU") 102480093f4SDimitry Andric .StartsWith("\xFB\xEE\x28", "BOCU-1") 103480093f4SDimitry Andric .StartsWith("\x84\x31\x95\x33", "GB-18030") 104480093f4SDimitry Andric .Default(nullptr); 105480093f4SDimitry Andric 106480093f4SDimitry Andric return InvalidBOM; 107480093f4SDimitry Andric } 108480093f4SDimitry Andric 109bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> 110e8d8bef9SDimitry Andric ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM, 111e8d8bef9SDimitry Andric SourceLocation Loc) const { 1120b57cec5SDimitry Andric // Lazily create the Buffer for ContentCaches that wrap files. If we already 1130b57cec5SDimitry Andric // computed it, just return what we have. 114e8d8bef9SDimitry Andric if (IsBufferInvalid) 115bdd1243dSDimitry Andric return std::nullopt; 116e8d8bef9SDimitry Andric if (Buffer) 117e8d8bef9SDimitry Andric return Buffer->getMemBufferRef(); 118e8d8bef9SDimitry Andric if (!ContentsEntry) 119bdd1243dSDimitry Andric return std::nullopt; 1200b57cec5SDimitry Andric 121e8d8bef9SDimitry Andric // Start with the assumption that the buffer is invalid to simplify early 122e8d8bef9SDimitry Andric // return paths. 123e8d8bef9SDimitry Andric IsBufferInvalid = true; 1240b57cec5SDimitry Andric 1255f757f3fSDimitry Andric auto BufferOrError = FM.getBufferForFile(*ContentsEntry, IsFileVolatile); 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric // If we were unable to open the file, then we are in an inconsistent 1280b57cec5SDimitry Andric // situation where the content cache referenced a file which no longer 1290b57cec5SDimitry Andric // exists. Most likely, we were using a stat cache with an invalid entry but 1300b57cec5SDimitry Andric // the file could also have been removed during processing. Since we can't 1310b57cec5SDimitry Andric // really deal with this situation, just create an empty buffer. 1320b57cec5SDimitry Andric if (!BufferOrError) { 1330b57cec5SDimitry Andric if (Diag.isDiagnosticInFlight()) 1340b57cec5SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_cannot_open_file, 1350b57cec5SDimitry Andric ContentsEntry->getName(), 1360b57cec5SDimitry Andric BufferOrError.getError().message()); 1370b57cec5SDimitry Andric else 1380b57cec5SDimitry Andric Diag.Report(Loc, diag::err_cannot_open_file) 1390b57cec5SDimitry Andric << ContentsEntry->getName() << BufferOrError.getError().message(); 1400b57cec5SDimitry Andric 141bdd1243dSDimitry Andric return std::nullopt; 1420b57cec5SDimitry Andric } 1430b57cec5SDimitry Andric 144e8d8bef9SDimitry Andric Buffer = std::move(*BufferOrError); 1450b57cec5SDimitry Andric 146e8d8bef9SDimitry Andric // Check that the file's size fits in an 'unsigned' (with room for a 147e8d8bef9SDimitry Andric // past-the-end value). This is deeply regrettable, but various parts of 148e8d8bef9SDimitry Andric // Clang (including elsewhere in this file!) use 'unsigned' to represent file 149e8d8bef9SDimitry Andric // offsets, line numbers, string literal lengths, and so on, and fail 150e8d8bef9SDimitry Andric // miserably on large source files. 151e8d8bef9SDimitry Andric // 152e8d8bef9SDimitry Andric // Note: ContentsEntry could be a named pipe, in which case 153e8d8bef9SDimitry Andric // ContentsEntry::getSize() could have the wrong size. Use 154e8d8bef9SDimitry Andric // MemoryBuffer::getBufferSize() instead. 155e8d8bef9SDimitry Andric if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) { 156e8d8bef9SDimitry Andric if (Diag.isDiagnosticInFlight()) 157e8d8bef9SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_file_too_large, 158e8d8bef9SDimitry Andric ContentsEntry->getName()); 159e8d8bef9SDimitry Andric else 160e8d8bef9SDimitry Andric Diag.Report(Loc, diag::err_file_too_large) 161e8d8bef9SDimitry Andric << ContentsEntry->getName(); 162e8d8bef9SDimitry Andric 163bdd1243dSDimitry Andric return std::nullopt; 164e8d8bef9SDimitry Andric } 165e8d8bef9SDimitry Andric 166e8d8bef9SDimitry Andric // Unless this is a named pipe (in which case we can handle a mismatch), 167e8d8bef9SDimitry Andric // check that the file's size is the same as in the file entry (which may 1680b57cec5SDimitry Andric // have come from a stat cache). 169e8d8bef9SDimitry Andric if (!ContentsEntry->isNamedPipe() && 170e8d8bef9SDimitry Andric Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) { 1710b57cec5SDimitry Andric if (Diag.isDiagnosticInFlight()) 1720b57cec5SDimitry Andric Diag.SetDelayedDiagnostic(diag::err_file_modified, 1730b57cec5SDimitry Andric ContentsEntry->getName()); 1740b57cec5SDimitry Andric else 1750b57cec5SDimitry Andric Diag.Report(Loc, diag::err_file_modified) 1760b57cec5SDimitry Andric << ContentsEntry->getName(); 1770b57cec5SDimitry Andric 178bdd1243dSDimitry Andric return std::nullopt; 1790b57cec5SDimitry Andric } 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric // If the buffer is valid, check to see if it has a UTF Byte Order Mark 1820b57cec5SDimitry Andric // (BOM). We only support UTF-8 with and without a BOM right now. See 1830b57cec5SDimitry Andric // http://en.wikipedia.org/wiki/Byte_order_mark for more information. 184e8d8bef9SDimitry Andric StringRef BufStr = Buffer->getBuffer(); 185480093f4SDimitry Andric const char *InvalidBOM = getInvalidBOM(BufStr); 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric if (InvalidBOM) { 1880b57cec5SDimitry Andric Diag.Report(Loc, diag::err_unsupported_bom) 1890b57cec5SDimitry Andric << InvalidBOM << ContentsEntry->getName(); 190bdd1243dSDimitry Andric return std::nullopt; 1910b57cec5SDimitry Andric } 1920b57cec5SDimitry Andric 193e8d8bef9SDimitry Andric // Buffer has been validated. 194e8d8bef9SDimitry Andric IsBufferInvalid = false; 195e8d8bef9SDimitry Andric return Buffer->getMemBufferRef(); 1960b57cec5SDimitry Andric } 1970b57cec5SDimitry Andric 1980b57cec5SDimitry Andric unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) { 1990b57cec5SDimitry Andric auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size()); 2000b57cec5SDimitry Andric if (IterBool.second) 2010b57cec5SDimitry Andric FilenamesByID.push_back(&*IterBool.first); 2020b57cec5SDimitry Andric return IterBool.first->second; 2030b57cec5SDimitry Andric } 2040b57cec5SDimitry Andric 2050b57cec5SDimitry Andric /// Add a line note to the line table that indicates that there is a \#line or 2060b57cec5SDimitry Andric /// GNU line marker at the specified FID/Offset location which changes the 2070b57cec5SDimitry Andric /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't 2080b57cec5SDimitry Andric /// change the presumed \#include stack. If it is 1, this is a file entry, if 2090b57cec5SDimitry Andric /// it is 2 then this is a file exit. FileKind specifies whether this is a 2100b57cec5SDimitry Andric /// system header or extern C system header. 2110b57cec5SDimitry Andric void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, 2120b57cec5SDimitry Andric int FilenameID, unsigned EntryExit, 2130b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileKind) { 2140b57cec5SDimitry Andric std::vector<LineEntry> &Entries = LineEntries[FID]; 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric assert((Entries.empty() || Entries.back().FileOffset < Offset) && 2170b57cec5SDimitry Andric "Adding line entries out of order!"); 2180b57cec5SDimitry Andric 2190b57cec5SDimitry Andric unsigned IncludeOffset = 0; 220349cc55cSDimitry Andric if (EntryExit == 1) { 221349cc55cSDimitry Andric // Push #include 2220b57cec5SDimitry Andric IncludeOffset = Offset-1; 223349cc55cSDimitry Andric } else { 224349cc55cSDimitry Andric const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back(); 225349cc55cSDimitry Andric if (EntryExit == 2) { 226349cc55cSDimitry Andric // Pop #include 227349cc55cSDimitry Andric assert(PrevEntry && PrevEntry->IncludeOffset && 228349cc55cSDimitry Andric "PPDirectives should have caught case when popping empty include " 229349cc55cSDimitry Andric "stack"); 230349cc55cSDimitry Andric PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset); 231349cc55cSDimitry Andric } 232349cc55cSDimitry Andric if (PrevEntry) { 2330b57cec5SDimitry Andric IncludeOffset = PrevEntry->IncludeOffset; 234349cc55cSDimitry Andric if (FilenameID == -1) { 235349cc55cSDimitry Andric // An unspecified FilenameID means use the previous (or containing) 236349cc55cSDimitry Andric // filename if available, or the main source file otherwise. 237349cc55cSDimitry Andric FilenameID = PrevEntry->FilenameID; 238349cc55cSDimitry Andric } 239349cc55cSDimitry Andric } 2400b57cec5SDimitry Andric } 2410b57cec5SDimitry Andric 2420b57cec5SDimitry Andric Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, 2430b57cec5SDimitry Andric IncludeOffset)); 2440b57cec5SDimitry Andric } 2450b57cec5SDimitry Andric 2460b57cec5SDimitry Andric /// FindNearestLineEntry - Find the line entry nearest to FID that is before 2470b57cec5SDimitry Andric /// it. If there is no line entry before Offset in FID, return null. 2480b57cec5SDimitry Andric const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID, 2490b57cec5SDimitry Andric unsigned Offset) { 2500b57cec5SDimitry Andric const std::vector<LineEntry> &Entries = LineEntries[FID]; 2510b57cec5SDimitry Andric assert(!Entries.empty() && "No #line entries for this FID after all!"); 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric // It is very common for the query to be after the last #line, check this 2540b57cec5SDimitry Andric // first. 2550b57cec5SDimitry Andric if (Entries.back().FileOffset <= Offset) 2560b57cec5SDimitry Andric return &Entries.back(); 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric // Do a binary search to find the maximal element that is still before Offset. 2590b57cec5SDimitry Andric std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset); 2600b57cec5SDimitry Andric if (I == Entries.begin()) 2610b57cec5SDimitry Andric return nullptr; 2620b57cec5SDimitry Andric return &*--I; 2630b57cec5SDimitry Andric } 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric /// Add a new line entry that has already been encoded into 2660b57cec5SDimitry Andric /// the internal representation of the line table. 2670b57cec5SDimitry Andric void LineTableInfo::AddEntry(FileID FID, 2680b57cec5SDimitry Andric const std::vector<LineEntry> &Entries) { 2690b57cec5SDimitry Andric LineEntries[FID] = Entries; 2700b57cec5SDimitry Andric } 2710b57cec5SDimitry Andric 2720b57cec5SDimitry Andric /// getLineTableFilenameID - Return the uniqued ID for the specified filename. 2730b57cec5SDimitry Andric unsigned SourceManager::getLineTableFilenameID(StringRef Name) { 2740b57cec5SDimitry Andric return getLineTable().getLineTableFilenameID(Name); 2750b57cec5SDimitry Andric } 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric /// AddLineNote - Add a line note to the line table for the FileID and offset 2780b57cec5SDimitry Andric /// specified by Loc. If FilenameID is -1, it is considered to be 2790b57cec5SDimitry Andric /// unspecified. 2800b57cec5SDimitry Andric void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 2810b57cec5SDimitry Andric int FilenameID, bool IsFileEntry, 2820b57cec5SDimitry Andric bool IsFileExit, 2830b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileKind) { 2840b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric bool Invalid = false; 287*0fca6ea1SDimitry Andric SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); 2880b57cec5SDimitry Andric if (!Entry.isFile() || Invalid) 2890b57cec5SDimitry Andric return; 2900b57cec5SDimitry Andric 291*0fca6ea1SDimitry Andric SrcMgr::FileInfo &FileInfo = Entry.getFile(); 2920b57cec5SDimitry Andric 2930b57cec5SDimitry Andric // Remember that this file has #line directives now if it doesn't already. 294*0fca6ea1SDimitry Andric FileInfo.setHasLineDirectives(); 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric (void) getLineTable(); 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric unsigned EntryExit = 0; 2990b57cec5SDimitry Andric if (IsFileEntry) 3000b57cec5SDimitry Andric EntryExit = 1; 3010b57cec5SDimitry Andric else if (IsFileExit) 3020b57cec5SDimitry Andric EntryExit = 2; 3030b57cec5SDimitry Andric 3040b57cec5SDimitry Andric LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID, 3050b57cec5SDimitry Andric EntryExit, FileKind); 3060b57cec5SDimitry Andric } 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric LineTableInfo &SourceManager::getLineTable() { 3090b57cec5SDimitry Andric if (!LineTable) 3100b57cec5SDimitry Andric LineTable.reset(new LineTableInfo()); 3110b57cec5SDimitry Andric return *LineTable; 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 3150b57cec5SDimitry Andric // Private 'Create' methods. 3160b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr, 3190b57cec5SDimitry Andric bool UserFilesAreVolatile) 3200b57cec5SDimitry Andric : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) { 3210b57cec5SDimitry Andric clearIDTables(); 3220b57cec5SDimitry Andric Diag.setSourceManager(this); 3230b57cec5SDimitry Andric } 3240b57cec5SDimitry Andric 3250b57cec5SDimitry Andric SourceManager::~SourceManager() { 3260b57cec5SDimitry Andric // Delete FileEntry objects corresponding to content caches. Since the actual 3270b57cec5SDimitry Andric // content cache objects are bump pointer allocated, we just have to run the 3280b57cec5SDimitry Andric // dtors, but we call the deallocate method for completeness. 3290b57cec5SDimitry Andric for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { 3300b57cec5SDimitry Andric if (MemBufferInfos[i]) { 3310b57cec5SDimitry Andric MemBufferInfos[i]->~ContentCache(); 3320b57cec5SDimitry Andric ContentCacheAlloc.Deallocate(MemBufferInfos[i]); 3330b57cec5SDimitry Andric } 3340b57cec5SDimitry Andric } 3355f757f3fSDimitry Andric for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { 3360b57cec5SDimitry Andric if (I->second) { 3370b57cec5SDimitry Andric I->second->~ContentCache(); 3380b57cec5SDimitry Andric ContentCacheAlloc.Deallocate(I->second); 3390b57cec5SDimitry Andric } 3400b57cec5SDimitry Andric } 3410b57cec5SDimitry Andric } 3420b57cec5SDimitry Andric 3430b57cec5SDimitry Andric void SourceManager::clearIDTables() { 3440b57cec5SDimitry Andric MainFileID = FileID(); 3450b57cec5SDimitry Andric LocalSLocEntryTable.clear(); 3460b57cec5SDimitry Andric LoadedSLocEntryTable.clear(); 3470b57cec5SDimitry Andric SLocEntryLoaded.clear(); 3485f757f3fSDimitry Andric SLocEntryOffsetLoaded.clear(); 3490b57cec5SDimitry Andric LastLineNoFileIDQuery = FileID(); 3500b57cec5SDimitry Andric LastLineNoContentCache = nullptr; 3510b57cec5SDimitry Andric LastFileIDLookup = FileID(); 3520b57cec5SDimitry Andric 3530b57cec5SDimitry Andric if (LineTable) 3540b57cec5SDimitry Andric LineTable->clear(); 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric // Use up FileID #0 as an invalid expansion. 3570b57cec5SDimitry Andric NextLocalOffset = 0; 3580b57cec5SDimitry Andric CurrentLoadedOffset = MaxLoadedOffset; 3590b57cec5SDimitry Andric createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1); 3600b57cec5SDimitry Andric } 3610b57cec5SDimitry Andric 362e8d8bef9SDimitry Andric bool SourceManager::isMainFile(const FileEntry &SourceFile) { 3635ffd83dbSDimitry Andric assert(MainFileID.isValid() && "expected initialized SourceManager"); 364e8d8bef9SDimitry Andric if (auto *FE = getFileEntryForID(MainFileID)) 3655ffd83dbSDimitry Andric return FE->getUID() == SourceFile.getUID(); 366e8d8bef9SDimitry Andric return false; 3675ffd83dbSDimitry Andric } 3685ffd83dbSDimitry Andric 3690b57cec5SDimitry Andric void SourceManager::initializeForReplay(const SourceManager &Old) { 3700b57cec5SDimitry Andric assert(MainFileID.isInvalid() && "expected uninitialized SourceManager"); 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * { 3730b57cec5SDimitry Andric auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache; 3740b57cec5SDimitry Andric Clone->OrigEntry = Cache->OrigEntry; 3750b57cec5SDimitry Andric Clone->ContentsEntry = Cache->ContentsEntry; 3760b57cec5SDimitry Andric Clone->BufferOverridden = Cache->BufferOverridden; 377a7dea167SDimitry Andric Clone->IsFileVolatile = Cache->IsFileVolatile; 3780b57cec5SDimitry Andric Clone->IsTransient = Cache->IsTransient; 379e8d8bef9SDimitry Andric Clone->setUnownedBuffer(Cache->getBufferIfLoaded()); 3800b57cec5SDimitry Andric return Clone; 3810b57cec5SDimitry Andric }; 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric // Ensure all SLocEntries are loaded from the external source. 3840b57cec5SDimitry Andric for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I) 3850b57cec5SDimitry Andric if (!Old.SLocEntryLoaded[I]) 3860b57cec5SDimitry Andric Old.loadSLocEntry(I, nullptr); 3870b57cec5SDimitry Andric 3880b57cec5SDimitry Andric // Inherit any content cache data from the old source manager. 3890b57cec5SDimitry Andric for (auto &FileInfo : Old.FileInfos) { 3900b57cec5SDimitry Andric SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first]; 3910b57cec5SDimitry Andric if (Slot) 3920b57cec5SDimitry Andric continue; 3930b57cec5SDimitry Andric Slot = CloneContentCache(FileInfo.second); 3940b57cec5SDimitry Andric } 3950b57cec5SDimitry Andric } 3960b57cec5SDimitry Andric 397e8d8bef9SDimitry Andric ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt, 3980b57cec5SDimitry Andric bool isSystemFile) { 3990b57cec5SDimitry Andric // Do we already have information about this file? 4000b57cec5SDimitry Andric ContentCache *&Entry = FileInfos[FileEnt]; 401e8d8bef9SDimitry Andric if (Entry) 402e8d8bef9SDimitry Andric return *Entry; 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric // Nope, create a new Cache entry. 4050b57cec5SDimitry Andric Entry = ContentCacheAlloc.Allocate<ContentCache>(); 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric if (OverriddenFilesInfo) { 4080b57cec5SDimitry Andric // If the file contents are overridden with contents from another file, 4090b57cec5SDimitry Andric // pass that file to ContentCache. 410bdd1243dSDimitry Andric auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt); 4110b57cec5SDimitry Andric if (overI == OverriddenFilesInfo->OverriddenFiles.end()) 4120b57cec5SDimitry Andric new (Entry) ContentCache(FileEnt); 4130b57cec5SDimitry Andric else 4140b57cec5SDimitry Andric new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt 4150b57cec5SDimitry Andric : overI->second, 4160b57cec5SDimitry Andric overI->second); 4170b57cec5SDimitry Andric } else { 4180b57cec5SDimitry Andric new (Entry) ContentCache(FileEnt); 4190b57cec5SDimitry Andric } 4200b57cec5SDimitry Andric 421a7dea167SDimitry Andric Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile; 4220b57cec5SDimitry Andric Entry->IsTransient = FilesAreTransient; 423e8d8bef9SDimitry Andric Entry->BufferOverridden |= FileEnt.isNamedPipe(); 4240b57cec5SDimitry Andric 425e8d8bef9SDimitry Andric return *Entry; 4260b57cec5SDimitry Andric } 4270b57cec5SDimitry Andric 4280b57cec5SDimitry Andric /// Create a new ContentCache for the specified memory buffer. 4290b57cec5SDimitry Andric /// This does no caching. 430e8d8bef9SDimitry Andric ContentCache &SourceManager::createMemBufferContentCache( 431e8d8bef9SDimitry Andric std::unique_ptr<llvm::MemoryBuffer> Buffer) { 4320b57cec5SDimitry Andric // Add a new ContentCache to the MemBufferInfos list and return it. 4330b57cec5SDimitry Andric ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(); 4340b57cec5SDimitry Andric new (Entry) ContentCache(); 4350b57cec5SDimitry Andric MemBufferInfos.push_back(Entry); 436e8d8bef9SDimitry Andric Entry->setBuffer(std::move(Buffer)); 437e8d8bef9SDimitry Andric return *Entry; 4380b57cec5SDimitry Andric } 4390b57cec5SDimitry Andric 4400b57cec5SDimitry Andric const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, 4410b57cec5SDimitry Andric bool *Invalid) const { 442*0fca6ea1SDimitry Andric return const_cast<SourceManager *>(this)->loadSLocEntry(Index, Invalid); 443*0fca6ea1SDimitry Andric } 444*0fca6ea1SDimitry Andric 445*0fca6ea1SDimitry Andric SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, bool *Invalid) { 4460b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index]); 4470b57cec5SDimitry Andric if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) { 4480b57cec5SDimitry Andric if (Invalid) 4490b57cec5SDimitry Andric *Invalid = true; 4500b57cec5SDimitry Andric // If the file of the SLocEntry changed we could still have loaded it. 4510b57cec5SDimitry Andric if (!SLocEntryLoaded[Index]) { 4520b57cec5SDimitry Andric // Try to recover; create a SLocEntry so the rest of clang can handle it. 453e8d8bef9SDimitry Andric if (!FakeSLocEntryForRecovery) 454e8d8bef9SDimitry Andric FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get( 455a7dea167SDimitry Andric 0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(), 456e8d8bef9SDimitry Andric SrcMgr::C_User, ""))); 457e8d8bef9SDimitry Andric return *FakeSLocEntryForRecovery; 4580b57cec5SDimitry Andric } 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric 4610b57cec5SDimitry Andric return LoadedSLocEntryTable[Index]; 4620b57cec5SDimitry Andric } 4630b57cec5SDimitry Andric 464fe6060f1SDimitry Andric std::pair<int, SourceLocation::UIntTy> 4650b57cec5SDimitry Andric SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries, 466fe6060f1SDimitry Andric SourceLocation::UIntTy TotalSize) { 4670b57cec5SDimitry Andric assert(ExternalSLocEntries && "Don't have an external sloc source"); 4680b57cec5SDimitry Andric // Make sure we're not about to run out of source locations. 469bdd1243dSDimitry Andric if (CurrentLoadedOffset < TotalSize || 470bdd1243dSDimitry Andric CurrentLoadedOffset - TotalSize < NextLocalOffset) { 4710b57cec5SDimitry Andric return std::make_pair(0, 0); 472bdd1243dSDimitry Andric } 4730b57cec5SDimitry Andric LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries); 4740b57cec5SDimitry Andric SLocEntryLoaded.resize(LoadedSLocEntryTable.size()); 4755f757f3fSDimitry Andric SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size()); 4760b57cec5SDimitry Andric CurrentLoadedOffset -= TotalSize; 477*0fca6ea1SDimitry Andric updateSlocUsageStats(); 4785f757f3fSDimitry Andric int BaseID = -int(LoadedSLocEntryTable.size()) - 1; 4795f757f3fSDimitry Andric LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID)); 4805f757f3fSDimitry Andric return std::make_pair(BaseID, CurrentLoadedOffset); 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a 4840b57cec5SDimitry Andric /// fake, non-empty buffer. 485e8d8bef9SDimitry Andric llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const { 4860b57cec5SDimitry Andric if (!FakeBufferForRecovery) 4870b57cec5SDimitry Andric FakeBufferForRecovery = 4880b57cec5SDimitry Andric llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>"); 4890b57cec5SDimitry Andric 490e8d8bef9SDimitry Andric return *FakeBufferForRecovery; 4910b57cec5SDimitry Andric } 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric /// As part of recovering from missing or changed content, produce a 4940b57cec5SDimitry Andric /// fake content cache. 495e8d8bef9SDimitry Andric SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const { 4960b57cec5SDimitry Andric if (!FakeContentCacheForRecovery) { 497a7dea167SDimitry Andric FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>(); 498e8d8bef9SDimitry Andric FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery()); 4990b57cec5SDimitry Andric } 500e8d8bef9SDimitry Andric return *FakeContentCacheForRecovery; 5010b57cec5SDimitry Andric } 5020b57cec5SDimitry Andric 5030b57cec5SDimitry Andric /// Returns the previous in-order FileID or an invalid FileID if there 5040b57cec5SDimitry Andric /// is no previous one. 5050b57cec5SDimitry Andric FileID SourceManager::getPreviousFileID(FileID FID) const { 5060b57cec5SDimitry Andric if (FID.isInvalid()) 5070b57cec5SDimitry Andric return FileID(); 5080b57cec5SDimitry Andric 5090b57cec5SDimitry Andric int ID = FID.ID; 5100b57cec5SDimitry Andric if (ID == -1) 5110b57cec5SDimitry Andric return FileID(); 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric if (ID > 0) { 5140b57cec5SDimitry Andric if (ID-1 == 0) 5150b57cec5SDimitry Andric return FileID(); 5160b57cec5SDimitry Andric } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) { 5170b57cec5SDimitry Andric return FileID(); 5180b57cec5SDimitry Andric } 5190b57cec5SDimitry Andric 5200b57cec5SDimitry Andric return FileID::get(ID-1); 5210b57cec5SDimitry Andric } 5220b57cec5SDimitry Andric 5230b57cec5SDimitry Andric /// Returns the next in-order FileID or an invalid FileID if there is 5240b57cec5SDimitry Andric /// no next one. 5250b57cec5SDimitry Andric FileID SourceManager::getNextFileID(FileID FID) const { 5260b57cec5SDimitry Andric if (FID.isInvalid()) 5270b57cec5SDimitry Andric return FileID(); 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric int ID = FID.ID; 5300b57cec5SDimitry Andric if (ID > 0) { 5310b57cec5SDimitry Andric if (unsigned(ID+1) >= local_sloc_entry_size()) 5320b57cec5SDimitry Andric return FileID(); 5330b57cec5SDimitry Andric } else if (ID+1 >= -1) { 5340b57cec5SDimitry Andric return FileID(); 5350b57cec5SDimitry Andric } 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric return FileID::get(ID+1); 5380b57cec5SDimitry Andric } 5390b57cec5SDimitry Andric 5400b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 5410b57cec5SDimitry Andric // Methods to create new FileID's and macro expansions. 5420b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 5430b57cec5SDimitry Andric 5445ffd83dbSDimitry Andric /// Create a new FileID that represents the specified file 5455ffd83dbSDimitry Andric /// being \#included from the specified IncludePosition. 5465ffd83dbSDimitry Andric FileID SourceManager::createFileID(FileEntryRef SourceFile, 5475ffd83dbSDimitry Andric SourceLocation IncludePos, 5485ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter, 549fe6060f1SDimitry Andric int LoadedID, 550fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) { 551e8d8bef9SDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile, 552e8d8bef9SDimitry Andric isSystem(FileCharacter)); 553e8d8bef9SDimitry Andric 554e8d8bef9SDimitry Andric // If this is a named pipe, immediately load the buffer to ensure subsequent 555e8d8bef9SDimitry Andric // calls to ContentCache::getSize() are accurate. 556e8d8bef9SDimitry Andric if (IR.ContentsEntry->isNamedPipe()) 557e8d8bef9SDimitry Andric (void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation()); 558e8d8bef9SDimitry Andric 559e8d8bef9SDimitry Andric return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter, 5605ffd83dbSDimitry Andric LoadedID, LoadedOffset); 5615ffd83dbSDimitry Andric } 5625ffd83dbSDimitry Andric 5635ffd83dbSDimitry Andric /// Create a new FileID that represents the specified memory buffer. 5645ffd83dbSDimitry Andric /// 5655ffd83dbSDimitry Andric /// This does no caching of the buffer and takes ownership of the 5665ffd83dbSDimitry Andric /// MemoryBuffer, so only pass a MemoryBuffer to this once. 5675ffd83dbSDimitry Andric FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer, 5685ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter, 569fe6060f1SDimitry Andric int LoadedID, 570fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset, 5715ffd83dbSDimitry Andric SourceLocation IncludeLoc) { 5725ffd83dbSDimitry Andric StringRef Name = Buffer->getBufferIdentifier(); 573e8d8bef9SDimitry Andric return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name, 574e8d8bef9SDimitry Andric IncludeLoc, FileCharacter, LoadedID, LoadedOffset); 5755ffd83dbSDimitry Andric } 5765ffd83dbSDimitry Andric 5775ffd83dbSDimitry Andric /// Create a new FileID that represents the specified memory buffer. 5785ffd83dbSDimitry Andric /// 5795ffd83dbSDimitry Andric /// This does not take ownership of the MemoryBuffer. The memory buffer must 5805ffd83dbSDimitry Andric /// outlive the SourceManager. 581e8d8bef9SDimitry Andric FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer, 5825ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter, 583fe6060f1SDimitry Andric int LoadedID, 584fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset, 5855ffd83dbSDimitry Andric SourceLocation IncludeLoc) { 586e8d8bef9SDimitry Andric return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter, 587e8d8bef9SDimitry Andric LoadedID, LoadedOffset, IncludeLoc); 5885ffd83dbSDimitry Andric } 5895ffd83dbSDimitry Andric 5905ffd83dbSDimitry Andric /// Get the FileID for \p SourceFile if it exists. Otherwise, create a 5915ffd83dbSDimitry Andric /// new FileID for the \p SourceFile. 5925ffd83dbSDimitry Andric FileID 5935f757f3fSDimitry Andric SourceManager::getOrCreateFileID(FileEntryRef SourceFile, 5945ffd83dbSDimitry Andric SrcMgr::CharacteristicKind FileCharacter) { 5955ffd83dbSDimitry Andric FileID ID = translateFile(SourceFile); 5965ffd83dbSDimitry Andric return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(), 5975ffd83dbSDimitry Andric FileCharacter); 5985ffd83dbSDimitry Andric } 5995ffd83dbSDimitry Andric 6000b57cec5SDimitry Andric /// createFileID - Create a new FileID for the specified ContentCache and 6010b57cec5SDimitry Andric /// include position. This works regardless of whether the ContentCache 6020b57cec5SDimitry Andric /// corresponds to a file or some other input source. 603e8d8bef9SDimitry Andric FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename, 6040b57cec5SDimitry Andric SourceLocation IncludePos, 6050b57cec5SDimitry Andric SrcMgr::CharacteristicKind FileCharacter, 606fe6060f1SDimitry Andric int LoadedID, 607fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) { 6080b57cec5SDimitry Andric if (LoadedID < 0) { 6090b57cec5SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID"); 6100b57cec5SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2; 6110b57cec5SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); 6120b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded"); 613a7dea167SDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get( 614a7dea167SDimitry Andric LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename)); 6155f757f3fSDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true; 6160b57cec5SDimitry Andric return FileID::get(LoadedID); 6170b57cec5SDimitry Andric } 618e8d8bef9SDimitry Andric unsigned FileSize = File.getSize(); 6195ffd83dbSDimitry Andric if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset && 6205ffd83dbSDimitry Andric NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) { 6215f757f3fSDimitry Andric Diag.Report(IncludePos, diag::err_sloc_space_too_large); 622bdd1243dSDimitry Andric noteSLocAddressSpaceUsage(Diag); 6235ffd83dbSDimitry Andric return FileID(); 6245ffd83dbSDimitry Andric } 625a7dea167SDimitry Andric LocalSLocEntryTable.push_back( 626a7dea167SDimitry Andric SLocEntry::get(NextLocalOffset, 627a7dea167SDimitry Andric FileInfo::get(IncludePos, File, FileCharacter, Filename))); 6280b57cec5SDimitry Andric // We do a +1 here because we want a SourceLocation that means "the end of the 6290b57cec5SDimitry Andric // file", e.g. for the "no newline at the end of the file" diagnostic. 6300b57cec5SDimitry Andric NextLocalOffset += FileSize + 1; 631*0fca6ea1SDimitry Andric updateSlocUsageStats(); 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric // Set LastFileIDLookup to the newly created file. The next getFileID call is 6340b57cec5SDimitry Andric // almost guaranteed to be from that file. 6350b57cec5SDimitry Andric FileID FID = FileID::get(LocalSLocEntryTable.size()-1); 6360b57cec5SDimitry Andric return LastFileIDLookup = FID; 6370b57cec5SDimitry Andric } 6380b57cec5SDimitry Andric 63981ad6265SDimitry Andric SourceLocation SourceManager::createMacroArgExpansionLoc( 64081ad6265SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) { 6410b57cec5SDimitry Andric ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc, 6420b57cec5SDimitry Andric ExpansionLoc); 64381ad6265SDimitry Andric return createExpansionLocImpl(Info, Length); 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric 646fe6060f1SDimitry Andric SourceLocation SourceManager::createExpansionLoc( 647fe6060f1SDimitry Andric SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, 64881ad6265SDimitry Andric SourceLocation ExpansionLocEnd, unsigned Length, 649fe6060f1SDimitry Andric bool ExpansionIsTokenRange, int LoadedID, 650fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) { 6510b57cec5SDimitry Andric ExpansionInfo Info = ExpansionInfo::create( 6520b57cec5SDimitry Andric SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange); 65381ad6265SDimitry Andric return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset); 6540b57cec5SDimitry Andric } 6550b57cec5SDimitry Andric 6560b57cec5SDimitry Andric SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling, 6570b57cec5SDimitry Andric SourceLocation TokenStart, 6580b57cec5SDimitry Andric SourceLocation TokenEnd) { 6590b57cec5SDimitry Andric assert(getFileID(TokenStart) == getFileID(TokenEnd) && 6600b57cec5SDimitry Andric "token spans multiple files"); 6610b57cec5SDimitry Andric return createExpansionLocImpl( 6620b57cec5SDimitry Andric ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd), 6630b57cec5SDimitry Andric TokenEnd.getOffset() - TokenStart.getOffset()); 6640b57cec5SDimitry Andric } 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric SourceLocation 6670b57cec5SDimitry Andric SourceManager::createExpansionLocImpl(const ExpansionInfo &Info, 66881ad6265SDimitry Andric unsigned Length, int LoadedID, 669fe6060f1SDimitry Andric SourceLocation::UIntTy LoadedOffset) { 6700b57cec5SDimitry Andric if (LoadedID < 0) { 6710b57cec5SDimitry Andric assert(LoadedID != -1 && "Loading sentinel FileID"); 6720b57cec5SDimitry Andric unsigned Index = unsigned(-LoadedID) - 2; 6730b57cec5SDimitry Andric assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); 6740b57cec5SDimitry Andric assert(!SLocEntryLoaded[Index] && "FileID already loaded"); 6750b57cec5SDimitry Andric LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info); 6765f757f3fSDimitry Andric SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true; 6770b57cec5SDimitry Andric return SourceLocation::getMacroLoc(LoadedOffset); 6780b57cec5SDimitry Andric } 6790b57cec5SDimitry Andric LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info)); 6805f757f3fSDimitry Andric if (NextLocalOffset + Length + 1 <= NextLocalOffset || 6815f757f3fSDimitry Andric NextLocalOffset + Length + 1 > CurrentLoadedOffset) { 6825f757f3fSDimitry Andric Diag.Report(SourceLocation(), diag::err_sloc_space_too_large); 6835f757f3fSDimitry Andric // FIXME: call `noteSLocAddressSpaceUsage` to report details to users and 6845f757f3fSDimitry Andric // use a source location from `Info` to point at an error. 6855f757f3fSDimitry Andric // Currently, both cause Clang to run indefinitely, this needs to be fixed. 6865f757f3fSDimitry Andric // FIXME: return an error instead of crashing. Returning invalid source 6875f757f3fSDimitry Andric // locations causes compiler to run indefinitely. 6885f757f3fSDimitry Andric llvm::report_fatal_error("ran out of source locations"); 6895f757f3fSDimitry Andric } 6900b57cec5SDimitry Andric // See createFileID for that +1. 69181ad6265SDimitry Andric NextLocalOffset += Length + 1; 692*0fca6ea1SDimitry Andric updateSlocUsageStats(); 69381ad6265SDimitry Andric return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1)); 6940b57cec5SDimitry Andric } 6950b57cec5SDimitry Andric 696bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> 6975f757f3fSDimitry Andric SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) { 6985f757f3fSDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(File); 699e8d8bef9SDimitry Andric return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation()); 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric 702e8d8bef9SDimitry Andric void SourceManager::overrideFileContents( 7035f757f3fSDimitry Andric FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) { 7045f757f3fSDimitry Andric SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile); 7050b57cec5SDimitry Andric 706e8d8bef9SDimitry Andric IR.setBuffer(std::move(Buffer)); 707e8d8bef9SDimitry Andric IR.BufferOverridden = true; 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile); 7100b57cec5SDimitry Andric } 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric void SourceManager::overrideFileContents(const FileEntry *SourceFile, 713bdd1243dSDimitry Andric FileEntryRef NewFile) { 714bdd1243dSDimitry Andric assert(SourceFile->getSize() == NewFile.getSize() && 7150b57cec5SDimitry Andric "Different sizes, use the FileManager to create a virtual file with " 7160b57cec5SDimitry Andric "the correct size"); 7175f757f3fSDimitry Andric assert(FileInfos.find_as(SourceFile) == FileInfos.end() && 7180b57cec5SDimitry Andric "This function should be called at the initialization stage, before " 7190b57cec5SDimitry Andric "any parsing occurs."); 720bdd1243dSDimitry Andric // FileEntryRef is not default-constructible. 721bdd1243dSDimitry Andric auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert( 722bdd1243dSDimitry Andric std::make_pair(SourceFile, NewFile)); 723bdd1243dSDimitry Andric if (!Pair.second) 724bdd1243dSDimitry Andric Pair.first->second = NewFile; 7250b57cec5SDimitry Andric } 7260b57cec5SDimitry Andric 727bdd1243dSDimitry Andric OptionalFileEntryRef 728e8d8bef9SDimitry Andric SourceManager::bypassFileContentsOverride(FileEntryRef File) { 729e8d8bef9SDimitry Andric assert(isFileOverridden(&File.getFileEntry())); 730bdd1243dSDimitry Andric OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File); 7310b57cec5SDimitry Andric 732a7dea167SDimitry Andric // If the file can't be found in the FS, give up. 733a7dea167SDimitry Andric if (!BypassFile) 734bdd1243dSDimitry Andric return std::nullopt; 7350b57cec5SDimitry Andric 736e8d8bef9SDimitry Andric (void)getOrCreateContentCache(*BypassFile); 737e8d8bef9SDimitry Andric return BypassFile; 7380b57cec5SDimitry Andric } 7390b57cec5SDimitry Andric 7405f757f3fSDimitry Andric void SourceManager::setFileIsTransient(FileEntryRef File) { 7415f757f3fSDimitry Andric getOrCreateContentCache(File).IsTransient = true; 7420b57cec5SDimitry Andric } 7430b57cec5SDimitry Andric 744bdd1243dSDimitry Andric std::optional<StringRef> 745e8d8bef9SDimitry Andric SourceManager::getNonBuiltinFilenameForID(FileID FID) const { 746e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) 747e8d8bef9SDimitry Andric if (Entry->getFile().getContentCache().OrigEntry) 748e8d8bef9SDimitry Andric return Entry->getFile().getName(); 749bdd1243dSDimitry Andric return std::nullopt; 7505ffd83dbSDimitry Andric } 7515ffd83dbSDimitry Andric 7520b57cec5SDimitry Andric StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { 753e8d8bef9SDimitry Andric auto B = getBufferDataOrNone(FID); 7540b57cec5SDimitry Andric if (Invalid) 755e8d8bef9SDimitry Andric *Invalid = !B; 756e8d8bef9SDimitry Andric return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>"; 7570b57cec5SDimitry Andric } 7580b57cec5SDimitry Andric 759bdd1243dSDimitry Andric std::optional<StringRef> 760e8d8bef9SDimitry Andric SourceManager::getBufferDataIfLoaded(FileID FID) const { 761e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) 762e8d8bef9SDimitry Andric return Entry->getFile().getContentCache().getBufferDataIfLoaded(); 763bdd1243dSDimitry Andric return std::nullopt; 764e8d8bef9SDimitry Andric } 7650b57cec5SDimitry Andric 766bdd1243dSDimitry Andric std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const { 767e8d8bef9SDimitry Andric if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID)) 768e8d8bef9SDimitry Andric if (auto B = Entry->getFile().getContentCache().getBufferOrNone( 769e8d8bef9SDimitry Andric Diag, getFileManager(), SourceLocation())) 770e8d8bef9SDimitry Andric return B->getBuffer(); 771bdd1243dSDimitry Andric return std::nullopt; 7720b57cec5SDimitry Andric } 7730b57cec5SDimitry Andric 7740b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 7750b57cec5SDimitry Andric // SourceLocation manipulation methods. 7760b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric /// Return the FileID for a SourceLocation. 7790b57cec5SDimitry Andric /// 7800b57cec5SDimitry Andric /// This is the cache-miss path of getFileID. Not as hot as that function, but 7810b57cec5SDimitry Andric /// still very important. It is responsible for finding the entry in the 7820b57cec5SDimitry Andric /// SLocEntry tables that contains the specified location. 783fe6060f1SDimitry Andric FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const { 7840b57cec5SDimitry Andric if (!SLocOffset) 7850b57cec5SDimitry Andric return FileID::get(0); 7860b57cec5SDimitry Andric 7870b57cec5SDimitry Andric // Now it is time to search for the correct file. See where the SLocOffset 7880b57cec5SDimitry Andric // sits in the global view and consult local or loaded buffers for it. 7890b57cec5SDimitry Andric if (SLocOffset < NextLocalOffset) 7900b57cec5SDimitry Andric return getFileIDLocal(SLocOffset); 7910b57cec5SDimitry Andric return getFileIDLoaded(SLocOffset); 7920b57cec5SDimitry Andric } 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a low offset. 7950b57cec5SDimitry Andric /// 7960b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a local buffer, not a 7970b57cec5SDimitry Andric /// loaded one. 798fe6060f1SDimitry Andric FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const { 7990b57cec5SDimitry Andric assert(SLocOffset < NextLocalOffset && "Bad function choice"); 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric // After the first and second level caches, I see two common sorts of 8020b57cec5SDimitry Andric // behavior: 1) a lot of searched FileID's are "near" the cached file 8030b57cec5SDimitry Andric // location or are "near" the cached expansion location. 2) others are just 8040b57cec5SDimitry Andric // completely random and may be a very long way away. 8050b57cec5SDimitry Andric // 8060b57cec5SDimitry Andric // To handle this, we do a linear search for up to 8 steps to catch #1 quickly 8070b57cec5SDimitry Andric // then we fall back to a less cache efficient, but more scalable, binary 8080b57cec5SDimitry Andric // search to find the location. 8090b57cec5SDimitry Andric 8100b57cec5SDimitry Andric // See if this is near the file point - worst case we start scanning from the 8110b57cec5SDimitry Andric // most newly created FileID. 8120b57cec5SDimitry Andric 813bdd1243dSDimitry Andric // LessIndex - This is the lower bound of the range that we're searching. 814bdd1243dSDimitry Andric // We know that the offset corresponding to the FileID is less than 815bdd1243dSDimitry Andric // SLocOffset. 816bdd1243dSDimitry Andric unsigned LessIndex = 0; 817bdd1243dSDimitry Andric // upper bound of the search range. 818bdd1243dSDimitry Andric unsigned GreaterIndex = LocalSLocEntryTable.size(); 819bdd1243dSDimitry Andric if (LastFileIDLookup.ID >= 0) { 820bdd1243dSDimitry Andric // Use the LastFileIDLookup to prune the search space. 821bdd1243dSDimitry Andric if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) 822bdd1243dSDimitry Andric LessIndex = LastFileIDLookup.ID; 823bdd1243dSDimitry Andric else 824bdd1243dSDimitry Andric GreaterIndex = LastFileIDLookup.ID; 8250b57cec5SDimitry Andric } 8260b57cec5SDimitry Andric 827bdd1243dSDimitry Andric // Find the FileID that contains this. 8280b57cec5SDimitry Andric unsigned NumProbes = 0; 8290b57cec5SDimitry Andric while (true) { 830bdd1243dSDimitry Andric --GreaterIndex; 831bdd1243dSDimitry Andric assert(GreaterIndex < LocalSLocEntryTable.size()); 832bdd1243dSDimitry Andric if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) { 833bdd1243dSDimitry Andric FileID Res = FileID::get(int(GreaterIndex)); 8345ffd83dbSDimitry Andric // Remember it. We have good locality across FileID lookups. 8350b57cec5SDimitry Andric LastFileIDLookup = Res; 8360b57cec5SDimitry Andric NumLinearScans += NumProbes+1; 8370b57cec5SDimitry Andric return Res; 8380b57cec5SDimitry Andric } 8390b57cec5SDimitry Andric if (++NumProbes == 8) 8400b57cec5SDimitry Andric break; 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric NumProbes = 0; 8440b57cec5SDimitry Andric while (true) { 8450b57cec5SDimitry Andric unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; 846fe6060f1SDimitry Andric SourceLocation::UIntTy MidOffset = 847fe6060f1SDimitry Andric getLocalSLocEntry(MiddleIndex).getOffset(); 8480b57cec5SDimitry Andric 8490b57cec5SDimitry Andric ++NumProbes; 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric // If the offset of the midpoint is too large, chop the high side of the 8520b57cec5SDimitry Andric // range to the midpoint. 8530b57cec5SDimitry Andric if (MidOffset > SLocOffset) { 8540b57cec5SDimitry Andric GreaterIndex = MiddleIndex; 8550b57cec5SDimitry Andric continue; 8560b57cec5SDimitry Andric } 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric // If the middle index contains the value, succeed and return. 8595ffd83dbSDimitry Andric if (MiddleIndex + 1 == LocalSLocEntryTable.size() || 8605ffd83dbSDimitry Andric SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) { 8610b57cec5SDimitry Andric FileID Res = FileID::get(MiddleIndex); 8620b57cec5SDimitry Andric 8635ffd83dbSDimitry Andric // Remember it. We have good locality across FileID lookups. 8640b57cec5SDimitry Andric LastFileIDLookup = Res; 8650b57cec5SDimitry Andric NumBinaryProbes += NumProbes; 8660b57cec5SDimitry Andric return Res; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric // Otherwise, move the low-side up to the middle index. 8700b57cec5SDimitry Andric LessIndex = MiddleIndex; 8710b57cec5SDimitry Andric } 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric 8740b57cec5SDimitry Andric /// Return the FileID for a SourceLocation with a high offset. 8750b57cec5SDimitry Andric /// 8760b57cec5SDimitry Andric /// This function knows that the SourceLocation is in a loaded buffer, not a 8770b57cec5SDimitry Andric /// local one. 878fe6060f1SDimitry Andric FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const { 8790b57cec5SDimitry Andric if (SLocOffset < CurrentLoadedOffset) { 8800b57cec5SDimitry Andric assert(0 && "Invalid SLocOffset or bad function choice"); 8810b57cec5SDimitry Andric return FileID(); 8820b57cec5SDimitry Andric } 8830b57cec5SDimitry Andric 8845f757f3fSDimitry Andric return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset)); 8850b57cec5SDimitry Andric } 8860b57cec5SDimitry Andric 8870b57cec5SDimitry Andric SourceLocation SourceManager:: 8880b57cec5SDimitry Andric getExpansionLocSlowCase(SourceLocation Loc) const { 8890b57cec5SDimitry Andric do { 8900b57cec5SDimitry Andric // Note: If Loc indicates an offset into a token that came from a macro 8910b57cec5SDimitry Andric // expansion (e.g. the 5th character of the token) we do not want to add 8920b57cec5SDimitry Andric // this offset when going to the expansion location. The expansion 8930b57cec5SDimitry Andric // location is the macro invocation, which the offset has nothing to do 8940b57cec5SDimitry Andric // with. This is unlike when we get the spelling loc, because the offset 8950b57cec5SDimitry Andric // directly correspond to the token whose spelling we're inspecting. 8960b57cec5SDimitry Andric Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart(); 8970b57cec5SDimitry Andric } while (!Loc.isFileID()); 8980b57cec5SDimitry Andric 8990b57cec5SDimitry Andric return Loc; 9000b57cec5SDimitry Andric } 9010b57cec5SDimitry Andric 9020b57cec5SDimitry Andric SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { 9030b57cec5SDimitry Andric do { 9040b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 9050b57cec5SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); 9060b57cec5SDimitry Andric Loc = Loc.getLocWithOffset(LocInfo.second); 9070b57cec5SDimitry Andric } while (!Loc.isFileID()); 9080b57cec5SDimitry Andric return Loc; 9090b57cec5SDimitry Andric } 9100b57cec5SDimitry Andric 9110b57cec5SDimitry Andric SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const { 9120b57cec5SDimitry Andric do { 9130b57cec5SDimitry Andric if (isMacroArgExpansion(Loc)) 9140b57cec5SDimitry Andric Loc = getImmediateSpellingLoc(Loc); 9150b57cec5SDimitry Andric else 9160b57cec5SDimitry Andric Loc = getImmediateExpansionRange(Loc).getBegin(); 9170b57cec5SDimitry Andric } while (!Loc.isFileID()); 9180b57cec5SDimitry Andric return Loc; 9190b57cec5SDimitry Andric } 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric 9220b57cec5SDimitry Andric std::pair<FileID, unsigned> 9230b57cec5SDimitry Andric SourceManager::getDecomposedExpansionLocSlowCase( 9240b57cec5SDimitry Andric const SrcMgr::SLocEntry *E) const { 9250b57cec5SDimitry Andric // If this is an expansion record, walk through all the expansion points. 9260b57cec5SDimitry Andric FileID FID; 9270b57cec5SDimitry Andric SourceLocation Loc; 9280b57cec5SDimitry Andric unsigned Offset; 9290b57cec5SDimitry Andric do { 9300b57cec5SDimitry Andric Loc = E->getExpansion().getExpansionLocStart(); 9310b57cec5SDimitry Andric 9320b57cec5SDimitry Andric FID = getFileID(Loc); 9330b57cec5SDimitry Andric E = &getSLocEntry(FID); 9340b57cec5SDimitry Andric Offset = Loc.getOffset()-E->getOffset(); 9350b57cec5SDimitry Andric } while (!Loc.isFileID()); 9360b57cec5SDimitry Andric 9370b57cec5SDimitry Andric return std::make_pair(FID, Offset); 9380b57cec5SDimitry Andric } 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric std::pair<FileID, unsigned> 9410b57cec5SDimitry Andric SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, 9420b57cec5SDimitry Andric unsigned Offset) const { 9430b57cec5SDimitry Andric // If this is an expansion record, walk through all the expansion points. 9440b57cec5SDimitry Andric FileID FID; 9450b57cec5SDimitry Andric SourceLocation Loc; 9460b57cec5SDimitry Andric do { 9470b57cec5SDimitry Andric Loc = E->getExpansion().getSpellingLoc(); 9480b57cec5SDimitry Andric Loc = Loc.getLocWithOffset(Offset); 9490b57cec5SDimitry Andric 9500b57cec5SDimitry Andric FID = getFileID(Loc); 9510b57cec5SDimitry Andric E = &getSLocEntry(FID); 9520b57cec5SDimitry Andric Offset = Loc.getOffset()-E->getOffset(); 9530b57cec5SDimitry Andric } while (!Loc.isFileID()); 9540b57cec5SDimitry Andric 9550b57cec5SDimitry Andric return std::make_pair(FID, Offset); 9560b57cec5SDimitry Andric } 9570b57cec5SDimitry Andric 9580b57cec5SDimitry Andric /// getImmediateSpellingLoc - Given a SourceLocation object, return the 9590b57cec5SDimitry Andric /// spelling location referenced by the ID. This is the first level down 9600b57cec5SDimitry Andric /// towards the place where the characters that make up the lexed token can be 9610b57cec5SDimitry Andric /// found. This should not generally be used by clients. 9620b57cec5SDimitry Andric SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ 9630b57cec5SDimitry Andric if (Loc.isFileID()) return Loc; 9640b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 9650b57cec5SDimitry Andric Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); 9660b57cec5SDimitry Andric return Loc.getLocWithOffset(LocInfo.second); 9670b57cec5SDimitry Andric } 9680b57cec5SDimitry Andric 9695ffd83dbSDimitry Andric /// Return the filename of the file containing a SourceLocation. 9705ffd83dbSDimitry Andric StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const { 9715f757f3fSDimitry Andric if (OptionalFileEntryRef F = getFileEntryRefForID(getFileID(SpellingLoc))) 9725ffd83dbSDimitry Andric return F->getName(); 9735ffd83dbSDimitry Andric return StringRef(); 9745ffd83dbSDimitry Andric } 9755ffd83dbSDimitry Andric 9760b57cec5SDimitry Andric /// getImmediateExpansionRange - Loc is required to be an expansion location. 9770b57cec5SDimitry Andric /// Return the start/end of the expansion information. 9780b57cec5SDimitry Andric CharSourceRange 9790b57cec5SDimitry Andric SourceManager::getImmediateExpansionRange(SourceLocation Loc) const { 9800b57cec5SDimitry Andric assert(Loc.isMacroID() && "Not a macro expansion loc!"); 9810b57cec5SDimitry Andric const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion(); 9820b57cec5SDimitry Andric return Expansion.getExpansionLocRange(); 9830b57cec5SDimitry Andric } 9840b57cec5SDimitry Andric 9850b57cec5SDimitry Andric SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const { 9860b57cec5SDimitry Andric while (isMacroArgExpansion(Loc)) 9870b57cec5SDimitry Andric Loc = getImmediateSpellingLoc(Loc); 9880b57cec5SDimitry Andric return Loc; 9890b57cec5SDimitry Andric } 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric /// getExpansionRange - Given a SourceLocation object, return the range of 9920b57cec5SDimitry Andric /// tokens covered by the expansion in the ultimate file. 9930b57cec5SDimitry Andric CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const { 9940b57cec5SDimitry Andric if (Loc.isFileID()) 9950b57cec5SDimitry Andric return CharSourceRange(SourceRange(Loc, Loc), true); 9960b57cec5SDimitry Andric 9970b57cec5SDimitry Andric CharSourceRange Res = getImmediateExpansionRange(Loc); 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric // Fully resolve the start and end locations to their ultimate expansion 10000b57cec5SDimitry Andric // points. 10010b57cec5SDimitry Andric while (!Res.getBegin().isFileID()) 10020b57cec5SDimitry Andric Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin()); 10030b57cec5SDimitry Andric while (!Res.getEnd().isFileID()) { 10040b57cec5SDimitry Andric CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd()); 10050b57cec5SDimitry Andric Res.setEnd(EndRange.getEnd()); 10060b57cec5SDimitry Andric Res.setTokenRange(EndRange.isTokenRange()); 10070b57cec5SDimitry Andric } 10080b57cec5SDimitry Andric return Res; 10090b57cec5SDimitry Andric } 10100b57cec5SDimitry Andric 10110b57cec5SDimitry Andric bool SourceManager::isMacroArgExpansion(SourceLocation Loc, 10120b57cec5SDimitry Andric SourceLocation *StartLoc) const { 10130b57cec5SDimitry Andric if (!Loc.isMacroID()) return false; 10140b57cec5SDimitry Andric 10150b57cec5SDimitry Andric FileID FID = getFileID(Loc); 10160b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); 10170b57cec5SDimitry Andric if (!Expansion.isMacroArgExpansion()) return false; 10180b57cec5SDimitry Andric 10190b57cec5SDimitry Andric if (StartLoc) 10200b57cec5SDimitry Andric *StartLoc = Expansion.getExpansionLocStart(); 10210b57cec5SDimitry Andric return true; 10220b57cec5SDimitry Andric } 10230b57cec5SDimitry Andric 10240b57cec5SDimitry Andric bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const { 10250b57cec5SDimitry Andric if (!Loc.isMacroID()) return false; 10260b57cec5SDimitry Andric 10270b57cec5SDimitry Andric FileID FID = getFileID(Loc); 10280b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); 10290b57cec5SDimitry Andric return Expansion.isMacroBodyExpansion(); 10300b57cec5SDimitry Andric } 10310b57cec5SDimitry Andric 10320b57cec5SDimitry Andric bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc, 10330b57cec5SDimitry Andric SourceLocation *MacroBegin) const { 10340b57cec5SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc"); 10350b57cec5SDimitry Andric 10360b57cec5SDimitry Andric std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc); 10370b57cec5SDimitry Andric if (DecompLoc.second > 0) 10380b57cec5SDimitry Andric return false; // Does not point at the start of expansion range. 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric bool Invalid = false; 10410b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo = 10420b57cec5SDimitry Andric getSLocEntry(DecompLoc.first, &Invalid).getExpansion(); 10430b57cec5SDimitry Andric if (Invalid) 10440b57cec5SDimitry Andric return false; 10450b57cec5SDimitry Andric SourceLocation ExpLoc = ExpInfo.getExpansionLocStart(); 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric if (ExpInfo.isMacroArgExpansion()) { 10480b57cec5SDimitry Andric // For macro argument expansions, check if the previous FileID is part of 10490b57cec5SDimitry Andric // the same argument expansion, in which case this Loc is not at the 10500b57cec5SDimitry Andric // beginning of the expansion. 10510b57cec5SDimitry Andric FileID PrevFID = getPreviousFileID(DecompLoc.first); 10520b57cec5SDimitry Andric if (!PrevFID.isInvalid()) { 10530b57cec5SDimitry Andric const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid); 10540b57cec5SDimitry Andric if (Invalid) 10550b57cec5SDimitry Andric return false; 10560b57cec5SDimitry Andric if (PrevEntry.isExpansion() && 10570b57cec5SDimitry Andric PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc) 10580b57cec5SDimitry Andric return false; 10590b57cec5SDimitry Andric } 10600b57cec5SDimitry Andric } 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric if (MacroBegin) 10630b57cec5SDimitry Andric *MacroBegin = ExpLoc; 10640b57cec5SDimitry Andric return true; 10650b57cec5SDimitry Andric } 10660b57cec5SDimitry Andric 10670b57cec5SDimitry Andric bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc, 10680b57cec5SDimitry Andric SourceLocation *MacroEnd) const { 10690b57cec5SDimitry Andric assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc"); 10700b57cec5SDimitry Andric 10710b57cec5SDimitry Andric FileID FID = getFileID(Loc); 10720b57cec5SDimitry Andric SourceLocation NextLoc = Loc.getLocWithOffset(1); 10730b57cec5SDimitry Andric if (isInFileID(NextLoc, FID)) 10740b57cec5SDimitry Andric return false; // Does not point at the end of expansion range. 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric bool Invalid = false; 10770b57cec5SDimitry Andric const SrcMgr::ExpansionInfo &ExpInfo = 10780b57cec5SDimitry Andric getSLocEntry(FID, &Invalid).getExpansion(); 10790b57cec5SDimitry Andric if (Invalid) 10800b57cec5SDimitry Andric return false; 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric if (ExpInfo.isMacroArgExpansion()) { 10830b57cec5SDimitry Andric // For macro argument expansions, check if the next FileID is part of the 10840b57cec5SDimitry Andric // same argument expansion, in which case this Loc is not at the end of the 10850b57cec5SDimitry Andric // expansion. 10860b57cec5SDimitry Andric FileID NextFID = getNextFileID(FID); 10870b57cec5SDimitry Andric if (!NextFID.isInvalid()) { 10880b57cec5SDimitry Andric const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid); 10890b57cec5SDimitry Andric if (Invalid) 10900b57cec5SDimitry Andric return false; 10910b57cec5SDimitry Andric if (NextEntry.isExpansion() && 10920b57cec5SDimitry Andric NextEntry.getExpansion().getExpansionLocStart() == 10930b57cec5SDimitry Andric ExpInfo.getExpansionLocStart()) 10940b57cec5SDimitry Andric return false; 10950b57cec5SDimitry Andric } 10960b57cec5SDimitry Andric } 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric if (MacroEnd) 10990b57cec5SDimitry Andric *MacroEnd = ExpInfo.getExpansionLocEnd(); 11000b57cec5SDimitry Andric return true; 11010b57cec5SDimitry Andric } 11020b57cec5SDimitry Andric 11030b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 11040b57cec5SDimitry Andric // Queries about the code at a SourceLocation. 11050b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 11060b57cec5SDimitry Andric 11070b57cec5SDimitry Andric /// getCharacterData - Return a pointer to the start of the specified location 11080b57cec5SDimitry Andric /// in the appropriate MemoryBuffer. 11090b57cec5SDimitry Andric const char *SourceManager::getCharacterData(SourceLocation SL, 11100b57cec5SDimitry Andric bool *Invalid) const { 11110b57cec5SDimitry Andric // Note that this is a hot function in the getSpelling() path, which is 11120b57cec5SDimitry Andric // heavily used by -E mode. 11130b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric // Note that calling 'getBuffer()' may lazily page in a source file. 11160b57cec5SDimitry Andric bool CharDataInvalid = false; 11170b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid); 11180b57cec5SDimitry Andric if (CharDataInvalid || !Entry.isFile()) { 11190b57cec5SDimitry Andric if (Invalid) 11200b57cec5SDimitry Andric *Invalid = true; 11210b57cec5SDimitry Andric 11220b57cec5SDimitry Andric return "<<<<INVALID BUFFER>>>>"; 11230b57cec5SDimitry Andric } 1124bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer = 1125e8d8bef9SDimitry Andric Entry.getFile().getContentCache().getBufferOrNone(Diag, getFileManager(), 1126e8d8bef9SDimitry Andric SourceLocation()); 11270b57cec5SDimitry Andric if (Invalid) 1128e8d8bef9SDimitry Andric *Invalid = !Buffer; 1129e8d8bef9SDimitry Andric return Buffer ? Buffer->getBufferStart() + LocInfo.second 1130e8d8bef9SDimitry Andric : "<<<<INVALID BUFFER>>>>"; 11310b57cec5SDimitry Andric } 11320b57cec5SDimitry Andric 11330b57cec5SDimitry Andric /// getColumnNumber - Return the column # for the specified file position. 11340b57cec5SDimitry Andric /// this is significantly cheaper to compute than the line number. 11350b57cec5SDimitry Andric unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, 11360b57cec5SDimitry Andric bool *Invalid) const { 1137bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> MemBuf = getBufferOrNone(FID); 11380b57cec5SDimitry Andric if (Invalid) 1139e8d8bef9SDimitry Andric *Invalid = !MemBuf; 11400b57cec5SDimitry Andric 1141e8d8bef9SDimitry Andric if (!MemBuf) 11420b57cec5SDimitry Andric return 1; 11430b57cec5SDimitry Andric 11440b57cec5SDimitry Andric // It is okay to request a position just past the end of the buffer. 11450b57cec5SDimitry Andric if (FilePos > MemBuf->getBufferSize()) { 11460b57cec5SDimitry Andric if (Invalid) 11470b57cec5SDimitry Andric *Invalid = true; 11480b57cec5SDimitry Andric return 1; 11490b57cec5SDimitry Andric } 11500b57cec5SDimitry Andric 11510b57cec5SDimitry Andric const char *Buf = MemBuf->getBufferStart(); 11520b57cec5SDimitry Andric // See if we just calculated the line number for this FilePos and can use 11530b57cec5SDimitry Andric // that to lookup the start of the line instead of searching for it. 1154e8d8bef9SDimitry Andric if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache && 1155e8d8bef9SDimitry Andric LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) { 1156e8d8bef9SDimitry Andric const unsigned *SourceLineCache = 1157e8d8bef9SDimitry Andric LastLineNoContentCache->SourceLineCache.begin(); 11580b57cec5SDimitry Andric unsigned LineStart = SourceLineCache[LastLineNoResult - 1]; 11590b57cec5SDimitry Andric unsigned LineEnd = SourceLineCache[LastLineNoResult]; 11600b57cec5SDimitry Andric if (FilePos >= LineStart && FilePos < LineEnd) { 11610b57cec5SDimitry Andric // LineEnd is the LineStart of the next line. 11620b57cec5SDimitry Andric // A line ends with separator LF or CR+LF on Windows. 11630b57cec5SDimitry Andric // FilePos might point to the last separator, 11640b57cec5SDimitry Andric // but we need a column number at most 1 + the last column. 11650b57cec5SDimitry Andric if (FilePos + 1 == LineEnd && FilePos > LineStart) { 11660b57cec5SDimitry Andric if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n') 11670b57cec5SDimitry Andric --FilePos; 11680b57cec5SDimitry Andric } 11690b57cec5SDimitry Andric return FilePos - LineStart + 1; 11700b57cec5SDimitry Andric } 11710b57cec5SDimitry Andric } 11720b57cec5SDimitry Andric 11730b57cec5SDimitry Andric unsigned LineStart = FilePos; 11740b57cec5SDimitry Andric while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') 11750b57cec5SDimitry Andric --LineStart; 11760b57cec5SDimitry Andric return FilePos-LineStart+1; 11770b57cec5SDimitry Andric } 11780b57cec5SDimitry Andric 11790b57cec5SDimitry Andric // isInvalid - Return the result of calling loc.isInvalid(), and 11800b57cec5SDimitry Andric // if Invalid is not null, set its value to same. 11810b57cec5SDimitry Andric template<typename LocType> 11820b57cec5SDimitry Andric static bool isInvalid(LocType Loc, bool *Invalid) { 11830b57cec5SDimitry Andric bool MyInvalid = Loc.isInvalid(); 11840b57cec5SDimitry Andric if (Invalid) 11850b57cec5SDimitry Andric *Invalid = MyInvalid; 11860b57cec5SDimitry Andric return MyInvalid; 11870b57cec5SDimitry Andric } 11880b57cec5SDimitry Andric 11890b57cec5SDimitry Andric unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, 11900b57cec5SDimitry Andric bool *Invalid) const { 11910b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0; 11920b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 11930b57cec5SDimitry Andric return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 11940b57cec5SDimitry Andric } 11950b57cec5SDimitry Andric 11960b57cec5SDimitry Andric unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc, 11970b57cec5SDimitry Andric bool *Invalid) const { 11980b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0; 11990b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 12000b57cec5SDimitry Andric return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc, 12040b57cec5SDimitry Andric bool *Invalid) const { 12050b57cec5SDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc); 12060b57cec5SDimitry Andric if (isInvalid(PLoc, Invalid)) return 0; 12070b57cec5SDimitry Andric return PLoc.getColumn(); 12080b57cec5SDimitry Andric } 12090b57cec5SDimitry Andric 1210fe6060f1SDimitry Andric // Check if mutli-byte word x has bytes between m and n, included. This may also 1211fe6060f1SDimitry Andric // catch bytes equal to n + 1. 1212fe6060f1SDimitry Andric // The returned value holds a 0x80 at each byte position that holds a match. 1213fe6060f1SDimitry Andric // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord 1214fe6060f1SDimitry Andric template <class T> 1215fe6060f1SDimitry Andric static constexpr inline T likelyhasbetween(T x, unsigned char m, 1216fe6060f1SDimitry Andric unsigned char n) { 1217fe6060f1SDimitry Andric return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x & 1218fe6060f1SDimitry Andric ((x & ~static_cast<T>(0) / 255 * 127) + 1219fe6060f1SDimitry Andric (~static_cast<T>(0) / 255 * (127 - (m - 1))))) & 1220fe6060f1SDimitry Andric ~static_cast<T>(0) / 255 * 128; 1221fe6060f1SDimitry Andric } 12220b57cec5SDimitry Andric 1223e8d8bef9SDimitry Andric LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer, 1224e8d8bef9SDimitry Andric llvm::BumpPtrAllocator &Alloc) { 1225fe6060f1SDimitry Andric 12260b57cec5SDimitry Andric // Find the file offsets of all of the *physical* source lines. This does 12270b57cec5SDimitry Andric // not look at trigraphs, escaped newlines, or anything else tricky. 12280b57cec5SDimitry Andric SmallVector<unsigned, 256> LineOffsets; 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric // Line #1 starts at char 0. 12310b57cec5SDimitry Andric LineOffsets.push_back(0); 12320b57cec5SDimitry Andric 1233bdd1243dSDimitry Andric const unsigned char *Start = (const unsigned char *)Buffer.getBufferStart(); 1234e8d8bef9SDimitry Andric const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd(); 1235bdd1243dSDimitry Andric const unsigned char *Buf = Start; 1236fe6060f1SDimitry Andric 1237fe6060f1SDimitry Andric uint64_t Word; 1238fe6060f1SDimitry Andric 1239fe6060f1SDimitry Andric // scan sizeof(Word) bytes at a time for new lines. 1240fe6060f1SDimitry Andric // This is much faster than scanning each byte independently. 1241bdd1243dSDimitry Andric if ((unsigned long)(End - Start) > sizeof(Word)) { 1242fe6060f1SDimitry Andric do { 12435f757f3fSDimitry Andric Word = llvm::support::endian::read64(Buf, llvm::endianness::little); 1244fe6060f1SDimitry Andric // no new line => jump over sizeof(Word) bytes. 1245fe6060f1SDimitry Andric auto Mask = likelyhasbetween(Word, '\n', '\r'); 1246fe6060f1SDimitry Andric if (!Mask) { 1247bdd1243dSDimitry Andric Buf += sizeof(Word); 1248fe6060f1SDimitry Andric continue; 1249fe6060f1SDimitry Andric } 1250fe6060f1SDimitry Andric 1251fe6060f1SDimitry Andric // At that point, Mask contains 0x80 set at each byte that holds a value 1252fe6060f1SDimitry Andric // in [\n, \r + 1 [ 1253fe6060f1SDimitry Andric 1254fe6060f1SDimitry Andric // Scan for the next newline - it's very likely there's one. 125506c3fb27SDimitry Andric unsigned N = llvm::countr_zero(Mask) - 7; // -7 because 0x80 is the marker 1256fe6060f1SDimitry Andric Word >>= N; 1257bdd1243dSDimitry Andric Buf += N / 8 + 1; 1258fe6060f1SDimitry Andric unsigned char Byte = Word; 1259bdd1243dSDimitry Andric switch (Byte) { 1260bdd1243dSDimitry Andric case '\r': 1261fe6060f1SDimitry Andric // If this is \r\n, skip both characters. 1262bdd1243dSDimitry Andric if (*Buf == '\n') { 1263bdd1243dSDimitry Andric ++Buf; 1264fe6060f1SDimitry Andric } 126506c3fb27SDimitry Andric [[fallthrough]]; 1266bdd1243dSDimitry Andric case '\n': 1267bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start); 1268bdd1243dSDimitry Andric }; 1269bdd1243dSDimitry Andric } while (Buf < End - sizeof(Word) - 1); 1270fe6060f1SDimitry Andric } 1271fe6060f1SDimitry Andric 1272fe6060f1SDimitry Andric // Handle tail using a regular check. 1273bdd1243dSDimitry Andric while (Buf < End) { 1274bdd1243dSDimitry Andric if (*Buf == '\n') { 1275bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start + 1); 1276bdd1243dSDimitry Andric } else if (*Buf == '\r') { 12770b57cec5SDimitry Andric // If this is \r\n, skip both characters. 1278bdd1243dSDimitry Andric if (Buf + 1 < End && Buf[1] == '\n') { 1279bdd1243dSDimitry Andric ++Buf; 12800b57cec5SDimitry Andric } 1281bdd1243dSDimitry Andric LineOffsets.push_back(Buf - Start + 1); 1282bdd1243dSDimitry Andric } 1283bdd1243dSDimitry Andric ++Buf; 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric 1286e8d8bef9SDimitry Andric return LineOffsetMapping(LineOffsets, Alloc); 1287e8d8bef9SDimitry Andric } 1288e8d8bef9SDimitry Andric 1289e8d8bef9SDimitry Andric LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets, 1290e8d8bef9SDimitry Andric llvm::BumpPtrAllocator &Alloc) 1291e8d8bef9SDimitry Andric : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) { 1292e8d8bef9SDimitry Andric Storage[0] = LineOffsets.size(); 1293e8d8bef9SDimitry Andric std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1); 12940b57cec5SDimitry Andric } 12950b57cec5SDimitry Andric 12960b57cec5SDimitry Andric /// getLineNumber - Given a SourceLocation, return the spelling line number 12970b57cec5SDimitry Andric /// for the position indicated. This requires building and caching a table of 12980b57cec5SDimitry Andric /// line offsets for the MemoryBuffer, so this is not cheap: use only when 12990b57cec5SDimitry Andric /// about to emit a diagnostic. 13000b57cec5SDimitry Andric unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, 13010b57cec5SDimitry Andric bool *Invalid) const { 13020b57cec5SDimitry Andric if (FID.isInvalid()) { 13030b57cec5SDimitry Andric if (Invalid) 13040b57cec5SDimitry Andric *Invalid = true; 13050b57cec5SDimitry Andric return 1; 13060b57cec5SDimitry Andric } 13070b57cec5SDimitry Andric 1308e8d8bef9SDimitry Andric const ContentCache *Content; 13090b57cec5SDimitry Andric if (LastLineNoFileIDQuery == FID) 13100b57cec5SDimitry Andric Content = LastLineNoContentCache; 13110b57cec5SDimitry Andric else { 13120b57cec5SDimitry Andric bool MyInvalid = false; 13130b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid); 13140b57cec5SDimitry Andric if (MyInvalid || !Entry.isFile()) { 13150b57cec5SDimitry Andric if (Invalid) 13160b57cec5SDimitry Andric *Invalid = true; 13170b57cec5SDimitry Andric return 1; 13180b57cec5SDimitry Andric } 13190b57cec5SDimitry Andric 1320e8d8bef9SDimitry Andric Content = &Entry.getFile().getContentCache(); 13210b57cec5SDimitry Andric } 13220b57cec5SDimitry Andric 13230b57cec5SDimitry Andric // If this is the first use of line information for this buffer, compute the 13245f757f3fSDimitry Andric // SourceLineCache for it on demand. 13250b57cec5SDimitry Andric if (!Content->SourceLineCache) { 1326bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer = 1327e8d8bef9SDimitry Andric Content->getBufferOrNone(Diag, getFileManager(), SourceLocation()); 13280b57cec5SDimitry Andric if (Invalid) 1329e8d8bef9SDimitry Andric *Invalid = !Buffer; 1330e8d8bef9SDimitry Andric if (!Buffer) 13310b57cec5SDimitry Andric return 1; 1332e8d8bef9SDimitry Andric 1333e8d8bef9SDimitry Andric Content->SourceLineCache = 1334e8d8bef9SDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc); 13350b57cec5SDimitry Andric } else if (Invalid) 13360b57cec5SDimitry Andric *Invalid = false; 13370b57cec5SDimitry Andric 13380b57cec5SDimitry Andric // Okay, we know we have a line number table. Do a binary search to find the 13390b57cec5SDimitry Andric // line number that this character position lands on. 1340e8d8bef9SDimitry Andric const unsigned *SourceLineCache = Content->SourceLineCache.begin(); 1341e8d8bef9SDimitry Andric const unsigned *SourceLineCacheStart = SourceLineCache; 1342e8d8bef9SDimitry Andric const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end(); 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric unsigned QueriedFilePos = FilePos+1; 13450b57cec5SDimitry Andric 13460b57cec5SDimitry Andric // FIXME: I would like to be convinced that this code is worth being as 13470b57cec5SDimitry Andric // complicated as it is, binary search isn't that slow. 13480b57cec5SDimitry Andric // 13490b57cec5SDimitry Andric // If it is worth being optimized, then in my opinion it could be more 13500b57cec5SDimitry Andric // performant, simpler, and more obviously correct by just "galloping" outward 13510b57cec5SDimitry Andric // from the queried file position. In fact, this could be incorporated into a 13520b57cec5SDimitry Andric // generic algorithm such as lower_bound_with_hint. 13530b57cec5SDimitry Andric // 13540b57cec5SDimitry Andric // If someone gives me a test case where this matters, and I will do it! - DWD 13550b57cec5SDimitry Andric 13560b57cec5SDimitry Andric // If the previous query was to the same file, we know both the file pos from 13570b57cec5SDimitry Andric // that query and the line number returned. This allows us to narrow the 13580b57cec5SDimitry Andric // search space from the entire file to something near the match. 13590b57cec5SDimitry Andric if (LastLineNoFileIDQuery == FID) { 13600b57cec5SDimitry Andric if (QueriedFilePos >= LastLineNoFilePos) { 13610b57cec5SDimitry Andric // FIXME: Potential overflow? 13620b57cec5SDimitry Andric SourceLineCache = SourceLineCache+LastLineNoResult-1; 13630b57cec5SDimitry Andric 13640b57cec5SDimitry Andric // The query is likely to be nearby the previous one. Here we check to 13650b57cec5SDimitry Andric // see if it is within 5, 10 or 20 lines. It can be far away in cases 13660b57cec5SDimitry Andric // where big comment blocks and vertical whitespace eat up lines but 13670b57cec5SDimitry Andric // contribute no tokens. 13680b57cec5SDimitry Andric if (SourceLineCache+5 < SourceLineCacheEnd) { 13690b57cec5SDimitry Andric if (SourceLineCache[5] > QueriedFilePos) 13700b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+5; 13710b57cec5SDimitry Andric else if (SourceLineCache+10 < SourceLineCacheEnd) { 13720b57cec5SDimitry Andric if (SourceLineCache[10] > QueriedFilePos) 13730b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+10; 13740b57cec5SDimitry Andric else if (SourceLineCache+20 < SourceLineCacheEnd) { 13750b57cec5SDimitry Andric if (SourceLineCache[20] > QueriedFilePos) 13760b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+20; 13770b57cec5SDimitry Andric } 13780b57cec5SDimitry Andric } 13790b57cec5SDimitry Andric } 13800b57cec5SDimitry Andric } else { 1381e8d8bef9SDimitry Andric if (LastLineNoResult < Content->SourceLineCache.size()) 13820b57cec5SDimitry Andric SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; 13830b57cec5SDimitry Andric } 13840b57cec5SDimitry Andric } 13850b57cec5SDimitry Andric 1386e8d8bef9SDimitry Andric const unsigned *Pos = 1387e8d8bef9SDimitry Andric std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); 13880b57cec5SDimitry Andric unsigned LineNo = Pos-SourceLineCacheStart; 13890b57cec5SDimitry Andric 13900b57cec5SDimitry Andric LastLineNoFileIDQuery = FID; 13910b57cec5SDimitry Andric LastLineNoContentCache = Content; 13920b57cec5SDimitry Andric LastLineNoFilePos = QueriedFilePos; 13930b57cec5SDimitry Andric LastLineNoResult = LineNo; 13940b57cec5SDimitry Andric return LineNo; 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, 13980b57cec5SDimitry Andric bool *Invalid) const { 13990b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0; 14000b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 14010b57cec5SDimitry Andric return getLineNumber(LocInfo.first, LocInfo.second); 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc, 14040b57cec5SDimitry Andric bool *Invalid) const { 14050b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return 0; 14060b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 14070b57cec5SDimitry Andric return getLineNumber(LocInfo.first, LocInfo.second); 14080b57cec5SDimitry Andric } 14090b57cec5SDimitry Andric unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc, 14100b57cec5SDimitry Andric bool *Invalid) const { 14110b57cec5SDimitry Andric PresumedLoc PLoc = getPresumedLoc(Loc); 14120b57cec5SDimitry Andric if (isInvalid(PLoc, Invalid)) return 0; 14130b57cec5SDimitry Andric return PLoc.getLine(); 14140b57cec5SDimitry Andric } 14150b57cec5SDimitry Andric 14160b57cec5SDimitry Andric /// getFileCharacteristic - return the file characteristic of the specified 14170b57cec5SDimitry Andric /// source location, indicating whether this is a normal file, a system 14180b57cec5SDimitry Andric /// header, or an "implicit extern C" system header. 14190b57cec5SDimitry Andric /// 14200b57cec5SDimitry Andric /// This state can be modified with flags on GNU linemarker directives like: 14210b57cec5SDimitry Andric /// # 4 "foo.h" 3 14220b57cec5SDimitry Andric /// which changes all source locations in the current file after that to be 14230b57cec5SDimitry Andric /// considered to be from a system header. 14240b57cec5SDimitry Andric SrcMgr::CharacteristicKind 14250b57cec5SDimitry Andric SourceManager::getFileCharacteristic(SourceLocation Loc) const { 14260b57cec5SDimitry Andric assert(Loc.isValid() && "Can't get file characteristic of invalid loc!"); 14270b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 1428e8d8bef9SDimitry Andric const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first); 1429e8d8bef9SDimitry Andric if (!SEntry) 14300b57cec5SDimitry Andric return C_User; 14310b57cec5SDimitry Andric 1432e8d8bef9SDimitry Andric const SrcMgr::FileInfo &FI = SEntry->getFile(); 14330b57cec5SDimitry Andric 14340b57cec5SDimitry Andric // If there are no #line directives in this file, just return the whole-file 14350b57cec5SDimitry Andric // state. 14360b57cec5SDimitry Andric if (!FI.hasLineDirectives()) 14370b57cec5SDimitry Andric return FI.getFileCharacteristic(); 14380b57cec5SDimitry Andric 14390b57cec5SDimitry Andric assert(LineTable && "Can't have linetable entries without a LineTable!"); 14400b57cec5SDimitry Andric // See if there is a #line directive before the location. 14410b57cec5SDimitry Andric const LineEntry *Entry = 14420b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second); 14430b57cec5SDimitry Andric 14440b57cec5SDimitry Andric // If this is before the first line marker, use the file characteristic. 14450b57cec5SDimitry Andric if (!Entry) 14460b57cec5SDimitry Andric return FI.getFileCharacteristic(); 14470b57cec5SDimitry Andric 14480b57cec5SDimitry Andric return Entry->FileKind; 14490b57cec5SDimitry Andric } 14500b57cec5SDimitry Andric 14510b57cec5SDimitry Andric /// Return the filename or buffer identifier of the buffer the location is in. 14520b57cec5SDimitry Andric /// Note that this name does not respect \#line directives. Use getPresumedLoc 14530b57cec5SDimitry Andric /// for normal clients. 14540b57cec5SDimitry Andric StringRef SourceManager::getBufferName(SourceLocation Loc, 14550b57cec5SDimitry Andric bool *Invalid) const { 14560b57cec5SDimitry Andric if (isInvalid(Loc, Invalid)) return "<invalid loc>"; 14570b57cec5SDimitry Andric 1458e8d8bef9SDimitry Andric auto B = getBufferOrNone(getFileID(Loc)); 1459e8d8bef9SDimitry Andric if (Invalid) 1460e8d8bef9SDimitry Andric *Invalid = !B; 1461e8d8bef9SDimitry Andric return B ? B->getBufferIdentifier() : "<invalid buffer>"; 14620b57cec5SDimitry Andric } 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric /// getPresumedLoc - This method returns the "presumed" location of a 14650b57cec5SDimitry Andric /// SourceLocation specifies. A "presumed location" can be modified by \#line 14660b57cec5SDimitry Andric /// or GNU line marker directives. This provides a view on the data that a 14670b57cec5SDimitry Andric /// user should see in diagnostics, for example. 14680b57cec5SDimitry Andric /// 14690b57cec5SDimitry Andric /// Note that a presumed location is always given as the expansion point of an 14700b57cec5SDimitry Andric /// expansion location, not at the spelling location. 14710b57cec5SDimitry Andric PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, 14720b57cec5SDimitry Andric bool UseLineDirectives) const { 14730b57cec5SDimitry Andric if (Loc.isInvalid()) return PresumedLoc(); 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric // Presumed locations are always for expansion points. 14760b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 14770b57cec5SDimitry Andric 14780b57cec5SDimitry Andric bool Invalid = false; 14790b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); 14800b57cec5SDimitry Andric if (Invalid || !Entry.isFile()) 14810b57cec5SDimitry Andric return PresumedLoc(); 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric const SrcMgr::FileInfo &FI = Entry.getFile(); 1484e8d8bef9SDimitry Andric const SrcMgr::ContentCache *C = &FI.getContentCache(); 14850b57cec5SDimitry Andric 14860b57cec5SDimitry Andric // To get the source name, first consult the FileEntry (if one exists) 14870b57cec5SDimitry Andric // before the MemBuffer as this will avoid unnecessarily paging in the 14880b57cec5SDimitry Andric // MemBuffer. 14890b57cec5SDimitry Andric FileID FID = LocInfo.first; 14900b57cec5SDimitry Andric StringRef Filename; 14910b57cec5SDimitry Andric if (C->OrigEntry) 14920b57cec5SDimitry Andric Filename = C->OrigEntry->getName(); 1493e8d8bef9SDimitry Andric else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager())) 1494e8d8bef9SDimitry Andric Filename = Buffer->getBufferIdentifier(); 14950b57cec5SDimitry Andric 14960b57cec5SDimitry Andric unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid); 14970b57cec5SDimitry Andric if (Invalid) 14980b57cec5SDimitry Andric return PresumedLoc(); 14990b57cec5SDimitry Andric unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); 15000b57cec5SDimitry Andric if (Invalid) 15010b57cec5SDimitry Andric return PresumedLoc(); 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric SourceLocation IncludeLoc = FI.getIncludeLoc(); 15040b57cec5SDimitry Andric 15050b57cec5SDimitry Andric // If we have #line directives in this file, update and overwrite the physical 15060b57cec5SDimitry Andric // location info if appropriate. 15070b57cec5SDimitry Andric if (UseLineDirectives && FI.hasLineDirectives()) { 15080b57cec5SDimitry Andric assert(LineTable && "Can't have linetable entries without a LineTable!"); 15090b57cec5SDimitry Andric // See if there is a #line directive before this. If so, get it. 15100b57cec5SDimitry Andric if (const LineEntry *Entry = 15110b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) { 15120b57cec5SDimitry Andric // If the LineEntry indicates a filename, use it. 15130b57cec5SDimitry Andric if (Entry->FilenameID != -1) { 15140b57cec5SDimitry Andric Filename = LineTable->getFilename(Entry->FilenameID); 15150b57cec5SDimitry Andric // The contents of files referenced by #line are not in the 15160b57cec5SDimitry Andric // SourceManager 15170b57cec5SDimitry Andric FID = FileID::get(0); 15180b57cec5SDimitry Andric } 15190b57cec5SDimitry Andric 15200b57cec5SDimitry Andric // Use the line number specified by the LineEntry. This line number may 15210b57cec5SDimitry Andric // be multiple lines down from the line entry. Add the difference in 15220b57cec5SDimitry Andric // physical line numbers from the query point and the line marker to the 15230b57cec5SDimitry Andric // total. 15240b57cec5SDimitry Andric unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); 15250b57cec5SDimitry Andric LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric // Note that column numbers are not molested by line markers. 15280b57cec5SDimitry Andric 15290b57cec5SDimitry Andric // Handle virtual #include manipulation. 15300b57cec5SDimitry Andric if (Entry->IncludeOffset) { 15310b57cec5SDimitry Andric IncludeLoc = getLocForStartOfFile(LocInfo.first); 15320b57cec5SDimitry Andric IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset); 15330b57cec5SDimitry Andric } 15340b57cec5SDimitry Andric } 15350b57cec5SDimitry Andric } 15360b57cec5SDimitry Andric 15370b57cec5SDimitry Andric return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc); 15380b57cec5SDimitry Andric } 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric /// Returns whether the PresumedLoc for a given SourceLocation is 15410b57cec5SDimitry Andric /// in the main file. 15420b57cec5SDimitry Andric /// 15430b57cec5SDimitry Andric /// This computes the "presumed" location for a SourceLocation, then checks 15440b57cec5SDimitry Andric /// whether it came from a file other than the main file. This is different 15450b57cec5SDimitry Andric /// from isWrittenInMainFile() because it takes line marker directives into 15460b57cec5SDimitry Andric /// account. 15470b57cec5SDimitry Andric bool SourceManager::isInMainFile(SourceLocation Loc) const { 15480b57cec5SDimitry Andric if (Loc.isInvalid()) return false; 15490b57cec5SDimitry Andric 15500b57cec5SDimitry Andric // Presumed locations are always for expansion points. 15510b57cec5SDimitry Andric std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); 15520b57cec5SDimitry Andric 1553e8d8bef9SDimitry Andric const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first); 1554e8d8bef9SDimitry Andric if (!Entry) 15550b57cec5SDimitry Andric return false; 15560b57cec5SDimitry Andric 1557e8d8bef9SDimitry Andric const SrcMgr::FileInfo &FI = Entry->getFile(); 15580b57cec5SDimitry Andric 15590b57cec5SDimitry Andric // Check if there is a line directive for this location. 15600b57cec5SDimitry Andric if (FI.hasLineDirectives()) 15610b57cec5SDimitry Andric if (const LineEntry *Entry = 15620b57cec5SDimitry Andric LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) 15630b57cec5SDimitry Andric if (Entry->IncludeOffset) 15640b57cec5SDimitry Andric return false; 15650b57cec5SDimitry Andric 15660b57cec5SDimitry Andric return FI.getIncludeLoc().isInvalid(); 15670b57cec5SDimitry Andric } 15680b57cec5SDimitry Andric 15690b57cec5SDimitry Andric /// The size of the SLocEntry that \p FID represents. 15700b57cec5SDimitry Andric unsigned SourceManager::getFileIDSize(FileID FID) const { 15710b57cec5SDimitry Andric bool Invalid = false; 15720b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); 15730b57cec5SDimitry Andric if (Invalid) 15740b57cec5SDimitry Andric return 0; 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric int ID = FID.ID; 1577fe6060f1SDimitry Andric SourceLocation::UIntTy NextOffset; 15780b57cec5SDimitry Andric if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size())) 15790b57cec5SDimitry Andric NextOffset = getNextLocalOffset(); 15800b57cec5SDimitry Andric else if (ID+1 == -1) 15810b57cec5SDimitry Andric NextOffset = MaxLoadedOffset; 15820b57cec5SDimitry Andric else 15830b57cec5SDimitry Andric NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset(); 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric return NextOffset - Entry.getOffset() - 1; 15860b57cec5SDimitry Andric } 15870b57cec5SDimitry Andric 15880b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15890b57cec5SDimitry Andric // Other miscellaneous methods. 15900b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15910b57cec5SDimitry Andric 15920b57cec5SDimitry Andric /// Get the source location for the given file:line:col triplet. 15930b57cec5SDimitry Andric /// 15940b57cec5SDimitry Andric /// If the source file is included multiple times, the source location will 15950b57cec5SDimitry Andric /// be based upon an arbitrary inclusion. 15960b57cec5SDimitry Andric SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile, 15970b57cec5SDimitry Andric unsigned Line, 15980b57cec5SDimitry Andric unsigned Col) const { 15990b57cec5SDimitry Andric assert(SourceFile && "Null source file!"); 16000b57cec5SDimitry Andric assert(Line && Col && "Line and column should start from 1!"); 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric FileID FirstFID = translateFile(SourceFile); 16030b57cec5SDimitry Andric return translateLineCol(FirstFID, Line, Col); 16040b57cec5SDimitry Andric } 16050b57cec5SDimitry Andric 16060b57cec5SDimitry Andric /// Get the FileID for the given file. 16070b57cec5SDimitry Andric /// 16080b57cec5SDimitry Andric /// If the source file is included multiple times, the FileID will be the 16090b57cec5SDimitry Andric /// first inclusion. 16100b57cec5SDimitry Andric FileID SourceManager::translateFile(const FileEntry *SourceFile) const { 16110b57cec5SDimitry Andric assert(SourceFile && "Null source file!"); 16120b57cec5SDimitry Andric 16130b57cec5SDimitry Andric // First, check the main file ID, since it is common to look for a 16140b57cec5SDimitry Andric // location in the main file. 16150b57cec5SDimitry Andric if (MainFileID.isValid()) { 16160b57cec5SDimitry Andric bool Invalid = false; 16170b57cec5SDimitry Andric const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); 16180b57cec5SDimitry Andric if (Invalid) 16190b57cec5SDimitry Andric return FileID(); 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric if (MainSLoc.isFile()) { 1622e8d8bef9SDimitry Andric if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile) 1623a7dea167SDimitry Andric return MainFileID; 16240b57cec5SDimitry Andric } 16250b57cec5SDimitry Andric } 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric // The location we're looking for isn't in the main file; look 16280b57cec5SDimitry Andric // through all of the local source locations. 16290b57cec5SDimitry Andric for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { 16305ffd83dbSDimitry Andric const SLocEntry &SLoc = getLocalSLocEntry(I); 1631e8d8bef9SDimitry Andric if (SLoc.isFile() && 1632e8d8bef9SDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile) 1633a7dea167SDimitry Andric return FileID::get(I); 16340b57cec5SDimitry Andric } 1635a7dea167SDimitry Andric 16360b57cec5SDimitry Andric // If that still didn't help, try the modules. 16370b57cec5SDimitry Andric for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { 16380b57cec5SDimitry Andric const SLocEntry &SLoc = getLoadedSLocEntry(I); 1639e8d8bef9SDimitry Andric if (SLoc.isFile() && 1640e8d8bef9SDimitry Andric SLoc.getFile().getContentCache().OrigEntry == SourceFile) 1641a7dea167SDimitry Andric return FileID::get(-int(I) - 2); 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric return FileID(); 16450b57cec5SDimitry Andric } 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric /// Get the source location in \arg FID for the given line:col. 16480b57cec5SDimitry Andric /// Returns null location if \arg FID is not a file SLocEntry. 16490b57cec5SDimitry Andric SourceLocation SourceManager::translateLineCol(FileID FID, 16500b57cec5SDimitry Andric unsigned Line, 16510b57cec5SDimitry Andric unsigned Col) const { 16520b57cec5SDimitry Andric // Lines are used as a one-based index into a zero-based array. This assert 16530b57cec5SDimitry Andric // checks for possible buffer underruns. 16540b57cec5SDimitry Andric assert(Line && Col && "Line and column should start from 1!"); 16550b57cec5SDimitry Andric 16560b57cec5SDimitry Andric if (FID.isInvalid()) 16570b57cec5SDimitry Andric return SourceLocation(); 16580b57cec5SDimitry Andric 16590b57cec5SDimitry Andric bool Invalid = false; 16600b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(FID, &Invalid); 16610b57cec5SDimitry Andric if (Invalid) 16620b57cec5SDimitry Andric return SourceLocation(); 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric if (!Entry.isFile()) 16650b57cec5SDimitry Andric return SourceLocation(); 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset()); 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric if (Line == 1 && Col == 1) 16700b57cec5SDimitry Andric return FileLoc; 16710b57cec5SDimitry Andric 1672e8d8bef9SDimitry Andric const ContentCache *Content = &Entry.getFile().getContentCache(); 16730b57cec5SDimitry Andric 16740b57cec5SDimitry Andric // If this is the first use of line information for this buffer, compute the 16750b57cec5SDimitry Andric // SourceLineCache for it on demand. 1676bdd1243dSDimitry Andric std::optional<llvm::MemoryBufferRef> Buffer = 1677e8d8bef9SDimitry Andric Content->getBufferOrNone(Diag, getFileManager()); 1678e8d8bef9SDimitry Andric if (!Buffer) 16790b57cec5SDimitry Andric return SourceLocation(); 1680e8d8bef9SDimitry Andric if (!Content->SourceLineCache) 1681e8d8bef9SDimitry Andric Content->SourceLineCache = 1682e8d8bef9SDimitry Andric LineOffsetMapping::get(*Buffer, ContentCacheAlloc); 16830b57cec5SDimitry Andric 1684e8d8bef9SDimitry Andric if (Line > Content->SourceLineCache.size()) { 1685e8d8bef9SDimitry Andric unsigned Size = Buffer->getBufferSize(); 16860b57cec5SDimitry Andric if (Size > 0) 16870b57cec5SDimitry Andric --Size; 16880b57cec5SDimitry Andric return FileLoc.getLocWithOffset(Size); 16890b57cec5SDimitry Andric } 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric unsigned FilePos = Content->SourceLineCache[Line - 1]; 16920b57cec5SDimitry Andric const char *Buf = Buffer->getBufferStart() + FilePos; 16930b57cec5SDimitry Andric unsigned BufLength = Buffer->getBufferSize() - FilePos; 16940b57cec5SDimitry Andric if (BufLength == 0) 16950b57cec5SDimitry Andric return FileLoc.getLocWithOffset(FilePos); 16960b57cec5SDimitry Andric 16970b57cec5SDimitry Andric unsigned i = 0; 16980b57cec5SDimitry Andric 16990b57cec5SDimitry Andric // Check that the given column is valid. 17000b57cec5SDimitry Andric while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') 17010b57cec5SDimitry Andric ++i; 17020b57cec5SDimitry Andric return FileLoc.getLocWithOffset(FilePos + i); 17030b57cec5SDimitry Andric } 17040b57cec5SDimitry Andric 17050b57cec5SDimitry Andric /// Compute a map of macro argument chunks to their expanded source 17060b57cec5SDimitry Andric /// location. Chunks that are not part of a macro argument will map to an 17070b57cec5SDimitry Andric /// invalid source location. e.g. if a file contains one macro argument at 17080b57cec5SDimitry Andric /// offset 100 with length 10, this is how the map will be formed: 17090b57cec5SDimitry Andric /// 0 -> SourceLocation() 17100b57cec5SDimitry Andric /// 100 -> Expanded macro arg location 17110b57cec5SDimitry Andric /// 110 -> SourceLocation() 17120b57cec5SDimitry Andric void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache, 17130b57cec5SDimitry Andric FileID FID) const { 17140b57cec5SDimitry Andric assert(FID.isValid()); 17150b57cec5SDimitry Andric 17160b57cec5SDimitry Andric // Initially no macro argument chunk is present. 17170b57cec5SDimitry Andric MacroArgsCache.insert(std::make_pair(0, SourceLocation())); 17180b57cec5SDimitry Andric 17190b57cec5SDimitry Andric int ID = FID.ID; 17200b57cec5SDimitry Andric while (true) { 17210b57cec5SDimitry Andric ++ID; 17220b57cec5SDimitry Andric // Stop if there are no more FileIDs to check. 17230b57cec5SDimitry Andric if (ID > 0) { 17240b57cec5SDimitry Andric if (unsigned(ID) >= local_sloc_entry_size()) 17250b57cec5SDimitry Andric return; 17260b57cec5SDimitry Andric } else if (ID == -1) { 17270b57cec5SDimitry Andric return; 17280b57cec5SDimitry Andric } 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric bool Invalid = false; 17310b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid); 17320b57cec5SDimitry Andric if (Invalid) 17330b57cec5SDimitry Andric return; 17340b57cec5SDimitry Andric if (Entry.isFile()) { 1735e8d8bef9SDimitry Andric auto& File = Entry.getFile(); 1736e8d8bef9SDimitry Andric if (File.getFileCharacteristic() == C_User_ModuleMap || 1737e8d8bef9SDimitry Andric File.getFileCharacteristic() == C_System_ModuleMap) 1738e8d8bef9SDimitry Andric continue; 1739e8d8bef9SDimitry Andric 1740e8d8bef9SDimitry Andric SourceLocation IncludeLoc = File.getIncludeLoc(); 17415ffd83dbSDimitry Andric bool IncludedInFID = 17425ffd83dbSDimitry Andric (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) || 17435ffd83dbSDimitry Andric // Predefined header doesn't have a valid include location in main 17445ffd83dbSDimitry Andric // file, but any files created by it should still be skipped when 17455ffd83dbSDimitry Andric // computing macro args expanded in the main file. 1746e8d8bef9SDimitry Andric (FID == MainFileID && Entry.getFile().getName() == "<built-in>"); 17475ffd83dbSDimitry Andric if (IncludedInFID) { 17485ffd83dbSDimitry Andric // Skip the files/macros of the #include'd file, we only care about 17495ffd83dbSDimitry Andric // macros that lexed macro arguments from our file. 17500b57cec5SDimitry Andric if (Entry.getFile().NumCreatedFIDs) 17510b57cec5SDimitry Andric ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/; 17520b57cec5SDimitry Andric continue; 1753bdd1243dSDimitry Andric } 17545ffd83dbSDimitry Andric // If file was included but not from FID, there is no more files/macros 17555ffd83dbSDimitry Andric // that may be "contained" in this file. 1756bdd1243dSDimitry Andric if (IncludeLoc.isValid()) 17575ffd83dbSDimitry Andric return; 17585ffd83dbSDimitry Andric continue; 17590b57cec5SDimitry Andric } 17600b57cec5SDimitry Andric 17610b57cec5SDimitry Andric const ExpansionInfo &ExpInfo = Entry.getExpansion(); 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric if (ExpInfo.getExpansionLocStart().isFileID()) { 17640b57cec5SDimitry Andric if (!isInFileID(ExpInfo.getExpansionLocStart(), FID)) 17650b57cec5SDimitry Andric return; // No more files/macros that may be "contained" in this file. 17660b57cec5SDimitry Andric } 17670b57cec5SDimitry Andric 17680b57cec5SDimitry Andric if (!ExpInfo.isMacroArgExpansion()) 17690b57cec5SDimitry Andric continue; 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID, 17720b57cec5SDimitry Andric ExpInfo.getSpellingLoc(), 17730b57cec5SDimitry Andric SourceLocation::getMacroLoc(Entry.getOffset()), 17740b57cec5SDimitry Andric getFileIDSize(FileID::get(ID))); 17750b57cec5SDimitry Andric } 17760b57cec5SDimitry Andric } 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric void SourceManager::associateFileChunkWithMacroArgExp( 17790b57cec5SDimitry Andric MacroArgsMap &MacroArgsCache, 17800b57cec5SDimitry Andric FileID FID, 17810b57cec5SDimitry Andric SourceLocation SpellLoc, 17820b57cec5SDimitry Andric SourceLocation ExpansionLoc, 17830b57cec5SDimitry Andric unsigned ExpansionLength) const { 17840b57cec5SDimitry Andric if (!SpellLoc.isFileID()) { 1785fe6060f1SDimitry Andric SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset(); 1786fe6060f1SDimitry Andric SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength; 17870b57cec5SDimitry Andric 17880b57cec5SDimitry Andric // The spelling range for this macro argument expansion can span multiple 17890b57cec5SDimitry Andric // consecutive FileID entries. Go through each entry contained in the 17900b57cec5SDimitry Andric // spelling range and if one is itself a macro argument expansion, recurse 17910b57cec5SDimitry Andric // and associate the file chunk that it represents. 17920b57cec5SDimitry Andric 17930b57cec5SDimitry Andric FileID SpellFID; // Current FileID in the spelling range. 17940b57cec5SDimitry Andric unsigned SpellRelativeOffs; 17950b57cec5SDimitry Andric std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc); 17960b57cec5SDimitry Andric while (true) { 17970b57cec5SDimitry Andric const SLocEntry &Entry = getSLocEntry(SpellFID); 1798fe6060f1SDimitry Andric SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset(); 17990b57cec5SDimitry Andric unsigned SpellFIDSize = getFileIDSize(SpellFID); 1800fe6060f1SDimitry Andric SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize; 18010b57cec5SDimitry Andric const ExpansionInfo &Info = Entry.getExpansion(); 18020b57cec5SDimitry Andric if (Info.isMacroArgExpansion()) { 18030b57cec5SDimitry Andric unsigned CurrSpellLength; 18040b57cec5SDimitry Andric if (SpellFIDEndOffs < SpellEndOffs) 18050b57cec5SDimitry Andric CurrSpellLength = SpellFIDSize - SpellRelativeOffs; 18060b57cec5SDimitry Andric else 18070b57cec5SDimitry Andric CurrSpellLength = ExpansionLength; 18080b57cec5SDimitry Andric associateFileChunkWithMacroArgExp(MacroArgsCache, FID, 18090b57cec5SDimitry Andric Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs), 18100b57cec5SDimitry Andric ExpansionLoc, CurrSpellLength); 18110b57cec5SDimitry Andric } 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric if (SpellFIDEndOffs >= SpellEndOffs) 18140b57cec5SDimitry Andric return; // we covered all FileID entries in the spelling range. 18150b57cec5SDimitry Andric 18160b57cec5SDimitry Andric // Move to the next FileID entry in the spelling range. 18170b57cec5SDimitry Andric unsigned advance = SpellFIDSize - SpellRelativeOffs + 1; 18180b57cec5SDimitry Andric ExpansionLoc = ExpansionLoc.getLocWithOffset(advance); 18190b57cec5SDimitry Andric ExpansionLength -= advance; 18200b57cec5SDimitry Andric ++SpellFID.ID; 18210b57cec5SDimitry Andric SpellRelativeOffs = 0; 18220b57cec5SDimitry Andric } 18230b57cec5SDimitry Andric } 18240b57cec5SDimitry Andric 18250b57cec5SDimitry Andric assert(SpellLoc.isFileID()); 18260b57cec5SDimitry Andric 18270b57cec5SDimitry Andric unsigned BeginOffs; 18280b57cec5SDimitry Andric if (!isInFileID(SpellLoc, FID, &BeginOffs)) 18290b57cec5SDimitry Andric return; 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric unsigned EndOffs = BeginOffs + ExpansionLength; 18320b57cec5SDimitry Andric 18330b57cec5SDimitry Andric // Add a new chunk for this macro argument. A previous macro argument chunk 18340b57cec5SDimitry Andric // may have been lexed again, so e.g. if the map is 18350b57cec5SDimitry Andric // 0 -> SourceLocation() 18360b57cec5SDimitry Andric // 100 -> Expanded loc #1 18370b57cec5SDimitry Andric // 110 -> SourceLocation() 18380b57cec5SDimitry Andric // and we found a new macro FileID that lexed from offset 105 with length 3, 18390b57cec5SDimitry Andric // the new map will be: 18400b57cec5SDimitry Andric // 0 -> SourceLocation() 18410b57cec5SDimitry Andric // 100 -> Expanded loc #1 18420b57cec5SDimitry Andric // 105 -> Expanded loc #2 18430b57cec5SDimitry Andric // 108 -> Expanded loc #1 18440b57cec5SDimitry Andric // 110 -> SourceLocation() 18450b57cec5SDimitry Andric // 18460b57cec5SDimitry Andric // Since re-lexed macro chunks will always be the same size or less of 18470b57cec5SDimitry Andric // previous chunks, we only need to find where the ending of the new macro 18480b57cec5SDimitry Andric // chunk is mapped to and update the map with new begin/end mappings. 18490b57cec5SDimitry Andric 18500b57cec5SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs); 18510b57cec5SDimitry Andric --I; 18520b57cec5SDimitry Andric SourceLocation EndOffsMappedLoc = I->second; 18530b57cec5SDimitry Andric MacroArgsCache[BeginOffs] = ExpansionLoc; 18540b57cec5SDimitry Andric MacroArgsCache[EndOffs] = EndOffsMappedLoc; 18550b57cec5SDimitry Andric } 18560b57cec5SDimitry Andric 1857*0fca6ea1SDimitry Andric void SourceManager::updateSlocUsageStats() const { 1858*0fca6ea1SDimitry Andric SourceLocation::UIntTy UsedBytes = 1859*0fca6ea1SDimitry Andric NextLocalOffset + (MaxLoadedOffset - CurrentLoadedOffset); 1860*0fca6ea1SDimitry Andric MaxUsedSLocBytes.updateMax(UsedBytes); 1861*0fca6ea1SDimitry Andric } 1862*0fca6ea1SDimitry Andric 18630b57cec5SDimitry Andric /// If \arg Loc points inside a function macro argument, the returned 18640b57cec5SDimitry Andric /// location will be the macro location in which the argument was expanded. 18650b57cec5SDimitry Andric /// If a macro argument is used multiple times, the expanded location will 18660b57cec5SDimitry Andric /// be at the first expansion of the argument. 18670b57cec5SDimitry Andric /// e.g. 18680b57cec5SDimitry Andric /// MY_MACRO(foo); 18690b57cec5SDimitry Andric /// ^ 18700b57cec5SDimitry Andric /// Passing a file location pointing at 'foo', will yield a macro location 18710b57cec5SDimitry Andric /// where 'foo' was expanded into. 18720b57cec5SDimitry Andric SourceLocation 18730b57cec5SDimitry Andric SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { 18740b57cec5SDimitry Andric if (Loc.isInvalid() || !Loc.isFileID()) 18750b57cec5SDimitry Andric return Loc; 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric FileID FID; 18780b57cec5SDimitry Andric unsigned Offset; 18790b57cec5SDimitry Andric std::tie(FID, Offset) = getDecomposedLoc(Loc); 18800b57cec5SDimitry Andric if (FID.isInvalid()) 18810b57cec5SDimitry Andric return Loc; 18820b57cec5SDimitry Andric 18830b57cec5SDimitry Andric std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID]; 18840b57cec5SDimitry Andric if (!MacroArgsCache) { 1885a7dea167SDimitry Andric MacroArgsCache = std::make_unique<MacroArgsMap>(); 18860b57cec5SDimitry Andric computeMacroArgsCache(*MacroArgsCache, FID); 18870b57cec5SDimitry Andric } 18880b57cec5SDimitry Andric 18890b57cec5SDimitry Andric assert(!MacroArgsCache->empty()); 18900b57cec5SDimitry Andric MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); 1891e8d8bef9SDimitry Andric // In case every element in MacroArgsCache is greater than Offset we can't 1892e8d8bef9SDimitry Andric // decrement the iterator. 1893e8d8bef9SDimitry Andric if (I == MacroArgsCache->begin()) 1894e8d8bef9SDimitry Andric return Loc; 1895e8d8bef9SDimitry Andric 18960b57cec5SDimitry Andric --I; 18970b57cec5SDimitry Andric 1898fe6060f1SDimitry Andric SourceLocation::UIntTy MacroArgBeginOffs = I->first; 18990b57cec5SDimitry Andric SourceLocation MacroArgExpandedLoc = I->second; 19000b57cec5SDimitry Andric if (MacroArgExpandedLoc.isValid()) 19010b57cec5SDimitry Andric return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs); 19020b57cec5SDimitry Andric 19030b57cec5SDimitry Andric return Loc; 19040b57cec5SDimitry Andric } 19050b57cec5SDimitry Andric 19060b57cec5SDimitry Andric std::pair<FileID, unsigned> 19070b57cec5SDimitry Andric SourceManager::getDecomposedIncludedLoc(FileID FID) const { 19080b57cec5SDimitry Andric if (FID.isInvalid()) 19090b57cec5SDimitry Andric return std::make_pair(FileID(), 0); 19100b57cec5SDimitry Andric 19110b57cec5SDimitry Andric // Uses IncludedLocMap to retrieve/cache the decomposed loc. 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric using DecompTy = std::pair<FileID, unsigned>; 19140b57cec5SDimitry Andric auto InsertOp = IncludedLocMap.try_emplace(FID); 19150b57cec5SDimitry Andric DecompTy &DecompLoc = InsertOp.first->second; 19160b57cec5SDimitry Andric if (!InsertOp.second) 19170b57cec5SDimitry Andric return DecompLoc; // already in map. 19180b57cec5SDimitry Andric 19190b57cec5SDimitry Andric SourceLocation UpperLoc; 19200b57cec5SDimitry Andric bool Invalid = false; 19210b57cec5SDimitry Andric const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); 19220b57cec5SDimitry Andric if (!Invalid) { 19230b57cec5SDimitry Andric if (Entry.isExpansion()) 19240b57cec5SDimitry Andric UpperLoc = Entry.getExpansion().getExpansionLocStart(); 19250b57cec5SDimitry Andric else 19260b57cec5SDimitry Andric UpperLoc = Entry.getFile().getIncludeLoc(); 19270b57cec5SDimitry Andric } 19280b57cec5SDimitry Andric 19290b57cec5SDimitry Andric if (UpperLoc.isValid()) 19300b57cec5SDimitry Andric DecompLoc = getDecomposedLoc(UpperLoc); 19310b57cec5SDimitry Andric 19320b57cec5SDimitry Andric return DecompLoc; 19330b57cec5SDimitry Andric } 19340b57cec5SDimitry Andric 1935*0fca6ea1SDimitry Andric FileID SourceManager::getUniqueLoadedASTFileID(SourceLocation Loc) const { 1936*0fca6ea1SDimitry Andric assert(isLoadedSourceLocation(Loc) && 1937*0fca6ea1SDimitry Andric "Must be a source location in a loaded PCH/Module file"); 1938*0fca6ea1SDimitry Andric 1939*0fca6ea1SDimitry Andric auto [FID, Ignore] = getDecomposedLoc(Loc); 1940*0fca6ea1SDimitry Andric // `LoadedSLocEntryAllocBegin` stores the sorted lowest FID of each loaded 1941*0fca6ea1SDimitry Andric // allocation. Later allocations have lower FileIDs. The call below is to find 1942*0fca6ea1SDimitry Andric // the lowest FID of a loaded allocation from any FID in the same allocation. 1943*0fca6ea1SDimitry Andric // The lowest FID is used to identify a loaded allocation. 1944*0fca6ea1SDimitry Andric const FileID *FirstFID = 1945*0fca6ea1SDimitry Andric llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, std::greater<FileID>{}); 1946*0fca6ea1SDimitry Andric 1947*0fca6ea1SDimitry Andric assert(FirstFID && 1948*0fca6ea1SDimitry Andric "The failure to find the first FileID of a " 1949*0fca6ea1SDimitry Andric "loaded AST from a loaded source location was unexpected."); 1950*0fca6ea1SDimitry Andric return *FirstFID; 1951*0fca6ea1SDimitry Andric } 1952*0fca6ea1SDimitry Andric 19535f757f3fSDimitry Andric bool SourceManager::isInTheSameTranslationUnitImpl( 19545f757f3fSDimitry Andric const std::pair<FileID, unsigned> &LOffs, 19555f757f3fSDimitry Andric const std::pair<FileID, unsigned> &ROffs) const { 19565f757f3fSDimitry Andric // If one is local while the other is loaded. 19575f757f3fSDimitry Andric if (isLoadedFileID(LOffs.first) != isLoadedFileID(ROffs.first)) 19585f757f3fSDimitry Andric return false; 19595f757f3fSDimitry Andric 19605f757f3fSDimitry Andric if (isLoadedFileID(LOffs.first) && isLoadedFileID(ROffs.first)) { 19615f757f3fSDimitry Andric auto FindSLocEntryAlloc = [this](FileID FID) { 19625f757f3fSDimitry Andric // Loaded FileIDs are negative, we store the lowest FileID from each 19635f757f3fSDimitry Andric // allocation, later allocations have lower FileIDs. 19645f757f3fSDimitry Andric return llvm::lower_bound(LoadedSLocEntryAllocBegin, FID, 19655f757f3fSDimitry Andric std::greater<FileID>{}); 19665f757f3fSDimitry Andric }; 19675f757f3fSDimitry Andric 19685f757f3fSDimitry Andric // If both are loaded from different AST files. 19695f757f3fSDimitry Andric if (FindSLocEntryAlloc(LOffs.first) != FindSLocEntryAlloc(ROffs.first)) 19705f757f3fSDimitry Andric return false; 19715f757f3fSDimitry Andric } 19725f757f3fSDimitry Andric 19735f757f3fSDimitry Andric return true; 19745f757f3fSDimitry Andric } 19755f757f3fSDimitry Andric 19760b57cec5SDimitry Andric /// Given a decomposed source location, move it up the include/expansion stack 19775f757f3fSDimitry Andric /// to the parent source location within the same translation unit. If this is 19785f757f3fSDimitry Andric /// possible, return the decomposed version of the parent in Loc and return 19795f757f3fSDimitry Andric /// false. If Loc is a top-level entry, return true and don't modify it. 19805f757f3fSDimitry Andric static bool 19815f757f3fSDimitry Andric MoveUpTranslationUnitIncludeHierarchy(std::pair<FileID, unsigned> &Loc, 19820b57cec5SDimitry Andric const SourceManager &SM) { 19830b57cec5SDimitry Andric std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first); 19845f757f3fSDimitry Andric if (UpperLoc.first.isInvalid() || 19855f757f3fSDimitry Andric !SM.isInTheSameTranslationUnitImpl(UpperLoc, Loc)) 19860b57cec5SDimitry Andric return true; // We reached the top. 19870b57cec5SDimitry Andric 19880b57cec5SDimitry Andric Loc = UpperLoc; 19890b57cec5SDimitry Andric return false; 19900b57cec5SDimitry Andric } 19910b57cec5SDimitry Andric 19920b57cec5SDimitry Andric /// Return the cache entry for comparing the given file IDs 19930b57cec5SDimitry Andric /// for isBeforeInTranslationUnit. 19940b57cec5SDimitry Andric InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID, 19950b57cec5SDimitry Andric FileID RFID) const { 19960b57cec5SDimitry Andric // This is a magic number for limiting the cache size. It was experimentally 19970b57cec5SDimitry Andric // derived from a small Objective-C project (where the cache filled 19980b57cec5SDimitry Andric // out to ~250 items). We can make it larger if necessary. 1999bdd1243dSDimitry Andric // FIXME: this is almost certainly full these days. Use an LRU cache? 20000b57cec5SDimitry Andric enum { MagicCacheSize = 300 }; 20010b57cec5SDimitry Andric IsBeforeInTUCacheKey Key(LFID, RFID); 20020b57cec5SDimitry Andric 20030b57cec5SDimitry Andric // If the cache size isn't too large, do a lookup and if necessary default 20040b57cec5SDimitry Andric // construct an entry. We can then return it to the caller for direct 20050b57cec5SDimitry Andric // use. When they update the value, the cache will get automatically 20060b57cec5SDimitry Andric // updated as well. 20070b57cec5SDimitry Andric if (IBTUCache.size() < MagicCacheSize) 2008bdd1243dSDimitry Andric return IBTUCache.try_emplace(Key, LFID, RFID).first->second; 20090b57cec5SDimitry Andric 20100b57cec5SDimitry Andric // Otherwise, do a lookup that will not construct a new value. 20110b57cec5SDimitry Andric InBeforeInTUCache::iterator I = IBTUCache.find(Key); 20120b57cec5SDimitry Andric if (I != IBTUCache.end()) 20130b57cec5SDimitry Andric return I->second; 20140b57cec5SDimitry Andric 20150b57cec5SDimitry Andric // Fall back to the overflow value. 2016bdd1243dSDimitry Andric IBTUCacheOverflow.setQueryFIDs(LFID, RFID); 20170b57cec5SDimitry Andric return IBTUCacheOverflow; 20180b57cec5SDimitry Andric } 20190b57cec5SDimitry Andric 20200b57cec5SDimitry Andric /// Determines the order of 2 source locations in the translation unit. 20210b57cec5SDimitry Andric /// 20220b57cec5SDimitry Andric /// \returns true if LHS source location comes before RHS, false otherwise. 20230b57cec5SDimitry Andric bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, 20240b57cec5SDimitry Andric SourceLocation RHS) const { 20250b57cec5SDimitry Andric assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); 20260b57cec5SDimitry Andric if (LHS == RHS) 20270b57cec5SDimitry Andric return false; 20280b57cec5SDimitry Andric 20290b57cec5SDimitry Andric std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); 20300b57cec5SDimitry Andric std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); 20310b57cec5SDimitry Andric 20320b57cec5SDimitry Andric // getDecomposedLoc may have failed to return a valid FileID because, e.g. it 20330b57cec5SDimitry Andric // is a serialized one referring to a file that was removed after we loaded 20340b57cec5SDimitry Andric // the PCH. 20350b57cec5SDimitry Andric if (LOffs.first.isInvalid() || ROffs.first.isInvalid()) 20360b57cec5SDimitry Andric return LOffs.first.isInvalid() && !ROffs.first.isInvalid(); 20370b57cec5SDimitry Andric 20380b57cec5SDimitry Andric std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs); 20390b57cec5SDimitry Andric if (InSameTU.first) 20400b57cec5SDimitry Andric return InSameTU.second; 20415f757f3fSDimitry Andric // TODO: This should be unreachable, but some clients are calling this 20425f757f3fSDimitry Andric // function before making sure LHS and RHS are in the same TU. 20430b57cec5SDimitry Andric return LOffs.first < ROffs.first; 20440b57cec5SDimitry Andric } 20450b57cec5SDimitry Andric 20460b57cec5SDimitry Andric std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit( 20470b57cec5SDimitry Andric std::pair<FileID, unsigned> &LOffs, 20480b57cec5SDimitry Andric std::pair<FileID, unsigned> &ROffs) const { 20495f757f3fSDimitry Andric // If the source locations are not in the same TU, return early. 20505f757f3fSDimitry Andric if (!isInTheSameTranslationUnitImpl(LOffs, ROffs)) 20515f757f3fSDimitry Andric return std::make_pair(false, false); 20525f757f3fSDimitry Andric 20530b57cec5SDimitry Andric // If the source locations are in the same file, just compare offsets. 20540b57cec5SDimitry Andric if (LOffs.first == ROffs.first) 20550b57cec5SDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second); 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric // If we are comparing a source location with multiple locations in the same 20580b57cec5SDimitry Andric // file, we get a big win by caching the result. 20590b57cec5SDimitry Andric InBeforeInTUCacheEntry &IsBeforeInTUCache = 20600b57cec5SDimitry Andric getInBeforeInTUCache(LOffs.first, ROffs.first); 20610b57cec5SDimitry Andric 20620b57cec5SDimitry Andric // If we are comparing a source location with multiple locations in the same 20630b57cec5SDimitry Andric // file, we get a big win by caching the result. 2064bdd1243dSDimitry Andric if (IsBeforeInTUCache.isCacheValid()) 20650b57cec5SDimitry Andric return std::make_pair( 20660b57cec5SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); 20670b57cec5SDimitry Andric 2068bdd1243dSDimitry Andric // Okay, we missed in the cache, we'll compute the answer and populate it. 20690b57cec5SDimitry Andric // We need to find the common ancestor. The only way of doing this is to 20700b57cec5SDimitry Andric // build the complete include chain for one and then walking up the chain 20710b57cec5SDimitry Andric // of the other looking for a match. 2072bdd1243dSDimitry Andric 2073bdd1243dSDimitry Andric // A location within a FileID on the path up from LOffs to the main file. 2074bdd1243dSDimitry Andric struct Entry { 20755f757f3fSDimitry Andric std::pair<FileID, unsigned> DecomposedLoc; // FileID redundant, but clearer. 20765f757f3fSDimitry Andric FileID ChildFID; // Used for breaking ties. Invalid for the initial loc. 2077bdd1243dSDimitry Andric }; 2078bdd1243dSDimitry Andric llvm::SmallDenseMap<FileID, Entry, 16> LChain; 2079bdd1243dSDimitry Andric 20805f757f3fSDimitry Andric FileID LChild; 20810b57cec5SDimitry Andric do { 20825f757f3fSDimitry Andric LChain.try_emplace(LOffs.first, Entry{LOffs, LChild}); 20830b57cec5SDimitry Andric // We catch the case where LOffs is in a file included by ROffs and 20840b57cec5SDimitry Andric // quit early. The other way round unfortunately remains suboptimal. 2085bdd1243dSDimitry Andric if (LOffs.first == ROffs.first) 2086bdd1243dSDimitry Andric break; 20875f757f3fSDimitry Andric LChild = LOffs.first; 20885f757f3fSDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(LOffs, *this)); 20890b57cec5SDimitry Andric 20905f757f3fSDimitry Andric FileID RChild; 2091bdd1243dSDimitry Andric do { 20925f757f3fSDimitry Andric auto LIt = LChain.find(ROffs.first); 20935f757f3fSDimitry Andric if (LIt != LChain.end()) { 2094bdd1243dSDimitry Andric // Compare the locations within the common file and cache them. 20955f757f3fSDimitry Andric LOffs = LIt->second.DecomposedLoc; 20965f757f3fSDimitry Andric LChild = LIt->second.ChildFID; 20975f757f3fSDimitry Andric // The relative order of LChild and RChild is a tiebreaker when 2098bdd1243dSDimitry Andric // - locs expand to the same location (occurs in macro arg expansion) 2099bdd1243dSDimitry Andric // - one loc is a parent of the other (we consider the parent as "first") 21005f757f3fSDimitry Andric // For the parent entry to be first, its invalid child file ID must 21015f757f3fSDimitry Andric // compare smaller to the valid child file ID of the other entry. 2102bdd1243dSDimitry Andric // However loaded FileIDs are <0, so we perform *unsigned* comparison! 2103bdd1243dSDimitry Andric // This changes the relative order of local vs loaded FileIDs, but it 2104bdd1243dSDimitry Andric // doesn't matter as these are never mixed in macro expansion. 21055f757f3fSDimitry Andric unsigned LChildID = LChild.ID; 21065f757f3fSDimitry Andric unsigned RChildID = RChild.ID; 2107bdd1243dSDimitry Andric assert(((LOffs.second != ROffs.second) || 21085f757f3fSDimitry Andric (LChildID == 0 || RChildID == 0) || 21095f757f3fSDimitry Andric isInSameSLocAddrSpace(getComposedLoc(LChild, 0), 21105f757f3fSDimitry Andric getComposedLoc(RChild, 0), nullptr)) && 2111bdd1243dSDimitry Andric "Mixed local/loaded FileIDs with same include location?"); 2112bdd1243dSDimitry Andric IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second, 21135f757f3fSDimitry Andric LChildID < RChildID); 21140b57cec5SDimitry Andric return std::make_pair( 21150b57cec5SDimitry Andric true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second)); 21160b57cec5SDimitry Andric } 21175f757f3fSDimitry Andric RChild = ROffs.first; 21185f757f3fSDimitry Andric } while (!MoveUpTranslationUnitIncludeHierarchy(ROffs, *this)); 2119bdd1243dSDimitry Andric 21205f757f3fSDimitry Andric // If we found no match, the location is either in a built-ins buffer or 21215f757f3fSDimitry Andric // associated with global inline asm. PR5662 and PR22576 are examples. 21225f757f3fSDimitry Andric 21235f757f3fSDimitry Andric StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier(); 21245f757f3fSDimitry Andric StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier(); 21255f757f3fSDimitry Andric 21265f757f3fSDimitry Andric bool LIsBuiltins = LB == "<built-in>"; 21275f757f3fSDimitry Andric bool RIsBuiltins = RB == "<built-in>"; 21285f757f3fSDimitry Andric // Sort built-in before non-built-in. 21295f757f3fSDimitry Andric if (LIsBuiltins || RIsBuiltins) { 21305f757f3fSDimitry Andric if (LIsBuiltins != RIsBuiltins) 21315f757f3fSDimitry Andric return std::make_pair(true, LIsBuiltins); 21325f757f3fSDimitry Andric // Both are in built-in buffers, but from different files. We just claim 21335f757f3fSDimitry Andric // that lower IDs come first. 21345f757f3fSDimitry Andric return std::make_pair(true, LOffs.first < ROffs.first); 21355f757f3fSDimitry Andric } 21365f757f3fSDimitry Andric 21375f757f3fSDimitry Andric bool LIsAsm = LB == "<inline asm>"; 21385f757f3fSDimitry Andric bool RIsAsm = RB == "<inline asm>"; 21395f757f3fSDimitry Andric // Sort assembler after built-ins, but before the rest. 21405f757f3fSDimitry Andric if (LIsAsm || RIsAsm) { 21415f757f3fSDimitry Andric if (LIsAsm != RIsAsm) 21425f757f3fSDimitry Andric return std::make_pair(true, RIsAsm); 21435f757f3fSDimitry Andric assert(LOffs.first == ROffs.first); 21445f757f3fSDimitry Andric return std::make_pair(true, false); 21455f757f3fSDimitry Andric } 21465f757f3fSDimitry Andric 21475f757f3fSDimitry Andric bool LIsScratch = LB == "<scratch space>"; 21485f757f3fSDimitry Andric bool RIsScratch = RB == "<scratch space>"; 21495f757f3fSDimitry Andric // Sort scratch after inline asm, but before the rest. 21505f757f3fSDimitry Andric if (LIsScratch || RIsScratch) { 21515f757f3fSDimitry Andric if (LIsScratch != RIsScratch) 21525f757f3fSDimitry Andric return std::make_pair(true, LIsScratch); 21535f757f3fSDimitry Andric return std::make_pair(true, LOffs.second < ROffs.second); 21545f757f3fSDimitry Andric } 21555f757f3fSDimitry Andric 21565f757f3fSDimitry Andric llvm_unreachable("Unsortable locations found"); 21570b57cec5SDimitry Andric } 21580b57cec5SDimitry Andric 21590b57cec5SDimitry Andric void SourceManager::PrintStats() const { 21600b57cec5SDimitry Andric llvm::errs() << "\n*** Source Manager Stats:\n"; 21610b57cec5SDimitry Andric llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() 21620b57cec5SDimitry Andric << " mem buffers mapped.\n"; 21635f757f3fSDimitry Andric llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntries allocated (" 21640b57cec5SDimitry Andric << llvm::capacity_in_bytes(LocalSLocEntryTable) 21655f757f3fSDimitry Andric << " bytes of capacity), " << NextLocalOffset 21665f757f3fSDimitry Andric << "B of SLoc address space used.\n"; 21670b57cec5SDimitry Andric llvm::errs() << LoadedSLocEntryTable.size() 21685f757f3fSDimitry Andric << " loaded SLocEntries allocated (" 21695f757f3fSDimitry Andric << llvm::capacity_in_bytes(LoadedSLocEntryTable) 21705f757f3fSDimitry Andric << " bytes of capacity), " 21710b57cec5SDimitry Andric << MaxLoadedOffset - CurrentLoadedOffset 21725f757f3fSDimitry Andric << "B of SLoc address space used.\n"; 21730b57cec5SDimitry Andric 21740b57cec5SDimitry Andric unsigned NumLineNumsComputed = 0; 21750b57cec5SDimitry Andric unsigned NumFileBytesMapped = 0; 21760b57cec5SDimitry Andric for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ 2177e8d8bef9SDimitry Andric NumLineNumsComputed += bool(I->second->SourceLineCache); 21780b57cec5SDimitry Andric NumFileBytesMapped += I->second->getSizeBytesMapped(); 21790b57cec5SDimitry Andric } 21800b57cec5SDimitry Andric unsigned NumMacroArgsComputed = MacroArgsCacheMap.size(); 21810b57cec5SDimitry Andric 21820b57cec5SDimitry Andric llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " 21830b57cec5SDimitry Andric << NumLineNumsComputed << " files with line #'s computed, " 21840b57cec5SDimitry Andric << NumMacroArgsComputed << " files with macro args computed.\n"; 21850b57cec5SDimitry Andric llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " 21860b57cec5SDimitry Andric << NumBinaryProbes << " binary.\n"; 21870b57cec5SDimitry Andric } 21880b57cec5SDimitry Andric 21890b57cec5SDimitry Andric LLVM_DUMP_METHOD void SourceManager::dump() const { 21900b57cec5SDimitry Andric llvm::raw_ostream &out = llvm::errs(); 21910b57cec5SDimitry Andric 21920b57cec5SDimitry Andric auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry, 2193bdd1243dSDimitry Andric std::optional<SourceLocation::UIntTy> NextStart) { 21940b57cec5SDimitry Andric out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion") 21950b57cec5SDimitry Andric << " <SourceLocation " << Entry.getOffset() << ":"; 21960b57cec5SDimitry Andric if (NextStart) 21970b57cec5SDimitry Andric out << *NextStart << ">\n"; 21980b57cec5SDimitry Andric else 21990b57cec5SDimitry Andric out << "???\?>\n"; 22000b57cec5SDimitry Andric if (Entry.isFile()) { 22010b57cec5SDimitry Andric auto &FI = Entry.getFile(); 22020b57cec5SDimitry Andric if (FI.NumCreatedFIDs) 22030b57cec5SDimitry Andric out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs) 22040b57cec5SDimitry Andric << ">\n"; 22050b57cec5SDimitry Andric if (FI.getIncludeLoc().isValid()) 22060b57cec5SDimitry Andric out << " included from " << FI.getIncludeLoc().getOffset() << "\n"; 2207e8d8bef9SDimitry Andric auto &CC = FI.getContentCache(); 2208e8d8bef9SDimitry Andric out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>") 22090b57cec5SDimitry Andric << "\n"; 2210e8d8bef9SDimitry Andric if (CC.BufferOverridden) 22110b57cec5SDimitry Andric out << " contents overridden\n"; 2212e8d8bef9SDimitry Andric if (CC.ContentsEntry != CC.OrigEntry) { 22130b57cec5SDimitry Andric out << " contents from " 2214e8d8bef9SDimitry Andric << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>") 22150b57cec5SDimitry Andric << "\n"; 22160b57cec5SDimitry Andric } 22170b57cec5SDimitry Andric } else { 22180b57cec5SDimitry Andric auto &EI = Entry.getExpansion(); 22190b57cec5SDimitry Andric out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n"; 22200b57cec5SDimitry Andric out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body") 22210b57cec5SDimitry Andric << " range <" << EI.getExpansionLocStart().getOffset() << ":" 22220b57cec5SDimitry Andric << EI.getExpansionLocEnd().getOffset() << ">\n"; 22230b57cec5SDimitry Andric } 22240b57cec5SDimitry Andric }; 22250b57cec5SDimitry Andric 22260b57cec5SDimitry Andric // Dump local SLocEntries. 22270b57cec5SDimitry Andric for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) { 22280b57cec5SDimitry Andric DumpSLocEntry(ID, LocalSLocEntryTable[ID], 22290b57cec5SDimitry Andric ID == NumIDs - 1 ? NextLocalOffset 22300b57cec5SDimitry Andric : LocalSLocEntryTable[ID + 1].getOffset()); 22310b57cec5SDimitry Andric } 22320b57cec5SDimitry Andric // Dump loaded SLocEntries. 2233bdd1243dSDimitry Andric std::optional<SourceLocation::UIntTy> NextStart; 22340b57cec5SDimitry Andric for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) { 22350b57cec5SDimitry Andric int ID = -(int)Index - 2; 22360b57cec5SDimitry Andric if (SLocEntryLoaded[Index]) { 22370b57cec5SDimitry Andric DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart); 22380b57cec5SDimitry Andric NextStart = LoadedSLocEntryTable[Index].getOffset(); 22390b57cec5SDimitry Andric } else { 2240bdd1243dSDimitry Andric NextStart = std::nullopt; 22410b57cec5SDimitry Andric } 22420b57cec5SDimitry Andric } 22430b57cec5SDimitry Andric } 22440b57cec5SDimitry Andric 2245bdd1243dSDimitry Andric void SourceManager::noteSLocAddressSpaceUsage( 2246bdd1243dSDimitry Andric DiagnosticsEngine &Diag, std::optional<unsigned> MaxNotes) const { 2247bdd1243dSDimitry Andric struct Info { 2248bdd1243dSDimitry Andric // A location where this file was entered. 2249bdd1243dSDimitry Andric SourceLocation Loc; 2250bdd1243dSDimitry Andric // Number of times this FileEntry was entered. 2251bdd1243dSDimitry Andric unsigned Inclusions = 0; 2252bdd1243dSDimitry Andric // Size usage from the file itself. 2253bdd1243dSDimitry Andric uint64_t DirectSize = 0; 2254bdd1243dSDimitry Andric // Total size usage from the file and its macro expansions. 2255bdd1243dSDimitry Andric uint64_t TotalSize = 0; 2256bdd1243dSDimitry Andric }; 2257bdd1243dSDimitry Andric using UsageMap = llvm::MapVector<const FileEntry*, Info>; 2258bdd1243dSDimitry Andric 2259bdd1243dSDimitry Andric UsageMap Usage; 2260bdd1243dSDimitry Andric uint64_t CountedSize = 0; 2261bdd1243dSDimitry Andric 2262bdd1243dSDimitry Andric auto AddUsageForFileID = [&](FileID ID) { 2263bdd1243dSDimitry Andric // The +1 here is because getFileIDSize doesn't include the extra byte for 2264bdd1243dSDimitry Andric // the one-past-the-end location. 2265bdd1243dSDimitry Andric unsigned Size = getFileIDSize(ID) + 1; 2266bdd1243dSDimitry Andric 2267bdd1243dSDimitry Andric // Find the file that used this address space, either directly or by 2268bdd1243dSDimitry Andric // macro expansion. 2269bdd1243dSDimitry Andric SourceLocation FileStart = getFileLoc(getComposedLoc(ID, 0)); 2270bdd1243dSDimitry Andric FileID FileLocID = getFileID(FileStart); 2271bdd1243dSDimitry Andric const FileEntry *Entry = getFileEntryForID(FileLocID); 2272bdd1243dSDimitry Andric 2273bdd1243dSDimitry Andric Info &EntryInfo = Usage[Entry]; 2274bdd1243dSDimitry Andric if (EntryInfo.Loc.isInvalid()) 2275bdd1243dSDimitry Andric EntryInfo.Loc = FileStart; 2276bdd1243dSDimitry Andric if (ID == FileLocID) { 2277bdd1243dSDimitry Andric ++EntryInfo.Inclusions; 2278bdd1243dSDimitry Andric EntryInfo.DirectSize += Size; 2279bdd1243dSDimitry Andric } 2280bdd1243dSDimitry Andric EntryInfo.TotalSize += Size; 2281bdd1243dSDimitry Andric CountedSize += Size; 2282bdd1243dSDimitry Andric }; 2283bdd1243dSDimitry Andric 2284bdd1243dSDimitry Andric // Loaded SLocEntries have indexes counting downwards from -2. 2285bdd1243dSDimitry Andric for (size_t Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) { 2286bdd1243dSDimitry Andric AddUsageForFileID(FileID::get(-2 - Index)); 2287bdd1243dSDimitry Andric } 2288bdd1243dSDimitry Andric // Local SLocEntries have indexes counting upwards from 0. 2289bdd1243dSDimitry Andric for (size_t Index = 0; Index != LocalSLocEntryTable.size(); ++Index) { 2290bdd1243dSDimitry Andric AddUsageForFileID(FileID::get(Index)); 2291bdd1243dSDimitry Andric } 2292bdd1243dSDimitry Andric 2293bdd1243dSDimitry Andric // Sort the usage by size from largest to smallest. Break ties by raw source 2294bdd1243dSDimitry Andric // location. 2295bdd1243dSDimitry Andric auto SortedUsage = Usage.takeVector(); 2296bdd1243dSDimitry Andric auto Cmp = [](const UsageMap::value_type &A, const UsageMap::value_type &B) { 2297bdd1243dSDimitry Andric return A.second.TotalSize > B.second.TotalSize || 2298bdd1243dSDimitry Andric (A.second.TotalSize == B.second.TotalSize && 2299bdd1243dSDimitry Andric A.second.Loc < B.second.Loc); 2300bdd1243dSDimitry Andric }; 2301bdd1243dSDimitry Andric auto SortedEnd = SortedUsage.end(); 2302bdd1243dSDimitry Andric if (MaxNotes && SortedUsage.size() > *MaxNotes) { 2303bdd1243dSDimitry Andric SortedEnd = SortedUsage.begin() + *MaxNotes; 2304bdd1243dSDimitry Andric std::nth_element(SortedUsage.begin(), SortedEnd, SortedUsage.end(), Cmp); 2305bdd1243dSDimitry Andric } 2306bdd1243dSDimitry Andric std::sort(SortedUsage.begin(), SortedEnd, Cmp); 2307bdd1243dSDimitry Andric 2308bdd1243dSDimitry Andric // Produce note on sloc address space usage total. 2309bdd1243dSDimitry Andric uint64_t LocalUsage = NextLocalOffset; 2310bdd1243dSDimitry Andric uint64_t LoadedUsage = MaxLoadedOffset - CurrentLoadedOffset; 2311bdd1243dSDimitry Andric int UsagePercent = static_cast<int>(100.0 * double(LocalUsage + LoadedUsage) / 2312bdd1243dSDimitry Andric MaxLoadedOffset); 2313bdd1243dSDimitry Andric Diag.Report(SourceLocation(), diag::note_total_sloc_usage) 2314bdd1243dSDimitry Andric << LocalUsage << LoadedUsage << (LocalUsage + LoadedUsage) << UsagePercent; 2315bdd1243dSDimitry Andric 2316bdd1243dSDimitry Andric // Produce notes on sloc address space usage for each file with a high usage. 2317bdd1243dSDimitry Andric uint64_t ReportedSize = 0; 2318bdd1243dSDimitry Andric for (auto &[Entry, FileInfo] : 2319bdd1243dSDimitry Andric llvm::make_range(SortedUsage.begin(), SortedEnd)) { 2320bdd1243dSDimitry Andric Diag.Report(FileInfo.Loc, diag::note_file_sloc_usage) 2321bdd1243dSDimitry Andric << FileInfo.Inclusions << FileInfo.DirectSize 2322bdd1243dSDimitry Andric << (FileInfo.TotalSize - FileInfo.DirectSize); 2323bdd1243dSDimitry Andric ReportedSize += FileInfo.TotalSize; 2324bdd1243dSDimitry Andric } 2325bdd1243dSDimitry Andric 2326bdd1243dSDimitry Andric // Describe any remaining usage not reported in the per-file usage. 2327bdd1243dSDimitry Andric if (ReportedSize != CountedSize) { 2328bdd1243dSDimitry Andric Diag.Report(SourceLocation(), diag::note_file_misc_sloc_usage) 2329bdd1243dSDimitry Andric << (SortedUsage.end() - SortedEnd) << CountedSize - ReportedSize; 2330bdd1243dSDimitry Andric } 2331bdd1243dSDimitry Andric } 2332bdd1243dSDimitry Andric 23330b57cec5SDimitry Andric ExternalSLocEntrySource::~ExternalSLocEntrySource() = default; 23340b57cec5SDimitry Andric 23350b57cec5SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down 23360b57cec5SDimitry Andric /// by heap-backed versus mmap'ed memory. 23370b57cec5SDimitry Andric SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { 23380b57cec5SDimitry Andric size_t malloc_bytes = 0; 23390b57cec5SDimitry Andric size_t mmap_bytes = 0; 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) 23420b57cec5SDimitry Andric if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) 23430b57cec5SDimitry Andric switch (MemBufferInfos[i]->getMemoryBufferKind()) { 23440b57cec5SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_MMap: 23450b57cec5SDimitry Andric mmap_bytes += sized_mapped; 23460b57cec5SDimitry Andric break; 23470b57cec5SDimitry Andric case llvm::MemoryBuffer::MemoryBuffer_Malloc: 23480b57cec5SDimitry Andric malloc_bytes += sized_mapped; 23490b57cec5SDimitry Andric break; 23500b57cec5SDimitry Andric } 23510b57cec5SDimitry Andric 23520b57cec5SDimitry Andric return MemoryBufferSizes(malloc_bytes, mmap_bytes); 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric 23550b57cec5SDimitry Andric size_t SourceManager::getDataStructureSizes() const { 23565f757f3fSDimitry Andric size_t size = llvm::capacity_in_bytes(MemBufferInfos) + 23575f757f3fSDimitry Andric llvm::capacity_in_bytes(LocalSLocEntryTable) + 23585f757f3fSDimitry Andric llvm::capacity_in_bytes(LoadedSLocEntryTable) + 23595f757f3fSDimitry Andric llvm::capacity_in_bytes(SLocEntryLoaded) + 23605f757f3fSDimitry Andric llvm::capacity_in_bytes(FileInfos); 23610b57cec5SDimitry Andric 23620b57cec5SDimitry Andric if (OverriddenFilesInfo) 23630b57cec5SDimitry Andric size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles); 23640b57cec5SDimitry Andric 23650b57cec5SDimitry Andric return size; 23660b57cec5SDimitry Andric } 23670b57cec5SDimitry Andric 23680b57cec5SDimitry Andric SourceManagerForFile::SourceManagerForFile(StringRef FileName, 23690b57cec5SDimitry Andric StringRef Content) { 23700b57cec5SDimitry Andric // This is referenced by `FileMgr` and will be released by `FileMgr` when it 23710b57cec5SDimitry Andric // is deleted. 23720b57cec5SDimitry Andric IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( 23730b57cec5SDimitry Andric new llvm::vfs::InMemoryFileSystem); 23740b57cec5SDimitry Andric InMemoryFileSystem->addFile( 23750b57cec5SDimitry Andric FileName, 0, 23760b57cec5SDimitry Andric llvm::MemoryBuffer::getMemBuffer(Content, FileName, 23770b57cec5SDimitry Andric /*RequiresNullTerminator=*/false)); 23780b57cec5SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced 23790b57cec5SDimitry Andric // in `Environment` so that `FileMgr` can out-live this function scope. 23800b57cec5SDimitry Andric FileMgr = 2381a7dea167SDimitry Andric std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem); 23820b57cec5SDimitry Andric // This is passed to `SM` as reference, so the pointer has to be referenced 23830b57cec5SDimitry Andric // by `Environment` due to the same reason above. 2384a7dea167SDimitry Andric Diagnostics = std::make_unique<DiagnosticsEngine>( 23850b57cec5SDimitry Andric IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), 23860b57cec5SDimitry Andric new DiagnosticOptions); 2387a7dea167SDimitry Andric SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr); 23885f757f3fSDimitry Andric FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName)); 23895f757f3fSDimitry Andric FileID ID = 23905f757f3fSDimitry Andric SourceMgr->createFileID(FE, SourceLocation(), clang::SrcMgr::C_User); 23910b57cec5SDimitry Andric assert(ID.isValid()); 23920b57cec5SDimitry Andric SourceMgr->setMainFileID(ID); 23930b57cec5SDimitry Andric } 2394