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