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