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