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