SourceManager.cpp revision 205408
1//===--- SourceManager.cpp - Track and cache source files -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the SourceManager interface. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Basic/SourceManager.h" 15#include "clang/Basic/SourceManagerInternals.h" 16#include "clang/Basic/Diagnostic.h" 17#include "clang/Basic/FileManager.h" 18#include "llvm/Support/Compiler.h" 19#include "llvm/Support/MemoryBuffer.h" 20#include "llvm/Support/raw_ostream.h" 21#include "llvm/System/Path.h" 22#include <algorithm> 23#include <string> 24#include <cstring> 25 26using namespace clang; 27using namespace SrcMgr; 28using llvm::MemoryBuffer; 29 30//===----------------------------------------------------------------------===// 31// SourceManager Helper Classes 32//===----------------------------------------------------------------------===// 33 34ContentCache::~ContentCache() { 35 delete Buffer.getPointer(); 36} 37 38/// getSizeBytesMapped - Returns the number of bytes actually mapped for 39/// this ContentCache. This can be 0 if the MemBuffer was not actually 40/// instantiated. 41unsigned ContentCache::getSizeBytesMapped() const { 42 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0; 43} 44 45/// getSize - Returns the size of the content encapsulated by this ContentCache. 46/// This can be the size of the source file or the size of an arbitrary 47/// scratch buffer. If the ContentCache encapsulates a source file, that 48/// file is not lazily brought in from disk to satisfy this query. 49unsigned ContentCache::getSize() const { 50 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize() 51 : (unsigned) Entry->getSize(); 52} 53 54void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) { 55 assert(B != Buffer.getPointer()); 56 57 delete Buffer.getPointer(); 58 Buffer.setPointer(B); 59 Buffer.setInt(false); 60} 61 62const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag, 63 bool *Invalid) const { 64 if (Invalid) 65 *Invalid = false; 66 67 // Lazily create the Buffer for ContentCaches that wrap files. 68 if (!Buffer.getPointer() && Entry) { 69 std::string ErrorStr; 70 struct stat FileInfo; 71 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr, 72 Entry->getSize(), &FileInfo)); 73 Buffer.setInt(false); 74 75 // If we were unable to open the file, then we are in an inconsistent 76 // situation where the content cache referenced a file which no longer 77 // exists. Most likely, we were using a stat cache with an invalid entry but 78 // the file could also have been removed during processing. Since we can't 79 // really deal with this situation, just create an empty buffer. 80 // 81 // FIXME: This is definitely not ideal, but our immediate clients can't 82 // currently handle returning a null entry here. Ideally we should detect 83 // that we are in an inconsistent situation and error out as quickly as 84 // possible. 85 if (!Buffer.getPointer()) { 86 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n"); 87 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(), 88 "<invalid>")); 89 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart()); 90 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i) 91 Ptr[i] = FillStr[i % FillStr.size()]; 92 Diag.Report(diag::err_cannot_open_file) 93 << Entry->getName() << ErrorStr; 94 Buffer.setInt(true); 95 } else if (FileInfo.st_size != Entry->getSize() || 96 FileInfo.st_mtime != Entry->getModificationTime() || 97 FileInfo.st_ino != Entry->getInode()) { 98 // Check that the file's size, modification time, and inode are 99 // the same as in the file entry (which may have come from a 100 // stat cache). 101 Diag.Report(diag::err_file_modified) << Entry->getName(); 102 Buffer.setInt(true); 103 } 104 } 105 106 if (Invalid) 107 *Invalid = Buffer.getInt(); 108 109 return Buffer.getPointer(); 110} 111 112unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) { 113 // Look up the filename in the string table, returning the pre-existing value 114 // if it exists. 115 llvm::StringMapEntry<unsigned> &Entry = 116 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U); 117 if (Entry.getValue() != ~0U) 118 return Entry.getValue(); 119 120 // Otherwise, assign this the next available ID. 121 Entry.setValue(FilenamesByID.size()); 122 FilenamesByID.push_back(&Entry); 123 return FilenamesByID.size()-1; 124} 125 126/// AddLineNote - Add a line note to the line table that indicates that there 127/// is a #line at the specified FID/Offset location which changes the presumed 128/// location to LineNo/FilenameID. 129void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, 130 unsigned LineNo, int FilenameID) { 131 std::vector<LineEntry> &Entries = LineEntries[FID]; 132 133 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 134 "Adding line entries out of order!"); 135 136 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User; 137 unsigned IncludeOffset = 0; 138 139 if (!Entries.empty()) { 140 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember 141 // that we are still in "foo.h". 142 if (FilenameID == -1) 143 FilenameID = Entries.back().FilenameID; 144 145 // If we are after a line marker that switched us to system header mode, or 146 // that set #include information, preserve it. 147 Kind = Entries.back().FileKind; 148 IncludeOffset = Entries.back().IncludeOffset; 149 } 150 151 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind, 152 IncludeOffset)); 153} 154 155/// AddLineNote This is the same as the previous version of AddLineNote, but is 156/// used for GNU line markers. If EntryExit is 0, then this doesn't change the 157/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then 158/// this is a file exit. FileKind specifies whether this is a system header or 159/// extern C system header. 160void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset, 161 unsigned LineNo, int FilenameID, 162 unsigned EntryExit, 163 SrcMgr::CharacteristicKind FileKind) { 164 assert(FilenameID != -1 && "Unspecified filename should use other accessor"); 165 166 std::vector<LineEntry> &Entries = LineEntries[FID]; 167 168 assert((Entries.empty() || Entries.back().FileOffset < Offset) && 169 "Adding line entries out of order!"); 170 171 unsigned IncludeOffset = 0; 172 if (EntryExit == 0) { // No #include stack change. 173 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset; 174 } else if (EntryExit == 1) { 175 IncludeOffset = Offset-1; 176 } else if (EntryExit == 2) { 177 assert(!Entries.empty() && Entries.back().IncludeOffset && 178 "PPDirectives should have caught case when popping empty include stack"); 179 180 // Get the include loc of the last entries' include loc as our include loc. 181 IncludeOffset = 0; 182 if (const LineEntry *PrevEntry = 183 FindNearestLineEntry(FID, Entries.back().IncludeOffset)) 184 IncludeOffset = PrevEntry->IncludeOffset; 185 } 186 187 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, 188 IncludeOffset)); 189} 190 191 192/// FindNearestLineEntry - Find the line entry nearest to FID that is before 193/// it. If there is no line entry before Offset in FID, return null. 194const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID, 195 unsigned Offset) { 196 const std::vector<LineEntry> &Entries = LineEntries[FID]; 197 assert(!Entries.empty() && "No #line entries for this FID after all!"); 198 199 // It is very common for the query to be after the last #line, check this 200 // first. 201 if (Entries.back().FileOffset <= Offset) 202 return &Entries.back(); 203 204 // Do a binary search to find the maximal element that is still before Offset. 205 std::vector<LineEntry>::const_iterator I = 206 std::upper_bound(Entries.begin(), Entries.end(), Offset); 207 if (I == Entries.begin()) return 0; 208 return &*--I; 209} 210 211/// \brief Add a new line entry that has already been encoded into 212/// the internal representation of the line table. 213void LineTableInfo::AddEntry(unsigned FID, 214 const std::vector<LineEntry> &Entries) { 215 LineEntries[FID] = Entries; 216} 217 218/// getLineTableFilenameID - Return the uniqued ID for the specified filename. 219/// 220unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) { 221 if (LineTable == 0) 222 LineTable = new LineTableInfo(); 223 return LineTable->getLineTableFilenameID(Ptr, Len); 224} 225 226 227/// AddLineNote - Add a line note to the line table for the FileID and offset 228/// specified by Loc. If FilenameID is -1, it is considered to be 229/// unspecified. 230void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 231 int FilenameID) { 232 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 233 234 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); 235 236 // Remember that this file has #line directives now if it doesn't already. 237 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 238 239 if (LineTable == 0) 240 LineTable = new LineTableInfo(); 241 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID); 242} 243 244/// AddLineNote - Add a GNU line marker to the line table. 245void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, 246 int FilenameID, bool IsFileEntry, 247 bool IsFileExit, bool IsSystemHeader, 248 bool IsExternCHeader) { 249 // If there is no filename and no flags, this is treated just like a #line, 250 // which does not change the flags of the previous line marker. 251 if (FilenameID == -1) { 252 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader && 253 "Can't set flags without setting the filename!"); 254 return AddLineNote(Loc, LineNo, FilenameID); 255 } 256 257 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 258 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile(); 259 260 // Remember that this file has #line directives now if it doesn't already. 261 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); 262 263 if (LineTable == 0) 264 LineTable = new LineTableInfo(); 265 266 SrcMgr::CharacteristicKind FileKind; 267 if (IsExternCHeader) 268 FileKind = SrcMgr::C_ExternCSystem; 269 else if (IsSystemHeader) 270 FileKind = SrcMgr::C_System; 271 else 272 FileKind = SrcMgr::C_User; 273 274 unsigned EntryExit = 0; 275 if (IsFileEntry) 276 EntryExit = 1; 277 else if (IsFileExit) 278 EntryExit = 2; 279 280 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID, 281 EntryExit, FileKind); 282} 283 284LineTableInfo &SourceManager::getLineTable() { 285 if (LineTable == 0) 286 LineTable = new LineTableInfo(); 287 return *LineTable; 288} 289 290//===----------------------------------------------------------------------===// 291// Private 'Create' methods. 292//===----------------------------------------------------------------------===// 293 294SourceManager::~SourceManager() { 295 delete LineTable; 296 297 // Delete FileEntry objects corresponding to content caches. Since the actual 298 // content cache objects are bump pointer allocated, we just have to run the 299 // dtors, but we call the deallocate method for completeness. 300 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { 301 MemBufferInfos[i]->~ContentCache(); 302 ContentCacheAlloc.Deallocate(MemBufferInfos[i]); 303 } 304 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator 305 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { 306 I->second->~ContentCache(); 307 ContentCacheAlloc.Deallocate(I->second); 308 } 309} 310 311void SourceManager::clearIDTables() { 312 MainFileID = FileID(); 313 SLocEntryTable.clear(); 314 LastLineNoFileIDQuery = FileID(); 315 LastLineNoContentCache = 0; 316 LastFileIDLookup = FileID(); 317 318 if (LineTable) 319 LineTable->clear(); 320 321 // Use up FileID #0 as an invalid instantiation. 322 NextOffset = 0; 323 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1); 324} 325 326/// getOrCreateContentCache - Create or return a cached ContentCache for the 327/// specified file. 328const ContentCache * 329SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) { 330 assert(FileEnt && "Didn't specify a file entry to use?"); 331 332 // Do we already have information about this file? 333 ContentCache *&Entry = FileInfos[FileEnt]; 334 if (Entry) return Entry; 335 336 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned 337 // so that FileInfo can use the low 3 bits of the pointer for its own 338 // nefarious purposes. 339 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 340 EntryAlign = std::max(8U, EntryAlign); 341 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 342 new (Entry) ContentCache(FileEnt); 343 return Entry; 344} 345 346 347/// createMemBufferContentCache - Create a new ContentCache for the specified 348/// memory buffer. This does no caching. 349const ContentCache* 350SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) { 351 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure 352 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of 353 // the pointer for its own nefarious purposes. 354 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment; 355 EntryAlign = std::max(8U, EntryAlign); 356 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign); 357 new (Entry) ContentCache(); 358 MemBufferInfos.push_back(Entry); 359 Entry->setBuffer(Buffer); 360 return Entry; 361} 362 363void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source, 364 unsigned NumSLocEntries, 365 unsigned NextOffset) { 366 ExternalSLocEntries = Source; 367 this->NextOffset = NextOffset; 368 SLocEntryLoaded.resize(NumSLocEntries + 1); 369 SLocEntryLoaded[0] = true; 370 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries); 371} 372 373void SourceManager::ClearPreallocatedSLocEntries() { 374 unsigned I = 0; 375 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I) 376 if (!SLocEntryLoaded[I]) 377 break; 378 379 // We've already loaded all preallocated source location entries. 380 if (I == SLocEntryLoaded.size()) 381 return; 382 383 // Remove everything from location I onward. 384 SLocEntryTable.resize(I); 385 SLocEntryLoaded.clear(); 386 ExternalSLocEntries = 0; 387} 388 389 390//===----------------------------------------------------------------------===// 391// Methods to create new FileID's and instantiations. 392//===----------------------------------------------------------------------===// 393 394/// createFileID - Create a new fileID for the specified ContentCache and 395/// include position. This works regardless of whether the ContentCache 396/// corresponds to a file or some other input source. 397FileID SourceManager::createFileID(const ContentCache *File, 398 SourceLocation IncludePos, 399 SrcMgr::CharacteristicKind FileCharacter, 400 unsigned PreallocatedID, 401 unsigned Offset) { 402 if (PreallocatedID) { 403 // If we're filling in a preallocated ID, just load in the file 404 // entry and return. 405 assert(PreallocatedID < SLocEntryLoaded.size() && 406 "Preallocate ID out-of-range"); 407 assert(!SLocEntryLoaded[PreallocatedID] && 408 "Source location entry already loaded"); 409 assert(Offset && "Preallocate source location cannot have zero offset"); 410 SLocEntryTable[PreallocatedID] 411 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter)); 412 SLocEntryLoaded[PreallocatedID] = true; 413 FileID FID = FileID::get(PreallocatedID); 414 return FID; 415 } 416 417 SLocEntryTable.push_back(SLocEntry::get(NextOffset, 418 FileInfo::get(IncludePos, File, 419 FileCharacter))); 420 unsigned FileSize = File->getSize(); 421 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!"); 422 NextOffset += FileSize+1; 423 424 // Set LastFileIDLookup to the newly created file. The next getFileID call is 425 // almost guaranteed to be from that file. 426 FileID FID = FileID::get(SLocEntryTable.size()-1); 427 return LastFileIDLookup = FID; 428} 429 430/// createInstantiationLoc - Return a new SourceLocation that encodes the fact 431/// that a token from SpellingLoc should actually be referenced from 432/// InstantiationLoc. 433SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc, 434 SourceLocation ILocStart, 435 SourceLocation ILocEnd, 436 unsigned TokLength, 437 unsigned PreallocatedID, 438 unsigned Offset) { 439 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc); 440 if (PreallocatedID) { 441 // If we're filling in a preallocated ID, just load in the 442 // instantiation entry and return. 443 assert(PreallocatedID < SLocEntryLoaded.size() && 444 "Preallocate ID out-of-range"); 445 assert(!SLocEntryLoaded[PreallocatedID] && 446 "Source location entry already loaded"); 447 assert(Offset && "Preallocate source location cannot have zero offset"); 448 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II); 449 SLocEntryLoaded[PreallocatedID] = true; 450 return SourceLocation::getMacroLoc(Offset); 451 } 452 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II)); 453 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!"); 454 NextOffset += TokLength+1; 455 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1)); 456} 457 458const llvm::MemoryBuffer * 459SourceManager::getMemoryBufferForFile(const FileEntry *File, 460 bool *Invalid) { 461 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); 462 assert(IR && "getOrCreateContentCache() cannot return NULL"); 463 return IR->getBuffer(Diag, Invalid); 464} 465 466bool SourceManager::overrideFileContents(const FileEntry *SourceFile, 467 const llvm::MemoryBuffer *Buffer) { 468 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); 469 if (IR == 0) 470 return true; 471 472 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer); 473 return false; 474} 475 476llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { 477 bool MyInvalid = false; 478 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid); 479 if (Invalid) 480 *Invalid = MyInvalid; 481 482 if (MyInvalid) 483 return ""; 484 485 return Buf->getBuffer(); 486} 487 488//===----------------------------------------------------------------------===// 489// SourceLocation manipulation methods. 490//===----------------------------------------------------------------------===// 491 492/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot 493/// method that is used for all SourceManager queries that start with a 494/// SourceLocation object. It is responsible for finding the entry in 495/// SLocEntryTable which contains the specified location. 496/// 497FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { 498 assert(SLocOffset && "Invalid FileID"); 499 500 // After the first and second level caches, I see two common sorts of 501 // behavior: 1) a lot of searched FileID's are "near" the cached file location 502 // or are "near" the cached instantiation location. 2) others are just 503 // completely random and may be a very long way away. 504 // 505 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly 506 // then we fall back to a less cache efficient, but more scalable, binary 507 // search to find the location. 508 509 // See if this is near the file point - worst case we start scanning from the 510 // most newly created FileID. 511 std::vector<SrcMgr::SLocEntry>::const_iterator I; 512 513 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { 514 // Neither loc prunes our search. 515 I = SLocEntryTable.end(); 516 } else { 517 // Perhaps it is near the file point. 518 I = SLocEntryTable.begin()+LastFileIDLookup.ID; 519 } 520 521 // Find the FileID that contains this. "I" is an iterator that points to a 522 // FileID whose offset is known to be larger than SLocOffset. 523 unsigned NumProbes = 0; 524 while (1) { 525 --I; 526 if (ExternalSLocEntries) 527 getSLocEntry(FileID::get(I - SLocEntryTable.begin())); 528 if (I->getOffset() <= SLocOffset) { 529#if 0 530 printf("lin %d -> %d [%s] %d %d\n", SLocOffset, 531 I-SLocEntryTable.begin(), 532 I->isInstantiation() ? "inst" : "file", 533 LastFileIDLookup.ID, int(SLocEntryTable.end()-I)); 534#endif 535 FileID Res = FileID::get(I-SLocEntryTable.begin()); 536 537 // If this isn't an instantiation, remember it. We have good locality 538 // across FileID lookups. 539 if (!I->isInstantiation()) 540 LastFileIDLookup = Res; 541 NumLinearScans += NumProbes+1; 542 return Res; 543 } 544 if (++NumProbes == 8) 545 break; 546 } 547 548 // Convert "I" back into an index. We know that it is an entry whose index is 549 // larger than the offset we are looking for. 550 unsigned GreaterIndex = I-SLocEntryTable.begin(); 551 // LessIndex - This is the lower bound of the range that we're searching. 552 // We know that the offset corresponding to the FileID is is less than 553 // SLocOffset. 554 unsigned LessIndex = 0; 555 NumProbes = 0; 556 while (1) { 557 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; 558 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset(); 559 560 ++NumProbes; 561 562 // If the offset of the midpoint is too large, chop the high side of the 563 // range to the midpoint. 564 if (MidOffset > SLocOffset) { 565 GreaterIndex = MiddleIndex; 566 continue; 567 } 568 569 // If the middle index contains the value, succeed and return. 570 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { 571#if 0 572 printf("bin %d -> %d [%s] %d %d\n", SLocOffset, 573 I-SLocEntryTable.begin(), 574 I->isInstantiation() ? "inst" : "file", 575 LastFileIDLookup.ID, int(SLocEntryTable.end()-I)); 576#endif 577 FileID Res = FileID::get(MiddleIndex); 578 579 // If this isn't an instantiation, remember it. We have good locality 580 // across FileID lookups. 581 if (!I->isInstantiation()) 582 LastFileIDLookup = Res; 583 NumBinaryProbes += NumProbes; 584 return Res; 585 } 586 587 // Otherwise, move the low-side up to the middle index. 588 LessIndex = MiddleIndex; 589 } 590} 591 592SourceLocation SourceManager:: 593getInstantiationLocSlowCase(SourceLocation Loc) const { 594 do { 595 // Note: If Loc indicates an offset into a token that came from a macro 596 // expansion (e.g. the 5th character of the token) we do not want to add 597 // this offset when going to the instantiation location. The instatiation 598 // location is the macro invocation, which the offset has nothing to do 599 // with. This is unlike when we get the spelling loc, because the offset 600 // directly correspond to the token whose spelling we're inspecting. 601 Loc = getSLocEntry(getFileID(Loc)).getInstantiation() 602 .getInstantiationLocStart(); 603 } while (!Loc.isFileID()); 604 605 return Loc; 606} 607 608SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { 609 do { 610 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 611 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc(); 612 Loc = Loc.getFileLocWithOffset(LocInfo.second); 613 } while (!Loc.isFileID()); 614 return Loc; 615} 616 617 618std::pair<FileID, unsigned> 619SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E, 620 unsigned Offset) const { 621 // If this is an instantiation record, walk through all the instantiation 622 // points. 623 FileID FID; 624 SourceLocation Loc; 625 do { 626 Loc = E->getInstantiation().getInstantiationLocStart(); 627 628 FID = getFileID(Loc); 629 E = &getSLocEntry(FID); 630 Offset += Loc.getOffset()-E->getOffset(); 631 } while (!Loc.isFileID()); 632 633 return std::make_pair(FID, Offset); 634} 635 636std::pair<FileID, unsigned> 637SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, 638 unsigned Offset) const { 639 // If this is an instantiation record, walk through all the instantiation 640 // points. 641 FileID FID; 642 SourceLocation Loc; 643 do { 644 Loc = E->getInstantiation().getSpellingLoc(); 645 646 FID = getFileID(Loc); 647 E = &getSLocEntry(FID); 648 Offset += Loc.getOffset()-E->getOffset(); 649 } while (!Loc.isFileID()); 650 651 return std::make_pair(FID, Offset); 652} 653 654/// getImmediateSpellingLoc - Given a SourceLocation object, return the 655/// spelling location referenced by the ID. This is the first level down 656/// towards the place where the characters that make up the lexed token can be 657/// found. This should not generally be used by clients. 658SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ 659 if (Loc.isFileID()) return Loc; 660 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); 661 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc(); 662 return Loc.getFileLocWithOffset(LocInfo.second); 663} 664 665 666/// getImmediateInstantiationRange - Loc is required to be an instantiation 667/// location. Return the start/end of the instantiation information. 668std::pair<SourceLocation,SourceLocation> 669SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const { 670 assert(Loc.isMacroID() && "Not an instantiation loc!"); 671 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation(); 672 return II.getInstantiationLocRange(); 673} 674 675/// getInstantiationRange - Given a SourceLocation object, return the 676/// range of tokens covered by the instantiation in the ultimate file. 677std::pair<SourceLocation,SourceLocation> 678SourceManager::getInstantiationRange(SourceLocation Loc) const { 679 if (Loc.isFileID()) return std::make_pair(Loc, Loc); 680 681 std::pair<SourceLocation,SourceLocation> Res = 682 getImmediateInstantiationRange(Loc); 683 684 // Fully resolve the start and end locations to their ultimate instantiation 685 // points. 686 while (!Res.first.isFileID()) 687 Res.first = getImmediateInstantiationRange(Res.first).first; 688 while (!Res.second.isFileID()) 689 Res.second = getImmediateInstantiationRange(Res.second).second; 690 return Res; 691} 692 693 694 695//===----------------------------------------------------------------------===// 696// Queries about the code at a SourceLocation. 697//===----------------------------------------------------------------------===// 698 699/// getCharacterData - Return a pointer to the start of the specified location 700/// in the appropriate MemoryBuffer. 701const char *SourceManager::getCharacterData(SourceLocation SL, 702 bool *Invalid) const { 703 // Note that this is a hot function in the getSpelling() path, which is 704 // heavily used by -E mode. 705 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); 706 707 // Note that calling 'getBuffer()' may lazily page in a source file. 708 bool CharDataInvalid = false; 709 const llvm::MemoryBuffer *Buffer 710 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag, 711 &CharDataInvalid); 712 if (Invalid) 713 *Invalid = CharDataInvalid; 714 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second); 715} 716 717 718/// getColumnNumber - Return the column # for the specified file position. 719/// this is significantly cheaper to compute than the line number. 720unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, 721 bool *Invalid) const { 722 bool MyInvalid = false; 723 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart(); 724 if (Invalid) 725 *Invalid = MyInvalid; 726 727 if (MyInvalid) 728 return 1; 729 730 unsigned LineStart = FilePos; 731 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') 732 --LineStart; 733 return FilePos-LineStart+1; 734} 735 736unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, 737 bool *Invalid) const { 738 if (Loc.isInvalid()) return 0; 739 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 740 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 741} 742 743unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc, 744 bool *Invalid) const { 745 if (Loc.isInvalid()) return 0; 746 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 747 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); 748} 749 750static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag, 751 ContentCache* FI, 752 llvm::BumpPtrAllocator &Alloc, 753 bool &Invalid); 754static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI, 755 llvm::BumpPtrAllocator &Alloc, bool &Invalid) { 756 // Note that calling 'getBuffer()' may lazily page in the file. 757 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid); 758 if (Invalid) 759 return; 760 761 // Find the file offsets of all of the *physical* source lines. This does 762 // not look at trigraphs, escaped newlines, or anything else tricky. 763 std::vector<unsigned> LineOffsets; 764 765 // Line #1 starts at char 0. 766 LineOffsets.push_back(0); 767 768 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); 769 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); 770 unsigned Offs = 0; 771 while (1) { 772 // Skip over the contents of the line. 773 // TODO: Vectorize this? This is very performance sensitive for programs 774 // with lots of diagnostics and in -E mode. 775 const unsigned char *NextBuf = (const unsigned char *)Buf; 776 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0') 777 ++NextBuf; 778 Offs += NextBuf-Buf; 779 Buf = NextBuf; 780 781 if (Buf[0] == '\n' || Buf[0] == '\r') { 782 // If this is \n\r or \r\n, skip both characters. 783 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) 784 ++Offs, ++Buf; 785 ++Offs, ++Buf; 786 LineOffsets.push_back(Offs); 787 } else { 788 // Otherwise, this is a null. If end of file, exit. 789 if (Buf == End) break; 790 // Otherwise, skip the null. 791 ++Offs, ++Buf; 792 } 793 } 794 795 // Copy the offsets into the FileInfo structure. 796 FI->NumLines = LineOffsets.size(); 797 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size()); 798 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache); 799} 800 801/// getLineNumber - Given a SourceLocation, return the spelling line number 802/// for the position indicated. This requires building and caching a table of 803/// line offsets for the MemoryBuffer, so this is not cheap: use only when 804/// about to emit a diagnostic. 805unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, 806 bool *Invalid) const { 807 ContentCache *Content; 808 if (LastLineNoFileIDQuery == FID) 809 Content = LastLineNoContentCache; 810 else 811 Content = const_cast<ContentCache*>(getSLocEntry(FID) 812 .getFile().getContentCache()); 813 814 // If this is the first use of line information for this buffer, compute the 815 /// SourceLineCache for it on demand. 816 if (Content->SourceLineCache == 0) { 817 bool MyInvalid = false; 818 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid); 819 if (Invalid) 820 *Invalid = MyInvalid; 821 if (MyInvalid) 822 return 1; 823 } else if (Invalid) 824 *Invalid = false; 825 826 // Okay, we know we have a line number table. Do a binary search to find the 827 // line number that this character position lands on. 828 unsigned *SourceLineCache = Content->SourceLineCache; 829 unsigned *SourceLineCacheStart = SourceLineCache; 830 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; 831 832 unsigned QueriedFilePos = FilePos+1; 833 834 // FIXME: I would like to be convinced that this code is worth being as 835 // complicated as it is, binary search isn't that slow. 836 // 837 // If it is worth being optimized, then in my opinion it could be more 838 // performant, simpler, and more obviously correct by just "galloping" outward 839 // from the queried file position. In fact, this could be incorporated into a 840 // generic algorithm such as lower_bound_with_hint. 841 // 842 // If someone gives me a test case where this matters, and I will do it! - DWD 843 844 // If the previous query was to the same file, we know both the file pos from 845 // that query and the line number returned. This allows us to narrow the 846 // search space from the entire file to something near the match. 847 if (LastLineNoFileIDQuery == FID) { 848 if (QueriedFilePos >= LastLineNoFilePos) { 849 // FIXME: Potential overflow? 850 SourceLineCache = SourceLineCache+LastLineNoResult-1; 851 852 // The query is likely to be nearby the previous one. Here we check to 853 // see if it is within 5, 10 or 20 lines. It can be far away in cases 854 // where big comment blocks and vertical whitespace eat up lines but 855 // contribute no tokens. 856 if (SourceLineCache+5 < SourceLineCacheEnd) { 857 if (SourceLineCache[5] > QueriedFilePos) 858 SourceLineCacheEnd = SourceLineCache+5; 859 else if (SourceLineCache+10 < SourceLineCacheEnd) { 860 if (SourceLineCache[10] > QueriedFilePos) 861 SourceLineCacheEnd = SourceLineCache+10; 862 else if (SourceLineCache+20 < SourceLineCacheEnd) { 863 if (SourceLineCache[20] > QueriedFilePos) 864 SourceLineCacheEnd = SourceLineCache+20; 865 } 866 } 867 } 868 } else { 869 if (LastLineNoResult < Content->NumLines) 870 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; 871 } 872 } 873 874 // If the spread is large, do a "radix" test as our initial guess, based on 875 // the assumption that lines average to approximately the same length. 876 // NOTE: This is currently disabled, as it does not appear to be profitable in 877 // initial measurements. 878 if (0 && SourceLineCacheEnd-SourceLineCache > 20) { 879 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1]; 880 881 // Take a stab at guessing where it is. 882 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen; 883 884 // Check for -10 and +10 lines. 885 unsigned LowerBound = std::max(int(ApproxPos-10), 0); 886 unsigned UpperBound = std::min(ApproxPos+10, FileLen); 887 888 // If the computed lower bound is less than the query location, move it in. 889 if (SourceLineCache < SourceLineCacheStart+LowerBound && 890 SourceLineCacheStart[LowerBound] < QueriedFilePos) 891 SourceLineCache = SourceLineCacheStart+LowerBound; 892 893 // If the computed upper bound is greater than the query location, move it. 894 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound && 895 SourceLineCacheStart[UpperBound] >= QueriedFilePos) 896 SourceLineCacheEnd = SourceLineCacheStart+UpperBound; 897 } 898 899 unsigned *Pos 900 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); 901 unsigned LineNo = Pos-SourceLineCacheStart; 902 903 LastLineNoFileIDQuery = FID; 904 LastLineNoContentCache = Content; 905 LastLineNoFilePos = QueriedFilePos; 906 LastLineNoResult = LineNo; 907 return LineNo; 908} 909 910unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc, 911 bool *Invalid) const { 912 if (Loc.isInvalid()) return 0; 913 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 914 return getLineNumber(LocInfo.first, LocInfo.second); 915} 916unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, 917 bool *Invalid) const { 918 if (Loc.isInvalid()) return 0; 919 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); 920 return getLineNumber(LocInfo.first, LocInfo.second); 921} 922 923/// getFileCharacteristic - return the file characteristic of the specified 924/// source location, indicating whether this is a normal file, a system 925/// header, or an "implicit extern C" system header. 926/// 927/// This state can be modified with flags on GNU linemarker directives like: 928/// # 4 "foo.h" 3 929/// which changes all source locations in the current file after that to be 930/// considered to be from a system header. 931SrcMgr::CharacteristicKind 932SourceManager::getFileCharacteristic(SourceLocation Loc) const { 933 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!"); 934 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 935 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile(); 936 937 // If there are no #line directives in this file, just return the whole-file 938 // state. 939 if (!FI.hasLineDirectives()) 940 return FI.getFileCharacteristic(); 941 942 assert(LineTable && "Can't have linetable entries without a LineTable!"); 943 // See if there is a #line directive before the location. 944 const LineEntry *Entry = 945 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second); 946 947 // If this is before the first line marker, use the file characteristic. 948 if (!Entry) 949 return FI.getFileCharacteristic(); 950 951 return Entry->FileKind; 952} 953 954/// Return the filename or buffer identifier of the buffer the location is in. 955/// Note that this name does not respect #line directives. Use getPresumedLoc 956/// for normal clients. 957const char *SourceManager::getBufferName(SourceLocation Loc, 958 bool *Invalid) const { 959 if (Loc.isInvalid()) return "<invalid loc>"; 960 961 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier(); 962} 963 964 965/// getPresumedLoc - This method returns the "presumed" location of a 966/// SourceLocation specifies. A "presumed location" can be modified by #line 967/// or GNU line marker directives. This provides a view on the data that a 968/// user should see in diagnostics, for example. 969/// 970/// Note that a presumed location is always given as the instantiation point 971/// of an instantiation location, not at the spelling location. 972PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const { 973 if (Loc.isInvalid()) return PresumedLoc(); 974 975 // Presumed locations are always for instantiation points. 976 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc); 977 978 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile(); 979 const SrcMgr::ContentCache *C = FI.getContentCache(); 980 981 // To get the source name, first consult the FileEntry (if one exists) 982 // before the MemBuffer as this will avoid unnecessarily paging in the 983 // MemBuffer. 984 const char *Filename = 985 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier(); 986 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second); 987 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second); 988 SourceLocation IncludeLoc = FI.getIncludeLoc(); 989 990 // If we have #line directives in this file, update and overwrite the physical 991 // location info if appropriate. 992 if (FI.hasLineDirectives()) { 993 assert(LineTable && "Can't have linetable entries without a LineTable!"); 994 // See if there is a #line directive before this. If so, get it. 995 if (const LineEntry *Entry = 996 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) { 997 // If the LineEntry indicates a filename, use it. 998 if (Entry->FilenameID != -1) 999 Filename = LineTable->getFilename(Entry->FilenameID); 1000 1001 // Use the line number specified by the LineEntry. This line number may 1002 // be multiple lines down from the line entry. Add the difference in 1003 // physical line numbers from the query point and the line marker to the 1004 // total. 1005 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); 1006 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); 1007 1008 // Note that column numbers are not molested by line markers. 1009 1010 // Handle virtual #include manipulation. 1011 if (Entry->IncludeOffset) { 1012 IncludeLoc = getLocForStartOfFile(LocInfo.first); 1013 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset); 1014 } 1015 } 1016 } 1017 1018 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc); 1019} 1020 1021//===----------------------------------------------------------------------===// 1022// Other miscellaneous methods. 1023//===----------------------------------------------------------------------===// 1024 1025/// \brief Get the source location for the given file:line:col triplet. 1026/// 1027/// If the source file is included multiple times, the source location will 1028/// be based upon the first inclusion. 1029SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, 1030 unsigned Line, unsigned Col) const { 1031 assert(SourceFile && "Null source file!"); 1032 assert(Line && Col && "Line and column should start from 1!"); 1033 1034 fileinfo_iterator FI = FileInfos.find(SourceFile); 1035 if (FI == FileInfos.end()) 1036 return SourceLocation(); 1037 ContentCache *Content = FI->second; 1038 1039 // If this is the first use of line information for this buffer, compute the 1040 /// SourceLineCache for it on demand. 1041 if (Content->SourceLineCache == 0) { 1042 bool MyInvalid = false; 1043 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid); 1044 if (MyInvalid) 1045 return SourceLocation(); 1046 } 1047 1048 // Find the first file ID that corresponds to the given file. 1049 FileID FirstFID; 1050 1051 // First, check the main file ID, since it is common to look for a 1052 // location in the main file. 1053 if (!MainFileID.isInvalid()) { 1054 const SLocEntry &MainSLoc = getSLocEntry(MainFileID); 1055 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content) 1056 FirstFID = MainFileID; 1057 } 1058 1059 if (FirstFID.isInvalid()) { 1060 // The location we're looking for isn't in the main file; look 1061 // through all of the source locations. 1062 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) { 1063 const SLocEntry &SLoc = getSLocEntry(I); 1064 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) { 1065 FirstFID = FileID::get(I); 1066 break; 1067 } 1068 } 1069 } 1070 1071 if (FirstFID.isInvalid()) 1072 return SourceLocation(); 1073 1074 if (Line > Content->NumLines) { 1075 unsigned Size = Content->getBuffer(Diag)->getBufferSize(); 1076 if (Size > 0) 1077 --Size; 1078 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size); 1079 } 1080 1081 unsigned FilePos = Content->SourceLineCache[Line - 1]; 1082 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos; 1083 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf; 1084 unsigned i = 0; 1085 1086 // Check that the given column is valid. 1087 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') 1088 ++i; 1089 if (i < Col-1) 1090 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i); 1091 1092 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1); 1093} 1094 1095/// \brief Determines the order of 2 source locations in the translation unit. 1096/// 1097/// \returns true if LHS source location comes before RHS, false otherwise. 1098bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, 1099 SourceLocation RHS) const { 1100 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); 1101 if (LHS == RHS) 1102 return false; 1103 1104 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); 1105 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); 1106 1107 // If the source locations are in the same file, just compare offsets. 1108 if (LOffs.first == ROffs.first) 1109 return LOffs.second < ROffs.second; 1110 1111 // If we are comparing a source location with multiple locations in the same 1112 // file, we get a big win by caching the result. 1113 1114 if (LastLFIDForBeforeTUCheck == LOffs.first && 1115 LastRFIDForBeforeTUCheck == ROffs.first) 1116 return LastResForBeforeTUCheck; 1117 1118 LastLFIDForBeforeTUCheck = LOffs.first; 1119 LastRFIDForBeforeTUCheck = ROffs.first; 1120 1121 // "Traverse" the include/instantiation stacks of both locations and try to 1122 // find a common "ancestor". 1123 // 1124 // First we traverse the stack of the right location and check each level 1125 // against the level of the left location, while collecting all levels in a 1126 // "stack map". 1127 1128 std::map<FileID, unsigned> ROffsMap; 1129 ROffsMap[ROffs.first] = ROffs.second; 1130 1131 while (1) { 1132 SourceLocation UpperLoc; 1133 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first); 1134 if (Entry.isInstantiation()) 1135 UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); 1136 else 1137 UpperLoc = Entry.getFile().getIncludeLoc(); 1138 1139 if (UpperLoc.isInvalid()) 1140 break; // We reached the top. 1141 1142 ROffs = getDecomposedLoc(UpperLoc); 1143 1144 if (LOffs.first == ROffs.first) 1145 return LastResForBeforeTUCheck = LOffs.second < ROffs.second; 1146 1147 ROffsMap[ROffs.first] = ROffs.second; 1148 } 1149 1150 // We didn't find a common ancestor. Now traverse the stack of the left 1151 // location, checking against the stack map of the right location. 1152 1153 while (1) { 1154 SourceLocation UpperLoc; 1155 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first); 1156 if (Entry.isInstantiation()) 1157 UpperLoc = Entry.getInstantiation().getInstantiationLocStart(); 1158 else 1159 UpperLoc = Entry.getFile().getIncludeLoc(); 1160 1161 if (UpperLoc.isInvalid()) 1162 break; // We reached the top. 1163 1164 LOffs = getDecomposedLoc(UpperLoc); 1165 1166 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first); 1167 if (I != ROffsMap.end()) 1168 return LastResForBeforeTUCheck = LOffs.second < I->second; 1169 } 1170 1171 // There is no common ancestor, most probably because one location is in the 1172 // predefines buffer. 1173 // 1174 // FIXME: We should rearrange the external interface so this simply never 1175 // happens; it can't conceptually happen. Also see PR5662. 1176 1177 // If exactly one location is a memory buffer, assume it preceeds the other. 1178 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry; 1179 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry; 1180 if (LIsMB != RIsMB) 1181 return LastResForBeforeTUCheck = LIsMB; 1182 1183 // Otherwise, just assume FileIDs were created in order. 1184 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first); 1185} 1186 1187/// PrintStats - Print statistics to stderr. 1188/// 1189void SourceManager::PrintStats() const { 1190 llvm::errs() << "\n*** Source Manager Stats:\n"; 1191 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() 1192 << " mem buffers mapped.\n"; 1193 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, " 1194 << NextOffset << "B of Sloc address space used.\n"; 1195 1196 unsigned NumLineNumsComputed = 0; 1197 unsigned NumFileBytesMapped = 0; 1198 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ 1199 NumLineNumsComputed += I->second->SourceLineCache != 0; 1200 NumFileBytesMapped += I->second->getSizeBytesMapped(); 1201 } 1202 1203 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " 1204 << NumLineNumsComputed << " files with line #'s computed.\n"; 1205 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " 1206 << NumBinaryProbes << " binary.\n"; 1207} 1208 1209ExternalSLocEntrySource::~ExternalSLocEntrySource() { } 1210