SourceManager.h revision 4f32786ac45210143654390177105eb749b614e9
1//===--- SourceManager.h - Track and cache source files ---------*- C++ -*-===// 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 defines the SourceManager interface. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_SOURCEMANAGER_H 15#define LLVM_CLANG_SOURCEMANAGER_H 16 17#include "clang/Basic/SourceLocation.h" 18#include "llvm/Support/Allocator.h" 19#include "llvm/Support/DataTypes.h" 20#include "llvm/ADT/PointerIntPair.h" 21#include "llvm/ADT/PointerUnion.h" 22#include "llvm/ADT/IntrusiveRefCntPtr.h" 23#include "llvm/ADT/DenseMap.h" 24#include <vector> 25#include <cassert> 26 27namespace llvm { 28class MemoryBuffer; 29class StringRef; 30} 31 32namespace clang { 33 34class Diagnostic; 35class SourceManager; 36class FileManager; 37class FileEntry; 38class LineTableInfo; 39 40/// SrcMgr - Public enums and private classes that are part of the 41/// SourceManager implementation. 42/// 43namespace SrcMgr { 44 /// CharacteristicKind - This is used to represent whether a file or directory 45 /// holds normal user code, system code, or system code which is implicitly 46 /// 'extern "C"' in C++ mode. Entire directories can be tagged with this 47 /// (this is maintained by DirectoryLookup and friends) as can specific 48 /// FileIDInfos when a #pragma system_header is seen or various other cases. 49 /// 50 enum CharacteristicKind { 51 C_User, C_System, C_ExternCSystem 52 }; 53 54 /// ContentCache - One instance of this struct is kept for every file 55 /// loaded or used. This object owns the MemoryBuffer object. 56 class ContentCache { 57 enum CCFlags { 58 /// \brief Whether the buffer is invalid. 59 InvalidFlag = 0x01, 60 /// \brief Whether the buffer should not be freed on destruction. 61 DoNotFreeFlag = 0x02 62 }; 63 64 /// Buffer - The actual buffer containing the characters from the input 65 /// file. This is owned by the ContentCache object. 66 /// The bits indicate indicates whether the buffer is invalid. 67 mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer; 68 69 public: 70 /// Reference to the file entry representing this ContentCache. 71 /// This reference does not own the FileEntry object. 72 /// It is possible for this to be NULL if 73 /// the ContentCache encapsulates an imaginary text buffer. 74 const FileEntry *OrigEntry; 75 76 /// \brief References the file which the contents were actually loaded from. 77 /// Can be different from 'Entry' if we overridden the contents of one file 78 /// with the contents of another file. 79 const FileEntry *ContentsEntry; 80 81 /// SourceLineCache - A bump pointer allocated array of offsets for each 82 /// source line. This is lazily computed. This is owned by the 83 /// SourceManager BumpPointerAllocator object. 84 unsigned *SourceLineCache; 85 86 /// NumLines - The number of lines in this ContentCache. This is only valid 87 /// if SourceLineCache is non-null. 88 unsigned NumLines; 89 90 /// getBuffer - Returns the memory buffer for the associated content. 91 /// 92 /// \param Diag Object through which diagnostics will be emitted it the 93 /// buffer cannot be retrieved. 94 /// 95 /// \param Loc If specified, is the location that invalid file diagnostics 96 /// will be emitted at. 97 /// 98 /// \param Invalid If non-NULL, will be set \c true if an error occurred. 99 const llvm::MemoryBuffer *getBuffer(Diagnostic &Diag, 100 const SourceManager &SM, 101 SourceLocation Loc = SourceLocation(), 102 bool *Invalid = 0) const; 103 104 /// getSize - Returns the size of the content encapsulated by this 105 /// ContentCache. This can be the size of the source file or the size of an 106 /// arbitrary scratch buffer. If the ContentCache encapsulates a source 107 /// file this size is retrieved from the file's FileEntry. 108 unsigned getSize() const; 109 110 /// getSizeBytesMapped - Returns the number of bytes actually mapped for 111 /// this ContentCache. This can be 0 if the MemBuffer was not actually 112 /// instantiated. 113 unsigned getSizeBytesMapped() const; 114 115 void setBuffer(const llvm::MemoryBuffer *B) { 116 assert(!Buffer.getPointer() && "MemoryBuffer already set."); 117 Buffer.setPointer(B); 118 Buffer.setInt(false); 119 } 120 121 /// \brief Get the underlying buffer, returning NULL if the buffer is not 122 /// yet available. 123 const llvm::MemoryBuffer *getRawBuffer() const { 124 return Buffer.getPointer(); 125 } 126 127 /// \brief Replace the existing buffer (which will be deleted) 128 /// with the given buffer. 129 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false); 130 131 /// \brief Determine whether the buffer itself is invalid. 132 bool isBufferInvalid() const { 133 return Buffer.getInt() & InvalidFlag; 134 } 135 136 /// \brief Determine whether the buffer should be freed. 137 bool shouldFreeBuffer() const { 138 return (Buffer.getInt() & DoNotFreeFlag) == 0; 139 } 140 141 ContentCache(const FileEntry *Ent = 0) 142 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent), 143 SourceLineCache(0), NumLines(0) {} 144 145 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt) 146 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt), 147 SourceLineCache(0), NumLines(0) {} 148 149 ~ContentCache(); 150 151 /// The copy ctor does not allow copies where source object has either 152 /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory 153 /// is not transfered, so this is a logical error. 154 ContentCache(const ContentCache &RHS) 155 : Buffer(0, false), SourceLineCache(0) 156 { 157 OrigEntry = RHS.OrigEntry; 158 ContentsEntry = RHS.ContentsEntry; 159 160 assert (RHS.Buffer.getPointer() == 0 && RHS.SourceLineCache == 0 161 && "Passed ContentCache object cannot own a buffer."); 162 163 NumLines = RHS.NumLines; 164 } 165 166 private: 167 // Disable assignments. 168 ContentCache &operator=(const ContentCache& RHS); 169 }; 170 171 /// FileInfo - Information about a FileID, basically just the logical file 172 /// that it represents and include stack information. 173 /// 174 /// Each FileInfo has include stack information, indicating where it came 175 /// from. This information encodes the #include chain that a token was 176 /// instantiated from. The main include file has an invalid IncludeLoc. 177 /// 178 /// FileInfos contain a "ContentCache *", with the contents of the file. 179 /// 180 class FileInfo { 181 /// IncludeLoc - The location of the #include that brought in this file. 182 /// This is an invalid SLOC for the main file (top of the #include chain). 183 unsigned IncludeLoc; // Really a SourceLocation 184 185 /// Data - This contains the ContentCache* and the bits indicating the 186 /// characteristic of the file and whether it has #line info, all bitmangled 187 /// together. 188 uintptr_t Data; 189 public: 190 /// get - Return a FileInfo object. 191 static FileInfo get(SourceLocation IL, const ContentCache *Con, 192 CharacteristicKind FileCharacter) { 193 FileInfo X; 194 X.IncludeLoc = IL.getRawEncoding(); 195 X.Data = (uintptr_t)Con; 196 assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned"); 197 assert((unsigned)FileCharacter < 4 && "invalid file character"); 198 X.Data |= (unsigned)FileCharacter; 199 return X; 200 } 201 202 SourceLocation getIncludeLoc() const { 203 return SourceLocation::getFromRawEncoding(IncludeLoc); 204 } 205 const ContentCache* getContentCache() const { 206 return reinterpret_cast<const ContentCache*>(Data & ~7UL); 207 } 208 209 /// getCharacteristic - Return whether this is a system header or not. 210 CharacteristicKind getFileCharacteristic() const { 211 return (CharacteristicKind)(Data & 3); 212 } 213 214 /// hasLineDirectives - Return true if this FileID has #line directives in 215 /// it. 216 bool hasLineDirectives() const { return (Data & 4) != 0; } 217 218 /// setHasLineDirectives - Set the flag that indicates that this FileID has 219 /// line table entries associated with it. 220 void setHasLineDirectives() { 221 Data |= 4; 222 } 223 }; 224 225 /// InstantiationInfo - Each InstantiationInfo encodes the Instantiation 226 /// location - where the token was ultimately instantiated, and the 227 /// SpellingLoc - where the actual character data for the token came from. 228 class InstantiationInfo { 229 // Really these are all SourceLocations. 230 231 /// SpellingLoc - Where the spelling for the token can be found. 232 unsigned SpellingLoc; 233 234 /// InstantiationLocStart/InstantiationLocEnd - In a macro expansion, these 235 /// indicate the start and end of the instantiation. In object-like macros, 236 /// these will be the same. In a function-like macro instantiation, the 237 /// start will be the identifier and the end will be the ')'. 238 unsigned InstantiationLocStart, InstantiationLocEnd; 239 public: 240 SourceLocation getSpellingLoc() const { 241 return SourceLocation::getFromRawEncoding(SpellingLoc); 242 } 243 SourceLocation getInstantiationLocStart() const { 244 return SourceLocation::getFromRawEncoding(InstantiationLocStart); 245 } 246 SourceLocation getInstantiationLocEnd() const { 247 return SourceLocation::getFromRawEncoding(InstantiationLocEnd); 248 } 249 250 std::pair<SourceLocation,SourceLocation> getInstantiationLocRange() const { 251 return std::make_pair(getInstantiationLocStart(), 252 getInstantiationLocEnd()); 253 } 254 255 /// get - Return a InstantiationInfo for an expansion. IL specifies 256 /// the instantiation location (where the macro is expanded), and SL 257 /// specifies the spelling location (where the characters from the token 258 /// come from). IL and PL can both refer to normal File SLocs or 259 /// instantiation locations. 260 static InstantiationInfo get(SourceLocation ILStart, SourceLocation ILEnd, 261 SourceLocation SL) { 262 InstantiationInfo X; 263 X.SpellingLoc = SL.getRawEncoding(); 264 X.InstantiationLocStart = ILStart.getRawEncoding(); 265 X.InstantiationLocEnd = ILEnd.getRawEncoding(); 266 return X; 267 } 268 }; 269 270 /// SLocEntry - This is a discriminated union of FileInfo and 271 /// InstantiationInfo. SourceManager keeps an array of these objects, and 272 /// they are uniquely identified by the FileID datatype. 273 class SLocEntry { 274 unsigned Offset; // low bit is set for instantiation info. 275 union { 276 FileInfo File; 277 InstantiationInfo Instantiation; 278 }; 279 public: 280 unsigned getOffset() const { return Offset >> 1; } 281 282 bool isInstantiation() const { return Offset & 1; } 283 bool isFile() const { return !isInstantiation(); } 284 285 const FileInfo &getFile() const { 286 assert(isFile() && "Not a file SLocEntry!"); 287 return File; 288 } 289 290 const InstantiationInfo &getInstantiation() const { 291 assert(isInstantiation() && "Not an instantiation SLocEntry!"); 292 return Instantiation; 293 } 294 295 static SLocEntry get(unsigned Offset, const FileInfo &FI) { 296 SLocEntry E; 297 E.Offset = Offset << 1; 298 E.File = FI; 299 return E; 300 } 301 302 static SLocEntry get(unsigned Offset, const InstantiationInfo &II) { 303 SLocEntry E; 304 E.Offset = (Offset << 1) | 1; 305 E.Instantiation = II; 306 return E; 307 } 308 }; 309} // end SrcMgr namespace. 310 311/// \brief External source of source location entries. 312class ExternalSLocEntrySource { 313public: 314 virtual ~ExternalSLocEntrySource(); 315 316 /// \brief Read the source location entry with index ID. 317 virtual void ReadSLocEntry(unsigned ID) = 0; 318}; 319 320 321/// IsBeforeInTranslationUnitCache - This class holds the cache used by 322/// isBeforeInTranslationUnit. The cache structure is complex enough to be 323/// worth breaking out of SourceManager. 324class IsBeforeInTranslationUnitCache { 325 /// L/R QueryFID - These are the FID's of the cached query. If these match up 326 /// with a subsequent query, the result can be reused. 327 FileID LQueryFID, RQueryFID; 328 329 /// CommonFID - This is the file found in common between the two #include 330 /// traces. It is the nearest common ancestor of the #include tree. 331 FileID CommonFID; 332 333 /// L/R CommonOffset - This is the offset of the previous query in CommonFID. 334 /// Usually, this represents the location of the #include for QueryFID, but if 335 /// LQueryFID is a parent of RQueryFID (or vise versa) then these can be a 336 /// random token in the parent. 337 unsigned LCommonOffset, RCommonOffset; 338public: 339 340 /// isCacheValid - Return true if the currently cached values match up with 341 /// the specified LHS/RHS query. If not, we can't use the cache. 342 bool isCacheValid(FileID LHS, FileID RHS) const { 343 return LQueryFID == LHS && RQueryFID == RHS; 344 } 345 346 /// getCachedResult - If the cache is valid, compute the result given the 347 /// specified offsets in the LHS/RHS FID's. 348 bool getCachedResult(unsigned LOffset, unsigned ROffset) const { 349 // If one of the query files is the common file, use the offset. Otherwise, 350 // use the #include loc in the common file. 351 if (LQueryFID != CommonFID) LOffset = LCommonOffset; 352 if (RQueryFID != CommonFID) ROffset = RCommonOffset; 353 return LOffset < ROffset; 354 } 355 356 // Set up a new query. 357 void setQueryFIDs(FileID LHS, FileID RHS) { 358 LQueryFID = LHS; 359 RQueryFID = RHS; 360 } 361 362 void setCommonLoc(FileID commonFID, unsigned lCommonOffset, 363 unsigned rCommonOffset) { 364 CommonFID = commonFID; 365 LCommonOffset = lCommonOffset; 366 RCommonOffset = rCommonOffset; 367 } 368 369}; 370 371/// SourceManager - This file handles loading and caching of source files into 372/// memory. This object owns the MemoryBuffer objects for all of the loaded 373/// files and assigns unique FileID's for each unique #include chain. 374/// 375/// The SourceManager can be queried for information about SourceLocation 376/// objects, turning them into either spelling or instantiation locations. 377/// Spelling locations represent where the bytes corresponding to a token came 378/// from and instantiation locations represent where the location is in the 379/// user's view. In the case of a macro expansion, for example, the spelling 380/// location indicates where the expanded token came from and the instantiation 381/// location specifies where it was expanded. 382class SourceManager : public llvm::RefCountedBase<SourceManager> { 383 /// \brief Diagnostic object. 384 Diagnostic &Diag; 385 386 FileManager &FileMgr; 387 388 mutable llvm::BumpPtrAllocator ContentCacheAlloc; 389 390 /// FileInfos - Memoized information about all of the files tracked by this 391 /// SourceManager. This set allows us to merge ContentCache entries based 392 /// on their FileEntry*. All ContentCache objects will thus have unique, 393 /// non-null, FileEntry pointers. 394 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos; 395 396 /// \brief True if the ContentCache for files that are overriden by other 397 /// files, should report the original file name. Defaults to true. 398 bool OverridenFilesKeepOriginalName; 399 400 /// \brief Files that have been overriden with the contents from another file. 401 llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles; 402 403 /// MemBufferInfos - Information about various memory buffers that we have 404 /// read in. All FileEntry* within the stored ContentCache objects are NULL, 405 /// as they do not refer to a file. 406 std::vector<SrcMgr::ContentCache*> MemBufferInfos; 407 408 /// SLocEntryTable - This is an array of SLocEntry's that we have created. 409 /// FileID is an index into this vector. This array is sorted by the offset. 410 std::vector<SrcMgr::SLocEntry> SLocEntryTable; 411 /// NextOffset - This is the next available offset that a new SLocEntry can 412 /// start at. It is SLocEntryTable.back().getOffset()+size of back() entry. 413 unsigned NextOffset; 414 415 /// \brief If source location entries are being lazily loaded from 416 /// an external source, this vector indicates whether the Ith source 417 /// location entry has already been loaded from the external storage. 418 std::vector<bool> SLocEntryLoaded; 419 420 /// \brief An external source for source location entries. 421 ExternalSLocEntrySource *ExternalSLocEntries; 422 423 /// LastFileIDLookup - This is a one-entry cache to speed up getFileID. 424 /// LastFileIDLookup records the last FileID looked up or created, because it 425 /// is very common to look up many tokens from the same file. 426 mutable FileID LastFileIDLookup; 427 428 /// LineTable - This holds information for #line directives. It is referenced 429 /// by indices from SLocEntryTable. 430 LineTableInfo *LineTable; 431 432 /// LastLineNo - These ivars serve as a cache used in the getLineNumber 433 /// method which is used to speedup getLineNumber calls to nearby locations. 434 mutable FileID LastLineNoFileIDQuery; 435 mutable SrcMgr::ContentCache *LastLineNoContentCache; 436 mutable unsigned LastLineNoFilePos; 437 mutable unsigned LastLineNoResult; 438 439 /// MainFileID - The file ID for the main source file of the translation unit. 440 FileID MainFileID; 441 442 // Statistics for -print-stats. 443 mutable unsigned NumLinearScans, NumBinaryProbes; 444 445 // Cache results for the isBeforeInTranslationUnit method. 446 mutable IsBeforeInTranslationUnitCache IsBeforeInTUCache; 447 448 // SourceManager doesn't support copy construction. 449 explicit SourceManager(const SourceManager&); 450 void operator=(const SourceManager&); 451public: 452 SourceManager(Diagnostic &Diag, FileManager &FileMgr); 453 ~SourceManager(); 454 455 void clearIDTables(); 456 457 Diagnostic &getDiagnostics() const { return Diag; } 458 459 FileManager &getFileManager() const { return FileMgr; } 460 461 /// \brief Set true if the SourceManager should report the original file name 462 /// for contents of files that were overriden by other files.Defaults to true. 463 void setOverridenFilesKeepOriginalName(bool value) { 464 OverridenFilesKeepOriginalName = value; 465 } 466 467 //===--------------------------------------------------------------------===// 468 // MainFileID creation and querying methods. 469 //===--------------------------------------------------------------------===// 470 471 /// getMainFileID - Returns the FileID of the main source file. 472 FileID getMainFileID() const { return MainFileID; } 473 474 /// createMainFileID - Create the FileID for the main source file. 475 FileID createMainFileID(const FileEntry *SourceFile) { 476 assert(MainFileID.isInvalid() && "MainFileID already set!"); 477 MainFileID = createFileID(SourceFile, SourceLocation(), SrcMgr::C_User); 478 return MainFileID; 479 } 480 481 /// \brief Set the file ID for the precompiled preamble, which is also the 482 /// main file. 483 void SetPreambleFileID(FileID Preamble) { 484 assert(MainFileID.isInvalid() && "MainFileID already set!"); 485 MainFileID = Preamble; 486 } 487 488 //===--------------------------------------------------------------------===// 489 // Methods to create new FileID's and instantiations. 490 //===--------------------------------------------------------------------===// 491 492 /// createFileID - Create a new FileID that represents the specified file 493 /// being #included from the specified IncludePosition. This returns 0 on 494 /// error and translates NULL into standard input. 495 /// PreallocateID should be non-zero to specify which pre-allocated, 496 /// lazily computed source location is being filled in by this operation. 497 FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, 498 SrcMgr::CharacteristicKind FileCharacter, 499 unsigned PreallocatedID = 0, 500 unsigned Offset = 0) { 501 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); 502 assert(IR && "getOrCreateContentCache() cannot return NULL"); 503 return createFileID(IR, IncludePos, FileCharacter, PreallocatedID, Offset); 504 } 505 506 /// createFileIDForMemBuffer - Create a new FileID that represents the 507 /// specified memory buffer. This does no caching of the buffer and takes 508 /// ownership of the MemoryBuffer, so only pass a MemoryBuffer to this once. 509 FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer, 510 unsigned PreallocatedID = 0, 511 unsigned Offset = 0) { 512 return createFileID(createMemBufferContentCache(Buffer), SourceLocation(), 513 SrcMgr::C_User, PreallocatedID, Offset); 514 } 515 516 /// createMainFileIDForMembuffer - Create the FileID for a memory buffer 517 /// that will represent the FileID for the main source. One example 518 /// of when this would be used is when the main source is read from STDIN. 519 FileID createMainFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer) { 520 assert(MainFileID.isInvalid() && "MainFileID already set!"); 521 MainFileID = createFileIDForMemBuffer(Buffer); 522 return MainFileID; 523 } 524 525 /// createInstantiationLoc - Return a new SourceLocation that encodes the fact 526 /// that a token at Loc should actually be referenced from InstantiationLoc. 527 /// TokLength is the length of the token being instantiated. 528 SourceLocation createInstantiationLoc(SourceLocation Loc, 529 SourceLocation InstantiationLocStart, 530 SourceLocation InstantiationLocEnd, 531 unsigned TokLength, 532 unsigned PreallocatedID = 0, 533 unsigned Offset = 0); 534 535 /// \brief Retrieve the memory buffer associated with the given file. 536 /// 537 /// \param Invalid If non-NULL, will be set \c true if an error 538 /// occurs while retrieving the memory buffer. 539 const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File, 540 bool *Invalid = 0); 541 542 /// \brief Override the contents of the given source file by providing an 543 /// already-allocated buffer. 544 /// 545 /// \param SourceFile the source file whose contents will be overriden. 546 /// 547 /// \param Buffer the memory buffer whose contents will be used as the 548 /// data in the given source file. 549 /// 550 /// \param DoNotFree If true, then the buffer will not be freed when the 551 /// source manager is destroyed. 552 void overrideFileContents(const FileEntry *SourceFile, 553 const llvm::MemoryBuffer *Buffer, 554 bool DoNotFree = false); 555 556 /// \brief Override the the given source file with another one. 557 /// 558 /// \param SourceFile the source file which will be overriden. 559 /// 560 /// \param NewFile the file whose contents will be used as the 561 /// data instead of the contents of the given source file. 562 void overrideFileContents(const FileEntry *SourceFile, 563 const FileEntry *NewFile); 564 565 //===--------------------------------------------------------------------===// 566 // FileID manipulation methods. 567 //===--------------------------------------------------------------------===// 568 569 /// getBuffer - Return the buffer for the specified FileID. If there is an 570 /// error opening this buffer the first time, this manufactures a temporary 571 /// buffer and returns a non-empty error string. 572 const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc, 573 bool *Invalid = 0) const { 574 return getSLocEntry(FID).getFile().getContentCache() 575 ->getBuffer(Diag, *this, Loc, Invalid); 576 } 577 578 const llvm::MemoryBuffer *getBuffer(FileID FID, bool *Invalid = 0) const { 579 return getSLocEntry(FID).getFile().getContentCache() 580 ->getBuffer(Diag, *this, SourceLocation(), Invalid); 581 } 582 583 /// getFileEntryForID - Returns the FileEntry record for the provided FileID. 584 const FileEntry *getFileEntryForID(FileID FID) const { 585 return getSLocEntry(FID).getFile().getContentCache()->OrigEntry; 586 } 587 588 /// getBufferData - Return a StringRef to the source buffer data for the 589 /// specified FileID. 590 /// 591 /// \param FID The file ID whose contents will be returned. 592 /// \param Invalid If non-NULL, will be set true if an error occurred. 593 llvm::StringRef getBufferData(FileID FID, bool *Invalid = 0) const; 594 595 596 //===--------------------------------------------------------------------===// 597 // SourceLocation manipulation methods. 598 //===--------------------------------------------------------------------===// 599 600 /// getFileID - Return the FileID for a SourceLocation. This is a very 601 /// hot method that is used for all SourceManager queries that start with a 602 /// SourceLocation object. It is responsible for finding the entry in 603 /// SLocEntryTable which contains the specified location. 604 /// 605 FileID getFileID(SourceLocation SpellingLoc) const { 606 unsigned SLocOffset = SpellingLoc.getOffset(); 607 608 // If our one-entry cache covers this offset, just return it. 609 if (isOffsetInFileID(LastFileIDLookup, SLocOffset)) 610 return LastFileIDLookup; 611 612 return getFileIDSlow(SLocOffset); 613 } 614 615 /// getLocForStartOfFile - Return the source location corresponding to the 616 /// first byte of the specified file. 617 SourceLocation getLocForStartOfFile(FileID FID) const { 618 assert(FID.ID < SLocEntryTable.size() && "FileID out of range"); 619 assert(getSLocEntry(FID).isFile() && "FileID is not a file"); 620 unsigned FileOffset = getSLocEntry(FID).getOffset(); 621 return SourceLocation::getFileLoc(FileOffset); 622 } 623 624 /// getInstantiationLoc - Given a SourceLocation object, return the 625 /// instantiation location referenced by the ID. 626 SourceLocation getInstantiationLoc(SourceLocation Loc) const { 627 // Handle the non-mapped case inline, defer to out of line code to handle 628 // instantiations. 629 if (Loc.isFileID()) return Loc; 630 return getInstantiationLocSlowCase(Loc); 631 } 632 633 /// getImmediateInstantiationRange - Loc is required to be an instantiation 634 /// location. Return the start/end of the instantiation information. 635 std::pair<SourceLocation,SourceLocation> 636 getImmediateInstantiationRange(SourceLocation Loc) const; 637 638 /// getInstantiationRange - Given a SourceLocation object, return the 639 /// range of tokens covered by the instantiation in the ultimate file. 640 std::pair<SourceLocation,SourceLocation> 641 getInstantiationRange(SourceLocation Loc) const; 642 643 644 /// getSpellingLoc - Given a SourceLocation object, return the spelling 645 /// location referenced by the ID. This is the place where the characters 646 /// that make up the lexed token can be found. 647 SourceLocation getSpellingLoc(SourceLocation Loc) const { 648 // Handle the non-mapped case inline, defer to out of line code to handle 649 // instantiations. 650 if (Loc.isFileID()) return Loc; 651 return getSpellingLocSlowCase(Loc); 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. 658 SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const; 659 660 /// getDecomposedLoc - Decompose the specified location into a raw FileID + 661 /// Offset pair. The first element is the FileID, the second is the 662 /// offset from the start of the buffer of the location. 663 std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const { 664 FileID FID = getFileID(Loc); 665 return std::make_pair(FID, Loc.getOffset()-getSLocEntry(FID).getOffset()); 666 } 667 668 /// getDecomposedInstantiationLoc - Decompose the specified location into a 669 /// raw FileID + Offset pair. If the location is an instantiation record, 670 /// walk through it until we find the final location instantiated. 671 std::pair<FileID, unsigned> 672 getDecomposedInstantiationLoc(SourceLocation Loc) const { 673 FileID FID = getFileID(Loc); 674 const SrcMgr::SLocEntry *E = &getSLocEntry(FID); 675 676 unsigned Offset = Loc.getOffset()-E->getOffset(); 677 if (Loc.isFileID()) 678 return std::make_pair(FID, Offset); 679 680 return getDecomposedInstantiationLocSlowCase(E, Offset); 681 } 682 683 /// getDecomposedSpellingLoc - Decompose the specified location into a raw 684 /// FileID + Offset pair. If the location is an instantiation record, walk 685 /// through it until we find its spelling record. 686 std::pair<FileID, unsigned> 687 getDecomposedSpellingLoc(SourceLocation Loc) const { 688 FileID FID = getFileID(Loc); 689 const SrcMgr::SLocEntry *E = &getSLocEntry(FID); 690 691 unsigned Offset = Loc.getOffset()-E->getOffset(); 692 if (Loc.isFileID()) 693 return std::make_pair(FID, Offset); 694 return getDecomposedSpellingLocSlowCase(E, Offset); 695 } 696 697 /// getFileOffset - This method returns the offset from the start 698 /// of the file that the specified SourceLocation represents. This is not very 699 /// meaningful for a macro ID. 700 unsigned getFileOffset(SourceLocation SpellingLoc) const { 701 return getDecomposedLoc(SpellingLoc).second; 702 } 703 704 705 //===--------------------------------------------------------------------===// 706 // Queries about the code at a SourceLocation. 707 //===--------------------------------------------------------------------===// 708 709 /// getCharacterData - Return a pointer to the start of the specified location 710 /// in the appropriate spelling MemoryBuffer. 711 /// 712 /// \param Invalid If non-NULL, will be set \c true if an error occurs. 713 const char *getCharacterData(SourceLocation SL, bool *Invalid = 0) const; 714 715 /// getColumnNumber - Return the column # for the specified file position. 716 /// This is significantly cheaper to compute than the line number. This 717 /// returns zero if the column number isn't known. This may only be called on 718 /// a file sloc, so you must choose a spelling or instantiation location 719 /// before calling this method. 720 unsigned getColumnNumber(FileID FID, unsigned FilePos, 721 bool *Invalid = 0) const; 722 unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid = 0) const; 723 unsigned getInstantiationColumnNumber(SourceLocation Loc, 724 bool *Invalid = 0) const; 725 unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid = 0) const; 726 727 728 /// getLineNumber - Given a SourceLocation, return the spelling line number 729 /// for the position indicated. This requires building and caching a table of 730 /// line offsets for the MemoryBuffer, so this is not cheap: use only when 731 /// about to emit a diagnostic. 732 unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = 0) const; 733 unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = 0) const; 734 unsigned getInstantiationLineNumber(SourceLocation Loc, 735 bool *Invalid = 0) const; 736 unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = 0) const; 737 738 /// Return the filename or buffer identifier of the buffer the location is in. 739 /// Note that this name does not respect #line directives. Use getPresumedLoc 740 /// for normal clients. 741 const char *getBufferName(SourceLocation Loc, bool *Invalid = 0) const; 742 743 /// getFileCharacteristic - return the file characteristic of the specified 744 /// source location, indicating whether this is a normal file, a system 745 /// header, or an "implicit extern C" system header. 746 /// 747 /// This state can be modified with flags on GNU linemarker directives like: 748 /// # 4 "foo.h" 3 749 /// which changes all source locations in the current file after that to be 750 /// considered to be from a system header. 751 SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const; 752 753 /// getPresumedLoc - This method returns the "presumed" location of a 754 /// SourceLocation specifies. A "presumed location" can be modified by #line 755 /// or GNU line marker directives. This provides a view on the data that a 756 /// user should see in diagnostics, for example. 757 /// 758 /// Note that a presumed location is always given as the instantiation point 759 /// of an instantiation location, not at the spelling location. 760 /// 761 /// \returns The presumed location of the specified SourceLocation. If the 762 /// presumed location cannot be calculate (e.g., because \p Loc is invalid 763 /// or the file containing \p Loc has changed on disk), returns an invalid 764 /// presumed location. 765 PresumedLoc getPresumedLoc(SourceLocation Loc) const; 766 767 /// isFromSameFile - Returns true if both SourceLocations correspond to 768 /// the same file. 769 bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const { 770 return getFileID(Loc1) == getFileID(Loc2); 771 } 772 773 /// isFromMainFile - Returns true if the file of provided SourceLocation is 774 /// the main file. 775 bool isFromMainFile(SourceLocation Loc) const { 776 return getFileID(Loc) == getMainFileID(); 777 } 778 779 /// isInSystemHeader - Returns if a SourceLocation is in a system header. 780 bool isInSystemHeader(SourceLocation Loc) const { 781 return getFileCharacteristic(Loc) != SrcMgr::C_User; 782 } 783 784 /// isInExternCSystemHeader - Returns if a SourceLocation is in an "extern C" 785 /// system header. 786 bool isInExternCSystemHeader(SourceLocation Loc) const { 787 return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem; 788 } 789 790 //===--------------------------------------------------------------------===// 791 // Line Table Manipulation Routines 792 //===--------------------------------------------------------------------===// 793 794 /// getLineTableFilenameID - Return the uniqued ID for the specified filename. 795 /// 796 unsigned getLineTableFilenameID(const char *Ptr, unsigned Len); 797 798 /// AddLineNote - Add a line note to the line table for the FileID and offset 799 /// specified by Loc. If FilenameID is -1, it is considered to be 800 /// unspecified. 801 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID); 802 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, 803 bool IsFileEntry, bool IsFileExit, 804 bool IsSystemHeader, bool IsExternCHeader); 805 806 /// \brief Determine if the source manager has a line table. 807 bool hasLineTable() const { return LineTable != 0; } 808 809 /// \brief Retrieve the stored line table. 810 LineTableInfo &getLineTable(); 811 812 //===--------------------------------------------------------------------===// 813 // Other miscellaneous methods. 814 //===--------------------------------------------------------------------===// 815 816 /// \brief Get the source location for the given file:line:col triplet. 817 /// 818 /// If the source file is included multiple times, the source location will 819 /// be based upon the first inclusion. 820 SourceLocation getLocation(const FileEntry *SourceFile, 821 unsigned Line, unsigned Col); 822 823 /// \brief Determines the order of 2 source locations in the translation unit. 824 /// 825 /// \returns true if LHS source location comes before RHS, false otherwise. 826 bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const; 827 828 // Iterators over FileInfos. 829 typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> 830 ::const_iterator fileinfo_iterator; 831 fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); } 832 fileinfo_iterator fileinfo_end() const { return FileInfos.end(); } 833 bool hasFileInfo(const FileEntry *File) const { 834 return FileInfos.find(File) != FileInfos.end(); 835 } 836 837 /// PrintStats - Print statistics to stderr. 838 /// 839 void PrintStats() const; 840 841 unsigned sloc_entry_size() const { return SLocEntryTable.size(); } 842 843 // FIXME: Exposing this is a little gross; what we want is a good way 844 // to iterate the entries that were not defined in an AST file (or 845 // any other external source). 846 unsigned sloc_loaded_entry_size() const { return SLocEntryLoaded.size(); } 847 848 const SrcMgr::SLocEntry &getSLocEntry(unsigned ID) const { 849 assert(ID < SLocEntryTable.size() && "Invalid id"); 850 if (ExternalSLocEntries && 851 ID < SLocEntryLoaded.size() && 852 !SLocEntryLoaded[ID]) 853 ExternalSLocEntries->ReadSLocEntry(ID); 854 return SLocEntryTable[ID]; 855 } 856 857 const SrcMgr::SLocEntry &getSLocEntry(FileID FID) const { 858 return getSLocEntry(FID.ID); 859 } 860 861 unsigned getNextOffset() const { return NextOffset; } 862 863 /// \brief Preallocate some number of source location entries, which 864 /// will be loaded as needed from the given external source. 865 void PreallocateSLocEntries(ExternalSLocEntrySource *Source, 866 unsigned NumSLocEntries, 867 unsigned NextOffset); 868 869 /// \brief Clear out any preallocated source location entries that 870 /// haven't already been loaded. 871 void ClearPreallocatedSLocEntries(); 872 873private: 874 /// isOffsetInFileID - Return true if the specified FileID contains the 875 /// specified SourceLocation offset. This is a very hot method. 876 inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const { 877 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID); 878 // If the entry is after the offset, it can't contain it. 879 if (SLocOffset < Entry.getOffset()) return false; 880 881 // If this is the last entry than it does. Otherwise, the entry after it 882 // has to not include it. 883 if (FID.ID+1 == SLocEntryTable.size()) return true; 884 885 return SLocOffset < getSLocEntry(FileID::get(FID.ID+1)).getOffset(); 886 } 887 888 /// createFileID - Create a new fileID for the specified ContentCache and 889 /// include position. This works regardless of whether the ContentCache 890 /// corresponds to a file or some other input source. 891 FileID createFileID(const SrcMgr::ContentCache* File, 892 SourceLocation IncludePos, 893 SrcMgr::CharacteristicKind DirCharacter, 894 unsigned PreallocatedID = 0, 895 unsigned Offset = 0); 896 897 const SrcMgr::ContentCache * 898 getOrCreateContentCache(const FileEntry *SourceFile); 899 900 /// createMemBufferContentCache - Create a new ContentCache for the specified 901 /// memory buffer. 902 const SrcMgr::ContentCache* 903 createMemBufferContentCache(const llvm::MemoryBuffer *Buf); 904 905 FileID getFileIDSlow(unsigned SLocOffset) const; 906 907 SourceLocation getInstantiationLocSlowCase(SourceLocation Loc) const; 908 SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const; 909 910 std::pair<FileID, unsigned> 911 getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E, 912 unsigned Offset) const; 913 std::pair<FileID, unsigned> 914 getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, 915 unsigned Offset) const; 916}; 917 918 919} // end namespace clang 920 921#endif 922