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