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