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