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