1 //===--- SourceManager.h - Track and cache source files ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SourceManager interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SOURCEMANAGER_H
15 #define LLVM_CLANG_SOURCEMANAGER_H
17 #include "clang/Basic/LLVM.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/ADT/PointerIntPair.h"
22 #include "llvm/ADT/PointerUnion.h"
23 #include "llvm/ADT/IntrusiveRefCntPtr.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/Support/MemoryBuffer.h"
32 class DiagnosticsEngine;
41 /// There are three different types of locations in a file: a spelling
42 /// location, an expansion location, and a presumed location.
44 /// Given an example of:
45 /// #define min(x, y) x < y ? x : y
47 /// and then later on a use of min:
51 /// The expansion location is the line in the source code where the macro
52 /// was expanded (the return statement), the spelling location is the
53 /// location in the source where the macro was originally defined,
54 /// and the presumed location is where the line directive states that
55 /// the line is 17, or any other line.
57 /// SrcMgr - Public enums and private classes that are part of the
58 /// SourceManager implementation.
61 /// CharacteristicKind - This is used to represent whether a file or directory
62 /// holds normal user code, system code, or system code which is implicitly
63 /// 'extern "C"' in C++ mode. Entire directories can be tagged with this
64 /// (this is maintained by DirectoryLookup and friends) as can specific
65 /// FileInfos when a #pragma system_header is seen or various other cases.
67 enum CharacteristicKind {
68 C_User, C_System, C_ExternCSystem
71 /// ContentCache - One instance of this struct is kept for every file
72 /// loaded or used. This object owns the MemoryBuffer object.
75 /// \brief Whether the buffer is invalid.
77 /// \brief Whether the buffer should not be freed on destruction.
81 /// Buffer - The actual buffer containing the characters from the input
82 /// file. This is owned by the ContentCache object.
83 /// The bits indicate indicates whether the buffer is invalid.
84 mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer;
87 /// Reference to the file entry representing this ContentCache.
88 /// This reference does not own the FileEntry object.
89 /// It is possible for this to be NULL if
90 /// the ContentCache encapsulates an imaginary text buffer.
91 const FileEntry *OrigEntry;
93 /// \brief References the file which the contents were actually loaded from.
94 /// Can be different from 'Entry' if we overridden the contents of one file
95 /// with the contents of another file.
96 const FileEntry *ContentsEntry;
98 /// SourceLineCache - A bump pointer allocated array of offsets for each
99 /// source line. This is lazily computed. This is owned by the
100 /// SourceManager BumpPointerAllocator object.
101 unsigned *SourceLineCache;
103 /// NumLines - The number of lines in this ContentCache. This is only valid
104 /// if SourceLineCache is non-null.
105 unsigned NumLines : 31;
107 /// \brief Indicates whether the buffer itself was provided to override
108 /// the actual file contents.
110 /// When true, the original entry may be a virtual file that does not
112 unsigned BufferOverridden : 1;
114 /// getBuffer - Returns the memory buffer for the associated content.
116 /// \param Diag Object through which diagnostics will be emitted if the
117 /// buffer cannot be retrieved.
119 /// \param Loc If specified, is the location that invalid file diagnostics
120 /// will be emitted at.
122 /// \param Invalid If non-NULL, will be set \c true if an error occurred.
123 const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
124 const SourceManager &SM,
125 SourceLocation Loc = SourceLocation(),
126 bool *Invalid = 0) const;
128 /// getSize - Returns the size of the content encapsulated by this
129 /// ContentCache. This can be the size of the source file or the size of an
130 /// arbitrary scratch buffer. If the ContentCache encapsulates a source
131 /// file this size is retrieved from the file's FileEntry.
132 unsigned getSize() const;
134 /// getSizeBytesMapped - Returns the number of bytes actually mapped for
135 /// this ContentCache. This can be 0 if the MemBuffer was not actually
137 unsigned getSizeBytesMapped() const;
139 /// Returns the kind of memory used to back the memory buffer for
140 /// this content cache. This is used for performance analysis.
141 llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
143 void setBuffer(const llvm::MemoryBuffer *B) {
144 assert(!Buffer.getPointer() && "MemoryBuffer already set.");
145 Buffer.setPointer(B);
146 Buffer.setInt(false);
149 /// \brief Get the underlying buffer, returning NULL if the buffer is not
151 const llvm::MemoryBuffer *getRawBuffer() const {
152 return Buffer.getPointer();
155 /// \brief Replace the existing buffer (which will be deleted)
156 /// with the given buffer.
157 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
159 /// \brief Determine whether the buffer itself is invalid.
160 bool isBufferInvalid() const {
161 return Buffer.getInt() & InvalidFlag;
164 /// \brief Determine whether the buffer should be freed.
165 bool shouldFreeBuffer() const {
166 return (Buffer.getInt() & DoNotFreeFlag) == 0;
169 ContentCache(const FileEntry *Ent = 0)
170 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent),
171 SourceLineCache(0), NumLines(0) {}
173 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
174 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt),
175 SourceLineCache(0), NumLines(0) {}
179 /// The copy ctor does not allow copies where source object has either
180 /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
181 /// is not transferred, so this is a logical error.
182 ContentCache(const ContentCache &RHS)
183 : Buffer(0, false), SourceLineCache(0)
185 OrigEntry = RHS.OrigEntry;
186 ContentsEntry = RHS.ContentsEntry;
188 assert (RHS.Buffer.getPointer() == 0 && RHS.SourceLineCache == 0 &&
189 "Passed ContentCache object cannot own a buffer.");
191 NumLines = RHS.NumLines;
195 // Disable assignments.
196 ContentCache &operator=(const ContentCache& RHS);
199 /// FileInfo - Information about a FileID, basically just the logical file
200 /// that it represents and include stack information.
202 /// Each FileInfo has include stack information, indicating where it came
203 /// from. This information encodes the #include chain that a token was
204 /// expanded from. The main include file has an invalid IncludeLoc.
206 /// FileInfos contain a "ContentCache *", with the contents of the file.
209 /// IncludeLoc - The location of the #include that brought in this file.
210 /// This is an invalid SLOC for the main file (top of the #include chain).
211 unsigned IncludeLoc; // Really a SourceLocation
213 /// \brief Number of FileIDs (files and macros) that were created during
214 /// preprocessing of this #include, including this SLocEntry.
215 /// Zero means the preprocessor didn't provide such info for this SLocEntry.
216 unsigned NumCreatedFIDs;
218 /// Data - This contains the ContentCache* and the bits indicating the
219 /// characteristic of the file and whether it has #line info, all bitmangled
223 friend class clang::SourceManager;
224 friend class clang::ASTWriter;
225 friend class clang::ASTReader;
227 /// get - Return a FileInfo object.
228 static FileInfo get(SourceLocation IL, const ContentCache *Con,
229 CharacteristicKind FileCharacter) {
231 X.IncludeLoc = IL.getRawEncoding();
232 X.NumCreatedFIDs = 0;
233 X.Data = (uintptr_t)Con;
234 assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
235 assert((unsigned)FileCharacter < 4 && "invalid file character");
236 X.Data |= (unsigned)FileCharacter;
240 SourceLocation getIncludeLoc() const {
241 return SourceLocation::getFromRawEncoding(IncludeLoc);
243 const ContentCache* getContentCache() const {
244 return reinterpret_cast<const ContentCache*>(Data & ~7UL);
247 /// getCharacteristic - Return whether this is a system header or not.
248 CharacteristicKind getFileCharacteristic() const {
249 return (CharacteristicKind)(Data & 3);
252 /// hasLineDirectives - Return true if this FileID has #line directives in
254 bool hasLineDirectives() const { return (Data & 4) != 0; }
256 /// setHasLineDirectives - Set the flag that indicates that this FileID has
257 /// line table entries associated with it.
258 void setHasLineDirectives() {
263 /// ExpansionInfo - Each ExpansionInfo encodes the expansion location - where
264 /// the token was ultimately expanded, and the SpellingLoc - where the actual
265 /// character data for the token came from.
266 class ExpansionInfo {
267 // Really these are all SourceLocations.
269 /// SpellingLoc - Where the spelling for the token can be found.
270 unsigned SpellingLoc;
272 /// ExpansionLocStart/ExpansionLocEnd - In a macro expansion, these
273 /// indicate the start and end of the expansion. In object-like macros,
274 /// these will be the same. In a function-like macro expansion, the start
275 /// will be the identifier and the end will be the ')'. Finally, in
276 /// macro-argument instantitions, the end will be 'SourceLocation()', an
277 /// invalid location.
278 unsigned ExpansionLocStart, ExpansionLocEnd;
281 SourceLocation getSpellingLoc() const {
282 return SourceLocation::getFromRawEncoding(SpellingLoc);
284 SourceLocation getExpansionLocStart() const {
285 return SourceLocation::getFromRawEncoding(ExpansionLocStart);
287 SourceLocation getExpansionLocEnd() const {
288 SourceLocation EndLoc =
289 SourceLocation::getFromRawEncoding(ExpansionLocEnd);
290 return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
293 std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
294 return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
297 bool isMacroArgExpansion() const {
298 // Note that this needs to return false for default constructed objects.
299 return getExpansionLocStart().isValid() &&
300 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
303 /// create - Return a ExpansionInfo for an expansion. Start and End specify
304 /// the expansion range (where the macro is expanded), and SpellingLoc
305 /// specifies the spelling location (where the characters from the token
306 /// come from). All three can refer to normal File SLocs or expansion
308 static ExpansionInfo create(SourceLocation SpellingLoc,
309 SourceLocation Start, SourceLocation End) {
311 X.SpellingLoc = SpellingLoc.getRawEncoding();
312 X.ExpansionLocStart = Start.getRawEncoding();
313 X.ExpansionLocEnd = End.getRawEncoding();
317 /// createForMacroArg - Return a special ExpansionInfo for the expansion of
318 /// a macro argument into a function-like macro's body. ExpansionLoc
319 /// specifies the expansion location (where the macro is expanded). This
320 /// doesn't need to be a range because a macro is always expanded at
321 /// a macro parameter reference, and macro parameters are always exactly
322 /// one token. SpellingLoc specifies the spelling location (where the
323 /// characters from the token come from). ExpansionLoc and SpellingLoc can
324 /// both refer to normal File SLocs or expansion locations.
328 /// #define F(x) f(x)
332 /// When expanding '\c F(42)', the '\c x' would call this with an
333 /// SpellingLoc pointing at '\c 42' anad an ExpansionLoc pointing at its
334 /// location in the definition of '\c F'.
335 static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
336 SourceLocation ExpansionLoc) {
337 // We store an intentionally invalid source location for the end of the
338 // expansion range to mark that this is a macro argument ion rather than
340 return create(SpellingLoc, ExpansionLoc, SourceLocation());
344 /// SLocEntry - This is a discriminated union of FileInfo and
345 /// ExpansionInfo. SourceManager keeps an array of these objects, and
346 /// they are uniquely identified by the FileID datatype.
348 unsigned Offset; // low bit is set for expansion info.
351 ExpansionInfo Expansion;
354 unsigned getOffset() const { return Offset >> 1; }
356 bool isExpansion() const { return Offset & 1; }
357 bool isFile() const { return !isExpansion(); }
359 const FileInfo &getFile() const {
360 assert(isFile() && "Not a file SLocEntry!");
364 const ExpansionInfo &getExpansion() const {
365 assert(isExpansion() && "Not a macro expansion SLocEntry!");
369 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
371 E.Offset = Offset << 1;
376 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
378 E.Offset = (Offset << 1) | 1;
379 E.Expansion = Expansion;
383 } // end SrcMgr namespace.
385 /// \brief External source of source location entries.
386 class ExternalSLocEntrySource {
388 virtual ~ExternalSLocEntrySource();
390 /// \brief Read the source location entry with index ID, which will always be
393 /// \returns true if an error occurred that prevented the source-location
394 /// entry from being loaded.
395 virtual bool ReadSLocEntry(int ID) = 0;
399 /// IsBeforeInTranslationUnitCache - This class holds the cache used by
400 /// isBeforeInTranslationUnit. The cache structure is complex enough to be
401 /// worth breaking out of SourceManager.
402 class IsBeforeInTranslationUnitCache {
403 /// L/R QueryFID - These are the FID's of the cached query. If these match up
404 /// with a subsequent query, the result can be reused.
405 FileID LQueryFID, RQueryFID;
407 /// \brief True if LQueryFID was created before RQueryFID. This is used
408 /// to compare macro expansion locations.
409 bool IsLQFIDBeforeRQFID;
411 /// CommonFID - This is the file found in common between the two #include
412 /// traces. It is the nearest common ancestor of the #include tree.
415 /// L/R CommonOffset - This is the offset of the previous query in CommonFID.
416 /// Usually, this represents the location of the #include for QueryFID, but if
417 /// LQueryFID is a parent of RQueryFID (or vise versa) then these can be a
418 /// random token in the parent.
419 unsigned LCommonOffset, RCommonOffset;
422 /// isCacheValid - Return true if the currently cached values match up with
423 /// the specified LHS/RHS query. If not, we can't use the cache.
424 bool isCacheValid(FileID LHS, FileID RHS) const {
425 return LQueryFID == LHS && RQueryFID == RHS;
428 /// getCachedResult - If the cache is valid, compute the result given the
429 /// specified offsets in the LHS/RHS FID's.
430 bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
431 // If one of the query files is the common file, use the offset. Otherwise,
432 // use the #include loc in the common file.
433 if (LQueryFID != CommonFID) LOffset = LCommonOffset;
434 if (RQueryFID != CommonFID) ROffset = RCommonOffset;
436 // It is common for multiple macro expansions to be "included" from the same
437 // location (expansion location), in which case use the order of the FileIDs
438 // to determine which came first. This will also take care the case where
439 // one of the locations points at the inclusion/expansion point of the other
440 // in which case its FileID will come before the other.
441 if (LOffset == ROffset &&
442 (LQueryFID != CommonFID || RQueryFID != CommonFID))
443 return IsLQFIDBeforeRQFID;
445 return LOffset < ROffset;
448 // Set up a new query.
449 void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
453 IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
457 LQueryFID = RQueryFID = FileID();
458 IsLQFIDBeforeRQFID = false;
461 void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
462 unsigned rCommonOffset) {
463 CommonFID = commonFID;
464 LCommonOffset = lCommonOffset;
465 RCommonOffset = rCommonOffset;
470 /// \brief This class handles loading and caching of source files into memory.
472 /// This object owns the MemoryBuffer objects for all of the loaded
473 /// files and assigns unique FileID's for each unique #include chain.
475 /// The SourceManager can be queried for information about SourceLocation
476 /// objects, turning them into either spelling or expansion locations. Spelling
477 /// locations represent where the bytes corresponding to a token came from and
478 /// expansion locations represent where the location is in the user's view. In
479 /// the case of a macro expansion, for example, the spelling location indicates
480 /// where the expanded token came from and the expansion location specifies
481 /// where it was expanded.
482 class SourceManager : public llvm::RefCountedBase<SourceManager> {
483 /// \brief DiagnosticsEngine object.
484 DiagnosticsEngine &Diag;
486 FileManager &FileMgr;
488 mutable llvm::BumpPtrAllocator ContentCacheAlloc;
490 /// FileInfos - Memoized information about all of the files tracked by this
491 /// SourceManager. This set allows us to merge ContentCache entries based
492 /// on their FileEntry*. All ContentCache objects will thus have unique,
493 /// non-null, FileEntry pointers.
494 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
496 /// \brief True if the ContentCache for files that are overriden by other
497 /// files, should report the original file name. Defaults to true.
498 bool OverridenFilesKeepOriginalName;
500 /// \brief Files that have been overriden with the contents from another file.
501 llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
503 /// MemBufferInfos - Information about various memory buffers that we have
504 /// read in. All FileEntry* within the stored ContentCache objects are NULL,
505 /// as they do not refer to a file.
506 std::vector<SrcMgr::ContentCache*> MemBufferInfos;
508 /// \brief The table of SLocEntries that are local to this module.
510 /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
512 std::vector<SrcMgr::SLocEntry> LocalSLocEntryTable;
514 /// \brief The table of SLocEntries that are loaded from other modules.
516 /// Negative FileIDs are indexes into this table. To get from ID to an index,
518 std::vector<SrcMgr::SLocEntry> LoadedSLocEntryTable;
520 /// \brief The starting offset of the next local SLocEntry.
522 /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
523 unsigned NextLocalOffset;
525 /// \brief The starting offset of the latest batch of loaded SLocEntries.
527 /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
528 /// not have been loaded, so that value would be unknown.
529 unsigned CurrentLoadedOffset;
531 /// \brief The highest possible offset is 2^31-1, so CurrentLoadedOffset
533 static const unsigned MaxLoadedOffset = 1U << 31U;
535 /// \brief A bitmap that indicates whether the entries of LoadedSLocEntryTable
536 /// have already been loaded from the external source.
538 /// Same indexing as LoadedSLocEntryTable.
539 std::vector<bool> SLocEntryLoaded;
541 /// \brief An external source for source location entries.
542 ExternalSLocEntrySource *ExternalSLocEntries;
544 /// LastFileIDLookup - This is a one-entry cache to speed up getFileID.
545 /// LastFileIDLookup records the last FileID looked up or created, because it
546 /// is very common to look up many tokens from the same file.
547 mutable FileID LastFileIDLookup;
549 /// LineTable - This holds information for #line directives. It is referenced
550 /// by indices from SLocEntryTable.
551 LineTableInfo *LineTable;
553 /// LastLineNo - These ivars serve as a cache used in the getLineNumber
554 /// method which is used to speedup getLineNumber calls to nearby locations.
555 mutable FileID LastLineNoFileIDQuery;
556 mutable SrcMgr::ContentCache *LastLineNoContentCache;
557 mutable unsigned LastLineNoFilePos;
558 mutable unsigned LastLineNoResult;
560 /// MainFileID - The file ID for the main source file of the translation unit.
563 /// \brief The file ID for the precompiled preamble there is one.
564 FileID PreambleFileID;
566 // Statistics for -print-stats.
567 mutable unsigned NumLinearScans, NumBinaryProbes;
569 // Cache results for the isBeforeInTranslationUnit method.
570 mutable IsBeforeInTranslationUnitCache IsBeforeInTUCache;
572 // Cache for the "fake" buffer used for error-recovery purposes.
573 mutable llvm::MemoryBuffer *FakeBufferForRecovery;
575 /// \brief Lazily computed map of macro argument chunks to their expanded
577 typedef std::map<unsigned, SourceLocation> MacroArgsMap;
579 mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
581 // SourceManager doesn't support copy construction.
582 explicit SourceManager(const SourceManager&);
583 void operator=(const SourceManager&);
585 SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr);
588 void clearIDTables();
590 DiagnosticsEngine &getDiagnostics() const { return Diag; }
592 FileManager &getFileManager() const { return FileMgr; }
594 /// \brief Set true if the SourceManager should report the original file name
595 /// for contents of files that were overriden by other files.Defaults to true.
596 void setOverridenFilesKeepOriginalName(bool value) {
597 OverridenFilesKeepOriginalName = value;
600 /// createMainFileIDForMembuffer - Create the FileID for a memory buffer
601 /// that will represent the FileID for the main source. One example
602 /// of when this would be used is when the main source is read from STDIN.
603 FileID createMainFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer) {
604 assert(MainFileID.isInvalid() && "MainFileID already set!");
605 MainFileID = createFileIDForMemBuffer(Buffer);
609 //===--------------------------------------------------------------------===//
610 // MainFileID creation and querying methods.
611 //===--------------------------------------------------------------------===//
613 /// getMainFileID - Returns the FileID of the main source file.
614 FileID getMainFileID() const { return MainFileID; }
616 /// createMainFileID - Create the FileID for the main source file.
617 FileID createMainFileID(const FileEntry *SourceFile) {
618 assert(MainFileID.isInvalid() && "MainFileID already set!");
619 MainFileID = createFileID(SourceFile, SourceLocation(), SrcMgr::C_User);
623 /// \brief Set the file ID for the precompiled preamble.
624 void setPreambleFileID(FileID Preamble) {
625 assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
626 PreambleFileID = Preamble;
629 /// \brief Get the file ID for the precompiled preamble if there is one.
630 FileID getPreambleFileID() const { return PreambleFileID; }
632 //===--------------------------------------------------------------------===//
633 // Methods to create new FileID's and macro expansions.
634 //===--------------------------------------------------------------------===//
636 /// createFileID - Create a new FileID that represents the specified file
637 /// being #included from the specified IncludePosition. This translates NULL
638 /// into standard input.
639 FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
640 SrcMgr::CharacteristicKind FileCharacter,
641 int LoadedID = 0, unsigned LoadedOffset = 0) {
642 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
643 assert(IR && "getOrCreateContentCache() cannot return NULL");
644 return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
647 /// createFileIDForMemBuffer - Create a new FileID that represents the
648 /// specified memory buffer. This does no caching of the buffer and takes
649 /// ownership of the MemoryBuffer, so only pass a MemoryBuffer to this once.
650 FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
651 int LoadedID = 0, unsigned LoadedOffset = 0,
652 SourceLocation IncludeLoc = SourceLocation()) {
653 return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
654 SrcMgr::C_User, LoadedID, LoadedOffset);
657 /// createMacroArgExpansionLoc - Return a new SourceLocation that encodes the
658 /// fact that a token from SpellingLoc should actually be referenced from
659 /// ExpansionLoc, and that it represents the expansion of a macro argument
660 /// into the function-like macro body.
661 SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
662 SourceLocation ExpansionLoc,
665 /// createExpansionLoc - Return a new SourceLocation that encodes the fact
666 /// that a token from SpellingLoc should actually be referenced from
668 SourceLocation createExpansionLoc(SourceLocation Loc,
669 SourceLocation ExpansionLocStart,
670 SourceLocation ExpansionLocEnd,
673 unsigned LoadedOffset = 0);
675 /// \brief Retrieve the memory buffer associated with the given file.
677 /// \param Invalid If non-NULL, will be set \c true if an error
678 /// occurs while retrieving the memory buffer.
679 const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
682 /// \brief Override the contents of the given source file by providing an
683 /// already-allocated buffer.
685 /// \param SourceFile the source file whose contents will be overriden.
687 /// \param Buffer the memory buffer whose contents will be used as the
688 /// data in the given source file.
690 /// \param DoNotFree If true, then the buffer will not be freed when the
691 /// source manager is destroyed.
692 void overrideFileContents(const FileEntry *SourceFile,
693 const llvm::MemoryBuffer *Buffer,
694 bool DoNotFree = false);
696 /// \brief Override the the given source file with another one.
698 /// \param SourceFile the source file which will be overriden.
700 /// \param NewFile the file whose contents will be used as the
701 /// data instead of the contents of the given source file.
702 void overrideFileContents(const FileEntry *SourceFile,
703 const FileEntry *NewFile);
705 //===--------------------------------------------------------------------===//
706 // FileID manipulation methods.
707 //===--------------------------------------------------------------------===//
709 /// getBuffer - Return the buffer for the specified FileID. If there is an
710 /// error opening this buffer the first time, this manufactures a temporary
711 /// buffer and returns a non-empty error string.
712 const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
713 bool *Invalid = 0) const {
714 bool MyInvalid = false;
715 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
716 if (MyInvalid || !Entry.isFile()) {
720 return getFakeBufferForRecovery();
723 return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
727 const llvm::MemoryBuffer *getBuffer(FileID FID, bool *Invalid = 0) const {
728 bool MyInvalid = false;
729 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
730 if (MyInvalid || !Entry.isFile()) {
734 return getFakeBufferForRecovery();
737 return Entry.getFile().getContentCache()->getBuffer(Diag, *this,
742 /// getFileEntryForID - Returns the FileEntry record for the provided FileID.
743 const FileEntry *getFileEntryForID(FileID FID) const {
744 bool MyInvalid = false;
745 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
746 if (MyInvalid || !Entry.isFile())
749 return Entry.getFile().getContentCache()->OrigEntry;
752 /// Returns the FileEntry record for the provided SLocEntry.
753 const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
755 return sloc.getFile().getContentCache()->OrigEntry;
758 /// getBufferData - Return a StringRef to the source buffer data for the
759 /// specified FileID.
761 /// \param FID The file ID whose contents will be returned.
762 /// \param Invalid If non-NULL, will be set true if an error occurred.
763 StringRef getBufferData(FileID FID, bool *Invalid = 0) const;
765 /// \brief Get the number of FileIDs (files and macros) that were created
766 /// during preprocessing of \arg FID, including it.
767 unsigned getNumCreatedFIDsForFileID(FileID FID) const {
768 bool Invalid = false;
769 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
770 if (Invalid || !Entry.isFile())
773 return Entry.getFile().NumCreatedFIDs;
776 /// \brief Set the number of FileIDs (files and macros) that were created
777 /// during preprocessing of \arg FID, including it.
778 void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
779 bool Invalid = false;
780 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
781 if (Invalid || !Entry.isFile())
784 assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
785 const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
788 //===--------------------------------------------------------------------===//
789 // SourceLocation manipulation methods.
790 //===--------------------------------------------------------------------===//
792 /// getFileID - Return the FileID for a SourceLocation. This is a very
793 /// hot method that is used for all SourceManager queries that start with a
794 /// SourceLocation object. It is responsible for finding the entry in
795 /// SLocEntryTable which contains the specified location.
797 FileID getFileID(SourceLocation SpellingLoc) const {
798 unsigned SLocOffset = SpellingLoc.getOffset();
800 // If our one-entry cache covers this offset, just return it.
801 if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
802 return LastFileIDLookup;
804 return getFileIDSlow(SLocOffset);
807 /// getLocForStartOfFile - Return the source location corresponding to the
808 /// first byte of the specified file.
809 SourceLocation getLocForStartOfFile(FileID FID) const {
810 bool Invalid = false;
811 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
812 if (Invalid || !Entry.isFile())
813 return SourceLocation();
815 unsigned FileOffset = Entry.getOffset();
816 return SourceLocation::getFileLoc(FileOffset);
819 /// \brief Return the source location corresponding to the last byte of the
821 SourceLocation getLocForEndOfFile(FileID FID) const {
822 bool Invalid = false;
823 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
824 if (Invalid || !Entry.isFile())
825 return SourceLocation();
827 unsigned FileOffset = Entry.getOffset();
828 return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID) - 1);
831 /// \brief Returns the include location if \arg FID is a #include'd file
832 /// otherwise it returns an invalid location.
833 SourceLocation getIncludeLoc(FileID FID) const {
834 bool Invalid = false;
835 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
836 if (Invalid || !Entry.isFile())
837 return SourceLocation();
839 return Entry.getFile().getIncludeLoc();
842 /// getExpansionLoc - Given a SourceLocation object, return the expansion
843 /// location referenced by the ID.
844 SourceLocation getExpansionLoc(SourceLocation Loc) const {
845 // Handle the non-mapped case inline, defer to out of line code to handle
847 if (Loc.isFileID()) return Loc;
848 return getExpansionLocSlowCase(Loc);
851 /// \brief Given \arg Loc, if it is a macro location return the expansion
852 /// location or the spelling location, depending on if it comes from a
853 /// macro argument or not.
854 SourceLocation getFileLoc(SourceLocation Loc) const {
855 if (Loc.isFileID()) return Loc;
856 return getFileLocSlowCase(Loc);
859 /// getImmediateExpansionRange - Loc is required to be an expansion location.
860 /// Return the start/end of the expansion information.
861 std::pair<SourceLocation,SourceLocation>
862 getImmediateExpansionRange(SourceLocation Loc) const;
864 /// getExpansionRange - Given a SourceLocation object, return the range of
865 /// tokens covered by the expansion the ultimate file.
866 std::pair<SourceLocation,SourceLocation>
867 getExpansionRange(SourceLocation Loc) const;
870 /// getSpellingLoc - Given a SourceLocation object, return the spelling
871 /// location referenced by the ID. This is the place where the characters
872 /// that make up the lexed token can be found.
873 SourceLocation getSpellingLoc(SourceLocation Loc) const {
874 // Handle the non-mapped case inline, defer to out of line code to handle
876 if (Loc.isFileID()) return Loc;
877 return getSpellingLocSlowCase(Loc);
880 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
881 /// spelling location referenced by the ID. This is the first level down
882 /// towards the place where the characters that make up the lexed token can be
883 /// found. This should not generally be used by clients.
884 SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
886 /// getDecomposedLoc - Decompose the specified location into a raw FileID +
887 /// Offset pair. The first element is the FileID, the second is the
888 /// offset from the start of the buffer of the location.
889 std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
890 FileID FID = getFileID(Loc);
891 bool Invalid = false;
892 const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
894 return std::make_pair(FileID(), 0);
895 return std::make_pair(FID, Loc.getOffset()-E.getOffset());
898 /// getDecomposedExpansionLoc - Decompose the specified location into a raw
899 /// FileID + Offset pair. If the location is an expansion record, walk
900 /// through it until we find the final location expanded.
901 std::pair<FileID, unsigned>
902 getDecomposedExpansionLoc(SourceLocation Loc) const {
903 FileID FID = getFileID(Loc);
904 bool Invalid = false;
905 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
907 return std::make_pair(FileID(), 0);
909 unsigned Offset = Loc.getOffset()-E->getOffset();
911 return std::make_pair(FID, Offset);
913 return getDecomposedExpansionLocSlowCase(E);
916 /// getDecomposedSpellingLoc - Decompose the specified location into a raw
917 /// FileID + Offset pair. If the location is an expansion record, walk
918 /// through it until we find its spelling record.
919 std::pair<FileID, unsigned>
920 getDecomposedSpellingLoc(SourceLocation Loc) const {
921 FileID FID = getFileID(Loc);
922 bool Invalid = false;
923 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
925 return std::make_pair(FileID(), 0);
927 unsigned Offset = Loc.getOffset()-E->getOffset();
929 return std::make_pair(FID, Offset);
930 return getDecomposedSpellingLocSlowCase(E, Offset);
933 /// getFileOffset - This method returns the offset from the start
934 /// of the file that the specified SourceLocation represents. This is not very
935 /// meaningful for a macro ID.
936 unsigned getFileOffset(SourceLocation SpellingLoc) const {
937 return getDecomposedLoc(SpellingLoc).second;
940 /// isMacroArgExpansion - This method tests whether the given source location
941 /// represents a macro argument's expansion into the function-like macro
942 /// definition. Such source locations only appear inside of the expansion
943 /// locations representing where a particular function-like macro was
945 bool isMacroArgExpansion(SourceLocation Loc) const;
947 /// \brief Returns true if \arg Loc is inside the [\arg Start, +\arg Length)
948 /// chunk of the source location address space.
949 /// If it's true and \arg RelativeOffset is non-null, it will be set to the
950 /// relative offset of \arg Loc inside the chunk.
951 bool isInSLocAddrSpace(SourceLocation Loc,
952 SourceLocation Start, unsigned Length,
953 unsigned *RelativeOffset = 0) const {
954 assert(((Start.getOffset() < NextLocalOffset &&
955 Start.getOffset()+Length <= NextLocalOffset) ||
956 (Start.getOffset() >= CurrentLoadedOffset &&
957 Start.getOffset()+Length < MaxLoadedOffset)) &&
958 "Chunk is not valid SLoc address space");
959 unsigned LocOffs = Loc.getOffset();
960 unsigned BeginOffs = Start.getOffset();
961 unsigned EndOffs = BeginOffs + Length;
962 if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
964 *RelativeOffset = LocOffs - BeginOffs;
971 /// \brief Return true if both \arg LHS and \arg RHS are in the local source
972 /// location address space or the loaded one. If it's true and
973 /// \arg RelativeOffset is non-null, it will be set to the offset of \arg RHS
974 /// relative to \arg LHS.
975 bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
976 int *RelativeOffset) const {
977 unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
978 bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
979 bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
981 if (LHSLoaded == RHSLoaded) {
983 *RelativeOffset = RHSOffs - LHSOffs;
990 //===--------------------------------------------------------------------===//
991 // Queries about the code at a SourceLocation.
992 //===--------------------------------------------------------------------===//
994 /// getCharacterData - Return a pointer to the start of the specified location
995 /// in the appropriate spelling MemoryBuffer.
997 /// \param Invalid If non-NULL, will be set \c true if an error occurs.
998 const char *getCharacterData(SourceLocation SL, bool *Invalid = 0) const;
1000 /// getColumnNumber - Return the column # for the specified file position.
1001 /// This is significantly cheaper to compute than the line number. This
1002 /// returns zero if the column number isn't known. This may only be called
1003 /// on a file sloc, so you must choose a spelling or expansion location
1004 /// before calling this method.
1005 unsigned getColumnNumber(FileID FID, unsigned FilePos,
1006 bool *Invalid = 0) const;
1007 unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1008 unsigned getExpansionColumnNumber(SourceLocation Loc,
1009 bool *Invalid = 0) const;
1010 unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1013 /// getLineNumber - Given a SourceLocation, return the spelling line number
1014 /// for the position indicated. This requires building and caching a table of
1015 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1016 /// about to emit a diagnostic.
1017 unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = 0) const;
1018 unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1019 unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1020 unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1022 /// Return the filename or buffer identifier of the buffer the location is in.
1023 /// Note that this name does not respect #line directives. Use getPresumedLoc
1024 /// for normal clients.
1025 const char *getBufferName(SourceLocation Loc, bool *Invalid = 0) const;
1027 /// getFileCharacteristic - return the file characteristic of the specified
1028 /// source location, indicating whether this is a normal file, a system
1029 /// header, or an "implicit extern C" system header.
1031 /// This state can be modified with flags on GNU linemarker directives like:
1033 /// which changes all source locations in the current file after that to be
1034 /// considered to be from a system header.
1035 SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1037 /// getPresumedLoc - This method returns the "presumed" location of a
1038 /// SourceLocation specifies. A "presumed location" can be modified by #line
1039 /// or GNU line marker directives. This provides a view on the data that a
1040 /// user should see in diagnostics, for example.
1042 /// Note that a presumed location is always given as the expansion point of
1043 /// an expansion location, not at the spelling location.
1045 /// \returns The presumed location of the specified SourceLocation. If the
1046 /// presumed location cannot be calculate (e.g., because \p Loc is invalid
1047 /// or the file containing \p Loc has changed on disk), returns an invalid
1048 /// presumed location.
1049 PresumedLoc getPresumedLoc(SourceLocation Loc) const;
1051 /// isFromSameFile - Returns true if both SourceLocations correspond to
1053 bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1054 return getFileID(Loc1) == getFileID(Loc2);
1057 /// isFromMainFile - Returns true if the file of provided SourceLocation is
1059 bool isFromMainFile(SourceLocation Loc) const {
1060 return getFileID(Loc) == getMainFileID();
1063 /// isInSystemHeader - Returns if a SourceLocation is in a system header.
1064 bool isInSystemHeader(SourceLocation Loc) const {
1065 return getFileCharacteristic(Loc) != SrcMgr::C_User;
1068 /// isInExternCSystemHeader - Returns if a SourceLocation is in an "extern C"
1070 bool isInExternCSystemHeader(SourceLocation Loc) const {
1071 return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1074 /// \brief The size of the SLocEnty that \arg FID represents.
1075 unsigned getFileIDSize(FileID FID) const;
1077 /// \brief Given a specific FileID, returns true if \arg Loc is inside that
1078 /// FileID chunk and sets relative offset (offset of \arg Loc from beginning
1079 /// of FileID) to \arg relativeOffset.
1080 bool isInFileID(SourceLocation Loc, FileID FID,
1081 unsigned *RelativeOffset = 0) const {
1082 unsigned Offs = Loc.getOffset();
1083 if (isOffsetInFileID(FID, Offs)) {
1085 *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1092 //===--------------------------------------------------------------------===//
1093 // Line Table Manipulation Routines
1094 //===--------------------------------------------------------------------===//
1096 /// getLineTableFilenameID - Return the uniqued ID for the specified filename.
1098 unsigned getLineTableFilenameID(StringRef Str);
1100 /// AddLineNote - Add a line note to the line table for the FileID and offset
1101 /// specified by Loc. If FilenameID is -1, it is considered to be
1103 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
1104 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1105 bool IsFileEntry, bool IsFileExit,
1106 bool IsSystemHeader, bool IsExternCHeader);
1108 /// \brief Determine if the source manager has a line table.
1109 bool hasLineTable() const { return LineTable != 0; }
1111 /// \brief Retrieve the stored line table.
1112 LineTableInfo &getLineTable();
1114 //===--------------------------------------------------------------------===//
1115 // Queries for performance analysis.
1116 //===--------------------------------------------------------------------===//
1118 /// Return the total amount of physical memory allocated by the
1119 /// ContentCache allocator.
1120 size_t getContentCacheSize() const {
1121 return ContentCacheAlloc.getTotalMemory();
1124 struct MemoryBufferSizes {
1125 const size_t malloc_bytes;
1126 const size_t mmap_bytes;
1128 MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1129 : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1132 /// Return the amount of memory used by memory buffers, breaking down
1133 /// by heap-backed versus mmap'ed memory.
1134 MemoryBufferSizes getMemoryBufferSizes() const;
1136 // Return the amount of memory used for various side tables and
1137 // data structures in the SourceManager.
1138 size_t getDataStructureSizes() const;
1140 //===--------------------------------------------------------------------===//
1141 // Other miscellaneous methods.
1142 //===--------------------------------------------------------------------===//
1144 /// \brief Get the source location for the given file:line:col triplet.
1146 /// If the source file is included multiple times, the source location will
1147 /// be based upon the first inclusion.
1148 SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1149 unsigned Line, unsigned Col) const;
1151 /// \brief Get the FileID for the given file.
1153 /// If the source file is included multiple times, the FileID will be the
1154 /// first inclusion.
1155 FileID translateFile(const FileEntry *SourceFile) const;
1157 /// \brief Get the source location in \arg FID for the given line:col.
1158 /// Returns null location if \arg FID is not a file SLocEntry.
1159 SourceLocation translateLineCol(FileID FID,
1160 unsigned Line, unsigned Col) const;
1162 /// \brief If \arg Loc points inside a function macro argument, the returned
1163 /// location will be the macro location in which the argument was expanded.
1164 /// If a macro argument is used multiple times, the expanded location will
1165 /// be at the first expansion of the argument.
1169 /// Passing a file location pointing at 'foo', will yield a macro location
1170 /// where 'foo' was expanded into.
1171 SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1173 /// \brief Determines the order of 2 source locations in the translation unit.
1175 /// \returns true if LHS source location comes before RHS, false otherwise.
1176 bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1178 /// \brief Comparison function class.
1179 class LocBeforeThanCompare : public std::binary_function<SourceLocation,
1180 SourceLocation, bool> {
1184 explicit LocBeforeThanCompare(SourceManager &SM) : SM(SM) { }
1186 bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1187 return SM.isBeforeInTranslationUnit(LHS, RHS);
1191 /// \brief Determines the order of 2 source locations in the "source location
1193 bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1194 return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1197 /// \brief Determines the order of a source location and a source location
1198 /// offset in the "source location address space".
1200 /// Note that we always consider source locations loaded from
1201 bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1202 unsigned LHSOffset = LHS.getOffset();
1203 bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1204 bool RHSLoaded = RHS >= CurrentLoadedOffset;
1205 if (LHSLoaded == RHSLoaded)
1206 return LHSOffset < RHS;
1211 // Iterators over FileInfos.
1212 typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1213 ::const_iterator fileinfo_iterator;
1214 fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1215 fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1216 bool hasFileInfo(const FileEntry *File) const {
1217 return FileInfos.find(File) != FileInfos.end();
1220 /// PrintStats - Print statistics to stderr.
1222 void PrintStats() const;
1224 /// \brief Get the number of local SLocEntries we have.
1225 unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1227 /// \brief Get a local SLocEntry. This is exposed for indexing.
1228 const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index,
1229 bool *Invalid = 0) const {
1230 assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1231 return LocalSLocEntryTable[Index];
1234 /// \brief Get the number of loaded SLocEntries we have.
1235 unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1237 /// \brief Get a loaded SLocEntry. This is exposed for indexing.
1238 const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1239 bool *Invalid = 0) const {
1240 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1241 if (!SLocEntryLoaded[Index])
1242 ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2));
1243 return LoadedSLocEntryTable[Index];
1246 const SrcMgr::SLocEntry &getSLocEntry(FileID FID, bool *Invalid = 0) const {
1247 if (FID.ID == 0 || FID.ID == -1) {
1248 if (Invalid) *Invalid = true;
1249 return LocalSLocEntryTable[0];
1251 return getSLocEntryByID(FID.ID);
1254 unsigned getNextLocalOffset() const { return NextLocalOffset; }
1256 void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1257 assert(LoadedSLocEntryTable.empty() &&
1258 "Invalidating existing loaded entries");
1259 ExternalSLocEntries = Source;
1262 /// \brief Allocate a number of loaded SLocEntries, which will be actually
1263 /// loaded on demand from the external source.
1265 /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1266 /// in the global source view. The lowest ID and the base offset of the
1267 /// entries will be returned.
1268 std::pair<int, unsigned>
1269 AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1271 /// \brief Returns true if \arg Loc came from a PCH/Module.
1272 bool isLoadedSourceLocation(SourceLocation Loc) const {
1273 return Loc.getOffset() >= CurrentLoadedOffset;
1276 /// \brief Returns true if \arg Loc did not come from a PCH/Module.
1277 bool isLocalSourceLocation(SourceLocation Loc) const {
1278 return Loc.getOffset() < NextLocalOffset;
1281 /// \brief Returns true if \arg FID came from a PCH/Module.
1282 bool isLoadedFileID(FileID FID) const {
1283 assert(FID.ID != -1 && "Using FileID sentinel value");
1287 /// \brief Returns true if \arg FID did not come from a PCH/Module.
1288 bool isLocalFileID(FileID FID) const {
1289 return !isLoadedFileID(FID);
1293 const llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1295 /// \brief Get the entry with the given unwrapped FileID.
1296 const SrcMgr::SLocEntry &getSLocEntryByID(int ID) const {
1297 assert(ID != -1 && "Using FileID sentinel value");
1299 return getLoadedSLocEntryByID(ID);
1300 return getLocalSLocEntry(static_cast<unsigned>(ID));
1303 const SrcMgr::SLocEntry &getLoadedSLocEntryByID(int ID) const {
1304 return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2));
1307 /// createExpansionLoc - Implements the common elements of storing an
1308 /// expansion info struct into the SLocEntry table and producing a source
1309 /// location that refers to it.
1310 SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1313 unsigned LoadedOffset = 0);
1315 /// isOffsetInFileID - Return true if the specified FileID contains the
1316 /// specified SourceLocation offset. This is a very hot method.
1317 inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1318 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1319 // If the entry is after the offset, it can't contain it.
1320 if (SLocOffset < Entry.getOffset()) return false;
1322 // If this is the very last entry then it does.
1326 // If it is the last local entry, then it does if the location is local.
1327 if (static_cast<unsigned>(FID.ID+1) == LocalSLocEntryTable.size()) {
1328 return SLocOffset < NextLocalOffset;
1331 // Otherwise, the entry after it has to not include it. This works for both
1332 // local and loaded entries.
1333 return SLocOffset < getSLocEntry(FileID::get(FID.ID+1)).getOffset();
1336 /// createFileID - Create a new fileID for the specified ContentCache and
1337 /// include position. This works regardless of whether the ContentCache
1338 /// corresponds to a file or some other input source.
1339 FileID createFileID(const SrcMgr::ContentCache* File,
1340 SourceLocation IncludePos,
1341 SrcMgr::CharacteristicKind DirCharacter,
1342 int LoadedID, unsigned LoadedOffset);
1344 const SrcMgr::ContentCache *
1345 getOrCreateContentCache(const FileEntry *SourceFile);
1347 /// createMemBufferContentCache - Create a new ContentCache for the specified
1349 const SrcMgr::ContentCache*
1350 createMemBufferContentCache(const llvm::MemoryBuffer *Buf);
1352 FileID getFileIDSlow(unsigned SLocOffset) const;
1353 FileID getFileIDLocal(unsigned SLocOffset) const;
1354 FileID getFileIDLoaded(unsigned SLocOffset) const;
1356 SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1357 SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1358 SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1360 std::pair<FileID, unsigned>
1361 getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1362 std::pair<FileID, unsigned>
1363 getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1364 unsigned Offset) const;
1365 void computeMacroArgsCache(MacroArgsMap *&MacroArgsCache, FileID FID) const;
1367 friend class ASTReader;
1368 friend class ASTWriter;
1372 } // end namespace clang