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 //===----------------------------------------------------------------------===//
11 /// \brief Defines the SourceManager interface.
13 /// There are three different types of locations in a file: a spelling
14 /// location, an expansion location, and a presumed location.
16 /// Given an example of:
18 /// #define min(x, y) x < y ? x : y
21 /// and then later on a use of min:
27 /// The expansion location is the line in the source code where the macro
28 /// was expanded (the return statement), the spelling location is the
29 /// location in the source where the macro was originally defined,
30 /// and the presumed location is where the line directive states that
31 /// the line is 17, or any other line.
33 //===----------------------------------------------------------------------===//
35 #ifndef LLVM_CLANG_SOURCEMANAGER_H
36 #define LLVM_CLANG_SOURCEMANAGER_H
38 #include "clang/Basic/LLVM.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/DataTypes.h"
43 #include "llvm/ADT/PointerIntPair.h"
44 #include "llvm/ADT/PointerUnion.h"
45 #include "llvm/ADT/IntrusiveRefCntPtr.h"
46 #include "llvm/ADT/OwningPtr.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/DenseSet.h"
49 #include "llvm/Support/MemoryBuffer.h"
56 class DiagnosticsEngine;
66 /// \brief Public enums and private classes that are part of the
67 /// SourceManager implementation.
70 /// \brief Indicates whether a file or directory holds normal user code,
71 /// system code, or system code which is implicitly 'extern "C"' in C++ mode.
73 /// Entire directories can be tagged with this (this is maintained by
74 /// DirectoryLookup and friends) as can specific FileInfos when a \#pragma
75 /// system_header is seen or in various other cases.
77 enum CharacteristicKind {
78 C_User, C_System, C_ExternCSystem
81 /// \brief One instance of this struct is kept for every file loaded or used.
83 /// This object owns the MemoryBuffer object.
86 /// \brief Whether the buffer is invalid.
88 /// \brief Whether the buffer should not be freed on destruction.
92 /// \brief The actual buffer containing the characters from the input
95 /// This is owned by the ContentCache object. The bits indicate
96 /// whether the buffer is invalid.
97 mutable llvm::PointerIntPair<const llvm::MemoryBuffer *, 2> Buffer;
100 /// \brief Reference to the file entry representing this ContentCache.
102 /// This reference does not own the FileEntry object.
104 /// It is possible for this to be NULL if the ContentCache encapsulates
105 /// an imaginary text buffer.
106 const FileEntry *OrigEntry;
108 /// \brief References the file which the contents were actually loaded from.
110 /// Can be different from 'Entry' if we overridden the contents of one file
111 /// with the contents of another file.
112 const FileEntry *ContentsEntry;
114 /// \brief A bump pointer allocated array of offsets for each source line.
116 /// This is lazily computed. This is owned by the SourceManager
117 /// BumpPointerAllocator object.
118 unsigned *SourceLineCache;
120 /// \brief The number of lines in this ContentCache.
122 /// This is only valid if SourceLineCache is non-null.
123 unsigned NumLines : 31;
125 /// \brief Indicates whether the buffer itself was provided to override
126 /// the actual file contents.
128 /// When true, the original entry may be a virtual file that does not
130 unsigned BufferOverridden : 1;
132 ContentCache(const FileEntry *Ent = 0)
133 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent),
134 SourceLineCache(0), NumLines(0), BufferOverridden(false) {}
136 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
137 : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt),
138 SourceLineCache(0), NumLines(0), BufferOverridden(false) {}
142 /// The copy ctor does not allow copies where source object has either
143 /// a non-NULL Buffer or SourceLineCache. Ownership of allocated memory
144 /// is not transferred, so this is a logical error.
145 ContentCache(const ContentCache &RHS)
146 : Buffer(0, false), SourceLineCache(0), BufferOverridden(false)
148 OrigEntry = RHS.OrigEntry;
149 ContentsEntry = RHS.ContentsEntry;
151 assert (RHS.Buffer.getPointer() == 0 && RHS.SourceLineCache == 0 &&
152 "Passed ContentCache object cannot own a buffer.");
154 NumLines = RHS.NumLines;
157 /// \brief Returns the memory buffer for the associated content.
159 /// \param Diag Object through which diagnostics will be emitted if the
160 /// buffer cannot be retrieved.
162 /// \param Loc If specified, is the location that invalid file diagnostics
163 /// will be emitted at.
165 /// \param Invalid If non-NULL, will be set \c true if an error occurred.
166 const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
167 const SourceManager &SM,
168 SourceLocation Loc = SourceLocation(),
169 bool *Invalid = 0) const;
171 /// \brief Returns the size of the content encapsulated by this
174 /// This can be the size of the source file or the size of an
175 /// arbitrary scratch buffer. If the ContentCache encapsulates a source
176 /// file this size is retrieved from the file's FileEntry.
177 unsigned getSize() const;
179 /// \brief Returns the number of bytes actually mapped for this
182 /// This can be 0 if the MemBuffer was not actually expanded.
183 unsigned getSizeBytesMapped() const;
185 /// Returns the kind of memory used to back the memory buffer for
186 /// this content cache. This is used for performance analysis.
187 llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
189 void setBuffer(const llvm::MemoryBuffer *B) {
190 assert(!Buffer.getPointer() && "MemoryBuffer already set.");
191 Buffer.setPointer(B);
192 Buffer.setInt(false);
195 /// \brief Get the underlying buffer, returning NULL if the buffer is not
197 const llvm::MemoryBuffer *getRawBuffer() const {
198 return Buffer.getPointer();
201 /// \brief Replace the existing buffer (which will be deleted)
202 /// with the given buffer.
203 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
205 /// \brief Determine whether the buffer itself is invalid.
206 bool isBufferInvalid() const {
207 return Buffer.getInt() & InvalidFlag;
210 /// \brief Determine whether the buffer should be freed.
211 bool shouldFreeBuffer() const {
212 return (Buffer.getInt() & DoNotFreeFlag) == 0;
216 // Disable assignments.
217 ContentCache &operator=(const ContentCache& RHS);
220 /// \brief Information about a FileID, basically just the logical file
221 /// that it represents and include stack information.
223 /// Each FileInfo has include stack information, indicating where it came
224 /// from. This information encodes the \#include chain that a token was
225 /// expanded from. The main include file has an invalid IncludeLoc.
227 /// FileInfos contain a "ContentCache *", with the contents of the file.
230 /// \brief The location of the \#include that brought in this file.
232 /// This is an invalid SLOC for the main file (top of the \#include chain).
233 unsigned IncludeLoc; // Really a SourceLocation
235 /// \brief Number of FileIDs (files and macros) that were created during
236 /// preprocessing of this \#include, including this SLocEntry.
238 /// Zero means the preprocessor didn't provide such info for this SLocEntry.
239 unsigned NumCreatedFIDs;
241 /// \brief Contains the ContentCache* and the bits indicating the
242 /// characteristic of the file and whether it has \#line info, all
243 /// bitmangled together.
246 friend class clang::SourceManager;
247 friend class clang::ASTWriter;
248 friend class clang::ASTReader;
250 /// \brief Return a FileInfo object.
251 static FileInfo get(SourceLocation IL, const ContentCache *Con,
252 CharacteristicKind FileCharacter) {
254 X.IncludeLoc = IL.getRawEncoding();
255 X.NumCreatedFIDs = 0;
256 X.Data = (uintptr_t)Con;
257 assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
258 assert((unsigned)FileCharacter < 4 && "invalid file character");
259 X.Data |= (unsigned)FileCharacter;
263 SourceLocation getIncludeLoc() const {
264 return SourceLocation::getFromRawEncoding(IncludeLoc);
266 const ContentCache* getContentCache() const {
267 return reinterpret_cast<const ContentCache*>(Data & ~7UL);
270 /// \brief Return whether this is a system header or not.
271 CharacteristicKind getFileCharacteristic() const {
272 return (CharacteristicKind)(Data & 3);
275 /// \brief Return true if this FileID has \#line directives in it.
276 bool hasLineDirectives() const { return (Data & 4) != 0; }
278 /// \brief Set the flag that indicates that this FileID has
279 /// line table entries associated with it.
280 void setHasLineDirectives() {
285 /// \brief Each ExpansionInfo encodes the expansion location - where
286 /// the token was ultimately expanded, and the SpellingLoc - where the actual
287 /// character data for the token came from.
288 class ExpansionInfo {
289 // Really these are all SourceLocations.
291 /// \brief Where the spelling for the token can be found.
292 unsigned SpellingLoc;
294 /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
295 /// indicate the start and end of the expansion. In object-like macros,
296 /// they will be the same. In a function-like macro expansion, the start
297 /// will be the identifier and the end will be the ')'. Finally, in
298 /// macro-argument instantiations, the end will be 'SourceLocation()', an
299 /// invalid location.
300 unsigned ExpansionLocStart, ExpansionLocEnd;
303 SourceLocation getSpellingLoc() const {
304 return SourceLocation::getFromRawEncoding(SpellingLoc);
306 SourceLocation getExpansionLocStart() const {
307 return SourceLocation::getFromRawEncoding(ExpansionLocStart);
309 SourceLocation getExpansionLocEnd() const {
310 SourceLocation EndLoc =
311 SourceLocation::getFromRawEncoding(ExpansionLocEnd);
312 return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
315 std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
316 return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
319 bool isMacroArgExpansion() const {
320 // Note that this needs to return false for default constructed objects.
321 return getExpansionLocStart().isValid() &&
322 SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
325 bool isFunctionMacroExpansion() const {
326 return getExpansionLocStart().isValid() &&
327 getExpansionLocStart() != getExpansionLocEnd();
330 /// \brief Return a ExpansionInfo for an expansion.
332 /// Start and End specify the expansion range (where the macro is
333 /// expanded), and SpellingLoc specifies the spelling location (where
334 /// the characters from the token come from). All three can refer to
335 /// normal File SLocs or expansion locations.
336 static ExpansionInfo create(SourceLocation SpellingLoc,
337 SourceLocation Start, SourceLocation End) {
339 X.SpellingLoc = SpellingLoc.getRawEncoding();
340 X.ExpansionLocStart = Start.getRawEncoding();
341 X.ExpansionLocEnd = End.getRawEncoding();
345 /// \brief Return a special ExpansionInfo for the expansion of
346 /// a macro argument into a function-like macro's body.
348 /// ExpansionLoc specifies the expansion location (where the macro is
349 /// expanded). This doesn't need to be a range because a macro is always
350 /// expanded at a macro parameter reference, and macro parameters are
351 /// always exactly one token. SpellingLoc specifies the spelling location
352 /// (where the characters from the token come from). ExpansionLoc and
353 /// SpellingLoc can both refer to normal File SLocs or expansion locations.
357 /// #define F(x) f(x)
361 /// When expanding '\c F(42)', the '\c x' would call this with an
362 /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
363 /// location in the definition of '\c F'.
364 static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
365 SourceLocation ExpansionLoc) {
366 // We store an intentionally invalid source location for the end of the
367 // expansion range to mark that this is a macro argument ion rather than
369 return create(SpellingLoc, ExpansionLoc, SourceLocation());
373 /// \brief This is a discriminated union of FileInfo and ExpansionInfo.
375 /// SourceManager keeps an array of these objects, and they are uniquely
376 /// identified by the FileID datatype.
378 unsigned Offset; // low bit is set for expansion info.
381 ExpansionInfo Expansion;
384 unsigned getOffset() const { return Offset >> 1; }
386 bool isExpansion() const { return Offset & 1; }
387 bool isFile() const { return !isExpansion(); }
389 const FileInfo &getFile() const {
390 assert(isFile() && "Not a file SLocEntry!");
394 const ExpansionInfo &getExpansion() const {
395 assert(isExpansion() && "Not a macro expansion SLocEntry!");
399 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
401 E.Offset = Offset << 1;
406 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
408 E.Offset = (Offset << 1) | 1;
409 E.Expansion = Expansion;
413 } // end SrcMgr namespace.
415 /// \brief External source of source location entries.
416 class ExternalSLocEntrySource {
418 virtual ~ExternalSLocEntrySource();
420 /// \brief Read the source location entry with index ID, which will always be
423 /// \returns true if an error occurred that prevented the source-location
424 /// entry from being loaded.
425 virtual bool ReadSLocEntry(int ID) = 0;
429 /// \brief Holds the cache used by isBeforeInTranslationUnit.
431 /// The cache structure is complex enough to be worth breaking out of
433 class IsBeforeInTranslationUnitCache {
434 /// \brief The FileID's of the cached query.
436 /// If these match up with a subsequent query, the result can be reused.
437 FileID LQueryFID, RQueryFID;
439 /// \brief True if LQueryFID was created before RQueryFID.
441 /// This is used to compare macro expansion locations.
442 bool IsLQFIDBeforeRQFID;
444 /// \brief The file found in common between the two \#include traces, i.e.,
445 /// the nearest common ancestor of the \#include tree.
448 /// \brief The offset of the previous query in CommonFID.
450 /// Usually, this represents the location of the \#include for QueryFID, but
451 /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
452 /// random token in the parent.
453 unsigned LCommonOffset, RCommonOffset;
456 /// \brief Return true if the currently cached values match up with
457 /// the specified LHS/RHS query.
459 /// If not, we can't use the cache.
460 bool isCacheValid(FileID LHS, FileID RHS) const {
461 return LQueryFID == LHS && RQueryFID == RHS;
464 /// \brief If the cache is valid, compute the result given the
465 /// specified offsets in the LHS/RHS FileID's.
466 bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
467 // If one of the query files is the common file, use the offset. Otherwise,
468 // use the #include loc in the common file.
469 if (LQueryFID != CommonFID) LOffset = LCommonOffset;
470 if (RQueryFID != CommonFID) ROffset = RCommonOffset;
472 // It is common for multiple macro expansions to be "included" from the same
473 // location (expansion location), in which case use the order of the FileIDs
474 // to determine which came first. This will also take care the case where
475 // one of the locations points at the inclusion/expansion point of the other
476 // in which case its FileID will come before the other.
477 if (LOffset == ROffset)
478 return IsLQFIDBeforeRQFID;
480 return LOffset < ROffset;
483 /// \brief Set up a new query.
484 void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
488 IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
492 LQueryFID = RQueryFID = FileID();
493 IsLQFIDBeforeRQFID = false;
496 void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
497 unsigned rCommonOffset) {
498 CommonFID = commonFID;
499 LCommonOffset = lCommonOffset;
500 RCommonOffset = rCommonOffset;
505 /// \brief This class handles loading and caching of source files into memory.
507 /// This object owns the MemoryBuffer objects for all of the loaded
508 /// files and assigns unique FileID's for each unique \#include chain.
510 /// The SourceManager can be queried for information about SourceLocation
511 /// objects, turning them into either spelling or expansion locations. Spelling
512 /// locations represent where the bytes corresponding to a token came from and
513 /// expansion locations represent where the location is in the user's view. In
514 /// the case of a macro expansion, for example, the spelling location indicates
515 /// where the expanded token came from and the expansion location specifies
516 /// where it was expanded.
517 class SourceManager : public RefCountedBase<SourceManager> {
518 /// \brief DiagnosticsEngine object.
519 DiagnosticsEngine &Diag;
521 FileManager &FileMgr;
523 mutable llvm::BumpPtrAllocator ContentCacheAlloc;
525 /// \brief Memoized information about all of the files tracked by this
528 /// This map allows us to merge ContentCache entries based
529 /// on their FileEntry*. All ContentCache objects will thus have unique,
530 /// non-null, FileEntry pointers.
531 llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
533 /// \brief True if the ContentCache for files that are overriden by other
534 /// files, should report the original file name. Defaults to true.
535 bool OverridenFilesKeepOriginalName;
537 struct OverriddenFilesInfoTy {
538 /// \brief Files that have been overriden with the contents from another
540 llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
541 /// \brief Files that were overridden with a memory buffer.
542 llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
545 /// \brief Lazily create the object keeping overridden files info, since
546 /// it is uncommonly used.
547 OwningPtr<OverriddenFilesInfoTy> OverriddenFilesInfo;
549 OverriddenFilesInfoTy &getOverriddenFilesInfo() {
550 if (!OverriddenFilesInfo)
551 OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
552 return *OverriddenFilesInfo;
555 /// \brief Information about various memory buffers that we have read in.
557 /// All FileEntry* within the stored ContentCache objects are NULL,
558 /// as they do not refer to a file.
559 std::vector<SrcMgr::ContentCache*> MemBufferInfos;
561 /// \brief The table of SLocEntries that are local to this module.
563 /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
565 std::vector<SrcMgr::SLocEntry> LocalSLocEntryTable;
567 /// \brief The table of SLocEntries that are loaded from other modules.
569 /// Negative FileIDs are indexes into this table. To get from ID to an index,
571 mutable std::vector<SrcMgr::SLocEntry> LoadedSLocEntryTable;
573 /// \brief The starting offset of the next local SLocEntry.
575 /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
576 unsigned NextLocalOffset;
578 /// \brief The starting offset of the latest batch of loaded SLocEntries.
580 /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
581 /// not have been loaded, so that value would be unknown.
582 unsigned CurrentLoadedOffset;
584 /// \brief The highest possible offset is 2^31-1, so CurrentLoadedOffset
586 static const unsigned MaxLoadedOffset = 1U << 31U;
588 /// \brief A bitmap that indicates whether the entries of LoadedSLocEntryTable
589 /// have already been loaded from the external source.
591 /// Same indexing as LoadedSLocEntryTable.
592 std::vector<bool> SLocEntryLoaded;
594 /// \brief An external source for source location entries.
595 ExternalSLocEntrySource *ExternalSLocEntries;
597 /// \brief A one-entry cache to speed up getFileID.
599 /// LastFileIDLookup records the last FileID looked up or created, because it
600 /// is very common to look up many tokens from the same file.
601 mutable FileID LastFileIDLookup;
603 /// \brief Holds information for \#line directives.
605 /// This is referenced by indices from SLocEntryTable.
606 LineTableInfo *LineTable;
608 /// \brief These ivars serve as a cache used in the getLineNumber
609 /// method which is used to speedup getLineNumber calls to nearby locations.
610 mutable FileID LastLineNoFileIDQuery;
611 mutable SrcMgr::ContentCache *LastLineNoContentCache;
612 mutable unsigned LastLineNoFilePos;
613 mutable unsigned LastLineNoResult;
615 /// \brief The file ID for the main source file of the translation unit.
618 /// \brief The file ID for the precompiled preamble there is one.
619 FileID PreambleFileID;
621 // Statistics for -print-stats.
622 mutable unsigned NumLinearScans, NumBinaryProbes;
624 // Cache results for the isBeforeInTranslationUnit method.
625 mutable IsBeforeInTranslationUnitCache IsBeforeInTUCache;
627 // Cache for the "fake" buffer used for error-recovery purposes.
628 mutable llvm::MemoryBuffer *FakeBufferForRecovery;
630 mutable SrcMgr::ContentCache *FakeContentCacheForRecovery;
632 /// \brief Lazily computed map of macro argument chunks to their expanded
634 typedef std::map<unsigned, SourceLocation> MacroArgsMap;
636 mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
638 // SourceManager doesn't support copy construction.
639 explicit SourceManager(const SourceManager&);
640 void operator=(const SourceManager&);
642 SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr);
645 void clearIDTables();
647 DiagnosticsEngine &getDiagnostics() const { return Diag; }
649 FileManager &getFileManager() const { return FileMgr; }
651 /// \brief Set true if the SourceManager should report the original file name
652 /// for contents of files that were overriden by other files.Defaults to true.
653 void setOverridenFilesKeepOriginalName(bool value) {
654 OverridenFilesKeepOriginalName = value;
657 /// \brief Create the FileID for a memory buffer that will represent the
658 /// FileID for the main source.
660 /// One example of when this would be used is when the main source is read
662 FileID createMainFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer) {
663 assert(MainFileID.isInvalid() && "MainFileID already set!");
664 MainFileID = createFileIDForMemBuffer(Buffer);
668 //===--------------------------------------------------------------------===//
669 // MainFileID creation and querying methods.
670 //===--------------------------------------------------------------------===//
672 /// \brief Returns the FileID of the main source file.
673 FileID getMainFileID() const { return MainFileID; }
675 /// \brief Create the FileID for the main source file.
676 FileID createMainFileID(const FileEntry *SourceFile,
677 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User) {
678 assert(MainFileID.isInvalid() && "MainFileID already set!");
679 MainFileID = createFileID(SourceFile, SourceLocation(), Kind);
683 /// \brief Set the file ID for the main source file.
684 void setMainFileID(FileID FID) {
685 assert(MainFileID.isInvalid() && "MainFileID already set!");
689 /// \brief Set the file ID for the precompiled preamble.
690 void setPreambleFileID(FileID Preamble) {
691 assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
692 PreambleFileID = Preamble;
695 /// \brief Get the file ID for the precompiled preamble if there is one.
696 FileID getPreambleFileID() const { return PreambleFileID; }
698 //===--------------------------------------------------------------------===//
699 // Methods to create new FileID's and macro expansions.
700 //===--------------------------------------------------------------------===//
702 /// \brief Create a new FileID that represents the specified file
703 /// being \#included from the specified IncludePosition.
705 /// This translates NULL into standard input.
706 FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
707 SrcMgr::CharacteristicKind FileCharacter,
708 int LoadedID = 0, unsigned LoadedOffset = 0) {
709 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
710 assert(IR && "getOrCreateContentCache() cannot return NULL");
711 return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
714 /// \brief Create a new FileID that represents the specified memory buffer.
716 /// This does no caching of the buffer and takes ownership of the
717 /// MemoryBuffer, so only pass a MemoryBuffer to this once.
718 FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
719 int LoadedID = 0, unsigned LoadedOffset = 0,
720 SourceLocation IncludeLoc = SourceLocation()) {
721 return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
722 SrcMgr::C_User, LoadedID, LoadedOffset);
725 /// \brief Return a new SourceLocation that encodes the
726 /// fact that a token from SpellingLoc should actually be referenced from
727 /// ExpansionLoc, and that it represents the expansion of a macro argument
728 /// into the function-like macro body.
729 SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
730 SourceLocation ExpansionLoc,
733 /// \brief Return a new SourceLocation that encodes the fact
734 /// that a token from SpellingLoc should actually be referenced from
736 SourceLocation createExpansionLoc(SourceLocation Loc,
737 SourceLocation ExpansionLocStart,
738 SourceLocation ExpansionLocEnd,
741 unsigned LoadedOffset = 0);
743 /// \brief Retrieve the memory buffer associated with the given file.
745 /// \param Invalid If non-NULL, will be set \c true if an error
746 /// occurs while retrieving the memory buffer.
747 const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
750 /// \brief Override the contents of the given source file by providing an
751 /// already-allocated buffer.
753 /// \param SourceFile the source file whose contents will be overriden.
755 /// \param Buffer the memory buffer whose contents will be used as the
756 /// data in the given source file.
758 /// \param DoNotFree If true, then the buffer will not be freed when the
759 /// source manager is destroyed.
760 void overrideFileContents(const FileEntry *SourceFile,
761 const llvm::MemoryBuffer *Buffer,
762 bool DoNotFree = false);
764 /// \brief Override the the given source file with another one.
766 /// \param SourceFile the source file which will be overriden.
768 /// \param NewFile the file whose contents will be used as the
769 /// data instead of the contents of the given source file.
770 void overrideFileContents(const FileEntry *SourceFile,
771 const FileEntry *NewFile);
773 /// \brief Returns true if the file contents have been overridden.
774 bool isFileOverridden(const FileEntry *File) {
775 if (OverriddenFilesInfo) {
776 if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
778 if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
779 OverriddenFilesInfo->OverriddenFiles.end())
785 /// \brief Disable overridding the contents of a file, previously enabled
786 /// with #overrideFileContents.
788 /// This should be called before parsing has begun.
789 void disableFileContentsOverride(const FileEntry *File);
791 //===--------------------------------------------------------------------===//
792 // FileID manipulation methods.
793 //===--------------------------------------------------------------------===//
795 /// \brief Return the buffer for the specified FileID.
797 /// If there is an error opening this buffer the first time, this
798 /// manufactures a temporary buffer and returns a non-empty error string.
799 const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
800 bool *Invalid = 0) const {
801 bool MyInvalid = false;
802 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
803 if (MyInvalid || !Entry.isFile()) {
807 return getFakeBufferForRecovery();
810 return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
814 const llvm::MemoryBuffer *getBuffer(FileID FID, bool *Invalid = 0) const {
815 bool MyInvalid = false;
816 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
817 if (MyInvalid || !Entry.isFile()) {
821 return getFakeBufferForRecovery();
824 return Entry.getFile().getContentCache()->getBuffer(Diag, *this,
829 /// \brief Returns the FileEntry record for the provided FileID.
830 const FileEntry *getFileEntryForID(FileID FID) const {
831 bool MyInvalid = false;
832 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
833 if (MyInvalid || !Entry.isFile())
836 const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
839 return Content->OrigEntry;
842 /// \brief Returns the FileEntry record for the provided SLocEntry.
843 const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
845 const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
848 return Content->OrigEntry;
851 /// \brief Return a StringRef to the source buffer data for the
852 /// specified FileID.
854 /// \param FID The file ID whose contents will be returned.
855 /// \param Invalid If non-NULL, will be set true if an error occurred.
856 StringRef getBufferData(FileID FID, bool *Invalid = 0) const;
858 /// \brief Get the number of FileIDs (files and macros) that were created
859 /// during preprocessing of \p FID, including it.
860 unsigned getNumCreatedFIDsForFileID(FileID FID) const {
861 bool Invalid = false;
862 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
863 if (Invalid || !Entry.isFile())
866 return Entry.getFile().NumCreatedFIDs;
869 /// \brief Set the number of FileIDs (files and macros) that were created
870 /// during preprocessing of \p FID, including it.
871 void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
872 bool Invalid = false;
873 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
874 if (Invalid || !Entry.isFile())
877 assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
878 const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
881 //===--------------------------------------------------------------------===//
882 // SourceLocation manipulation methods.
883 //===--------------------------------------------------------------------===//
885 /// \brief Return the FileID for a SourceLocation.
887 /// This is a very hot method that is used for all SourceManager queries
888 /// that start with a SourceLocation object. It is responsible for finding
889 /// the entry in SLocEntryTable which contains the specified location.
891 FileID getFileID(SourceLocation SpellingLoc) const {
892 unsigned SLocOffset = SpellingLoc.getOffset();
894 // If our one-entry cache covers this offset, just return it.
895 if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
896 return LastFileIDLookup;
898 return getFileIDSlow(SLocOffset);
901 /// \brief Return the filename of the file containing a SourceLocation.
902 StringRef getFilename(SourceLocation SpellingLoc) const {
903 if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
908 /// \brief Return the source location corresponding to the first byte of
909 /// the specified file.
910 SourceLocation getLocForStartOfFile(FileID FID) const {
911 bool Invalid = false;
912 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
913 if (Invalid || !Entry.isFile())
914 return SourceLocation();
916 unsigned FileOffset = Entry.getOffset();
917 return SourceLocation::getFileLoc(FileOffset);
920 /// \brief Return the source location corresponding to the last byte of the
922 SourceLocation getLocForEndOfFile(FileID FID) const {
923 bool Invalid = false;
924 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
925 if (Invalid || !Entry.isFile())
926 return SourceLocation();
928 unsigned FileOffset = Entry.getOffset();
929 return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID) - 1);
932 /// \brief Returns the include location if \p FID is a \#include'd file
933 /// otherwise it returns an invalid location.
934 SourceLocation getIncludeLoc(FileID FID) const {
935 bool Invalid = false;
936 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
937 if (Invalid || !Entry.isFile())
938 return SourceLocation();
940 return Entry.getFile().getIncludeLoc();
943 /// \brief Given a SourceLocation object \p Loc, return the expansion
944 /// location referenced by the ID.
945 SourceLocation getExpansionLoc(SourceLocation Loc) const {
946 // Handle the non-mapped case inline, defer to out of line code to handle
948 if (Loc.isFileID()) return Loc;
949 return getExpansionLocSlowCase(Loc);
952 /// \brief Given \p Loc, if it is a macro location return the expansion
953 /// location or the spelling location, depending on if it comes from a
954 /// macro argument or not.
955 SourceLocation getFileLoc(SourceLocation Loc) const {
956 if (Loc.isFileID()) return Loc;
957 return getFileLocSlowCase(Loc);
960 /// \brief Return the start/end of the expansion information for an
961 /// expansion location.
963 /// \pre \p Loc is required to be an expansion location.
964 std::pair<SourceLocation,SourceLocation>
965 getImmediateExpansionRange(SourceLocation Loc) const;
967 /// \brief Given a SourceLocation object, return the range of
968 /// tokens covered by the expansion the ultimate file.
969 std::pair<SourceLocation,SourceLocation>
970 getExpansionRange(SourceLocation Loc) const;
973 /// \brief Given a SourceLocation object, return the spelling
974 /// location referenced by the ID.
976 /// This is the place where the characters that make up the lexed token
978 SourceLocation getSpellingLoc(SourceLocation Loc) const {
979 // Handle the non-mapped case inline, defer to out of line code to handle
981 if (Loc.isFileID()) return Loc;
982 return getSpellingLocSlowCase(Loc);
985 /// \brief Given a SourceLocation object, return the spelling location
986 /// referenced by the ID.
988 /// This is the first level down towards the place where the characters
989 /// that make up the lexed token can be found. This should not generally
990 /// be used by clients.
991 SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
993 /// \brief Decompose the specified location into a raw FileID + Offset pair.
995 /// The first element is the FileID, the second is the offset from the
996 /// start of the buffer of the location.
997 std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
998 FileID FID = getFileID(Loc);
999 bool Invalid = false;
1000 const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
1002 return std::make_pair(FileID(), 0);
1003 return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1006 /// \brief Decompose the specified location into a raw FileID + Offset pair.
1008 /// If the location is an expansion record, walk through it until we find
1009 /// the final location expanded.
1010 std::pair<FileID, unsigned>
1011 getDecomposedExpansionLoc(SourceLocation Loc) const {
1012 FileID FID = getFileID(Loc);
1013 bool Invalid = false;
1014 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1016 return std::make_pair(FileID(), 0);
1018 unsigned Offset = Loc.getOffset()-E->getOffset();
1020 return std::make_pair(FID, Offset);
1022 return getDecomposedExpansionLocSlowCase(E);
1025 /// \brief Decompose the specified location into a raw FileID + Offset pair.
1027 /// If the location is an expansion record, walk through it until we find
1028 /// its spelling record.
1029 std::pair<FileID, unsigned>
1030 getDecomposedSpellingLoc(SourceLocation Loc) const {
1031 FileID FID = getFileID(Loc);
1032 bool Invalid = false;
1033 const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1035 return std::make_pair(FileID(), 0);
1037 unsigned Offset = Loc.getOffset()-E->getOffset();
1039 return std::make_pair(FID, Offset);
1040 return getDecomposedSpellingLocSlowCase(E, Offset);
1043 /// \brief Returns the offset from the start of the file that the
1044 /// specified SourceLocation represents.
1046 /// This is not very meaningful for a macro ID.
1047 unsigned getFileOffset(SourceLocation SpellingLoc) const {
1048 return getDecomposedLoc(SpellingLoc).second;
1051 /// \brief Tests whether the given source location represents a macro
1052 /// argument's expansion into the function-like macro definition.
1054 /// Such source locations only appear inside of the expansion
1055 /// locations representing where a particular function-like macro was
1057 bool isMacroArgExpansion(SourceLocation Loc) const;
1059 /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
1060 /// chunk of the source location address space.
1062 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1063 /// relative offset of \p Loc inside the chunk.
1064 bool isInSLocAddrSpace(SourceLocation Loc,
1065 SourceLocation Start, unsigned Length,
1066 unsigned *RelativeOffset = 0) const {
1067 assert(((Start.getOffset() < NextLocalOffset &&
1068 Start.getOffset()+Length <= NextLocalOffset) ||
1069 (Start.getOffset() >= CurrentLoadedOffset &&
1070 Start.getOffset()+Length < MaxLoadedOffset)) &&
1071 "Chunk is not valid SLoc address space");
1072 unsigned LocOffs = Loc.getOffset();
1073 unsigned BeginOffs = Start.getOffset();
1074 unsigned EndOffs = BeginOffs + Length;
1075 if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1077 *RelativeOffset = LocOffs - BeginOffs;
1084 /// \brief Return true if both \p LHS and \p RHS are in the local source
1085 /// location address space or the loaded one.
1087 /// If it's true and \p RelativeOffset is non-null, it will be set to the
1088 /// offset of \p RHS relative to \p LHS.
1089 bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
1090 int *RelativeOffset) const {
1091 unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1092 bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1093 bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1095 if (LHSLoaded == RHSLoaded) {
1097 *RelativeOffset = RHSOffs - LHSOffs;
1104 //===--------------------------------------------------------------------===//
1105 // Queries about the code at a SourceLocation.
1106 //===--------------------------------------------------------------------===//
1108 /// \brief Return a pointer to the start of the specified location
1109 /// in the appropriate spelling MemoryBuffer.
1111 /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1112 const char *getCharacterData(SourceLocation SL, bool *Invalid = 0) const;
1114 /// \brief Return the column # for the specified file position.
1116 /// This is significantly cheaper to compute than the line number. This
1117 /// returns zero if the column number isn't known. This may only be called
1118 /// on a file sloc, so you must choose a spelling or expansion location
1119 /// before calling this method.
1120 unsigned getColumnNumber(FileID FID, unsigned FilePos,
1121 bool *Invalid = 0) const;
1122 unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1123 unsigned getExpansionColumnNumber(SourceLocation Loc,
1124 bool *Invalid = 0) const;
1125 unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1128 /// \brief Given a SourceLocation, return the spelling line number
1129 /// for the position indicated.
1131 /// This requires building and caching a table of line offsets for the
1132 /// MemoryBuffer, so this is not cheap: use only when about to emit a
1134 unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = 0) const;
1135 unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1136 unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1137 unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1139 /// \brief Return the filename or buffer identifier of the buffer the
1142 /// Note that this name does not respect \#line directives. Use
1143 /// getPresumedLoc for normal clients.
1144 const char *getBufferName(SourceLocation Loc, bool *Invalid = 0) const;
1146 /// \brief Return the file characteristic of the specified source
1147 /// location, indicating whether this is a normal file, a system
1148 /// header, or an "implicit extern C" system header.
1150 /// This state can be modified with flags on GNU linemarker directives like:
1154 /// which changes all source locations in the current file after that to be
1155 /// considered to be from a system header.
1156 SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1158 /// \brief Returns the "presumed" location of a SourceLocation specifies.
1160 /// A "presumed location" can be modified by \#line or GNU line marker
1161 /// directives. This provides a view on the data that a user should see
1162 /// in diagnostics, for example.
1164 /// Note that a presumed location is always given as the expansion point of
1165 /// an expansion location, not at the spelling location.
1167 /// \returns The presumed location of the specified SourceLocation. If the
1168 /// presumed location cannot be calculate (e.g., because \p Loc is invalid
1169 /// or the file containing \p Loc has changed on disk), returns an invalid
1170 /// presumed location.
1171 PresumedLoc getPresumedLoc(SourceLocation Loc) const;
1173 /// \brief Returns true if both SourceLocations correspond to the same file.
1174 bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1175 return getFileID(Loc1) == getFileID(Loc2);
1178 /// \brief Returns true if the file of provided SourceLocation is the main
1180 bool isFromMainFile(SourceLocation Loc) const {
1181 return getFileID(Loc) == getMainFileID();
1184 /// \brief Returns if a SourceLocation is in a system header.
1185 bool isInSystemHeader(SourceLocation Loc) const {
1186 return getFileCharacteristic(Loc) != SrcMgr::C_User;
1189 /// \brief Returns if a SourceLocation is in an "extern C" system header.
1190 bool isInExternCSystemHeader(SourceLocation Loc) const {
1191 return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1194 /// \brief Returns whether \p Loc is expanded from a macro in a system header.
1195 bool isInSystemMacro(SourceLocation loc) {
1196 return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
1199 /// \brief The size of the SLocEnty that \p FID represents.
1200 unsigned getFileIDSize(FileID FID) const;
1202 /// \brief Given a specific FileID, returns true if \p Loc is inside that
1203 /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1204 /// of FileID) to \p relativeOffset.
1205 bool isInFileID(SourceLocation Loc, FileID FID,
1206 unsigned *RelativeOffset = 0) const {
1207 unsigned Offs = Loc.getOffset();
1208 if (isOffsetInFileID(FID, Offs)) {
1210 *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1217 //===--------------------------------------------------------------------===//
1218 // Line Table Manipulation Routines
1219 //===--------------------------------------------------------------------===//
1221 /// \brief Return the uniqued ID for the specified filename.
1223 unsigned getLineTableFilenameID(StringRef Str);
1225 /// \brief Add a line note to the line table for the FileID and offset
1226 /// specified by Loc.
1228 /// If FilenameID is -1, it is considered to be unspecified.
1229 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
1230 void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1231 bool IsFileEntry, bool IsFileExit,
1232 bool IsSystemHeader, bool IsExternCHeader);
1234 /// \brief Determine if the source manager has a line table.
1235 bool hasLineTable() const { return LineTable != 0; }
1237 /// \brief Retrieve the stored line table.
1238 LineTableInfo &getLineTable();
1240 //===--------------------------------------------------------------------===//
1241 // Queries for performance analysis.
1242 //===--------------------------------------------------------------------===//
1244 /// \brief Return the total amount of physical memory allocated by the
1245 /// ContentCache allocator.
1246 size_t getContentCacheSize() const {
1247 return ContentCacheAlloc.getTotalMemory();
1250 struct MemoryBufferSizes {
1251 const size_t malloc_bytes;
1252 const size_t mmap_bytes;
1254 MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1255 : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1258 /// \brief Return the amount of memory used by memory buffers, breaking down
1259 /// by heap-backed versus mmap'ed memory.
1260 MemoryBufferSizes getMemoryBufferSizes() const;
1262 /// \brief Return the amount of memory used for various side tables and
1263 /// data structures in the SourceManager.
1264 size_t getDataStructureSizes() const;
1266 //===--------------------------------------------------------------------===//
1267 // Other miscellaneous methods.
1268 //===--------------------------------------------------------------------===//
1270 /// \brief Get the source location for the given file:line:col triplet.
1272 /// If the source file is included multiple times, the source location will
1273 /// be based upon the first inclusion.
1274 SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1275 unsigned Line, unsigned Col) const;
1277 /// \brief Get the FileID for the given file.
1279 /// If the source file is included multiple times, the FileID will be the
1280 /// first inclusion.
1281 FileID translateFile(const FileEntry *SourceFile) const;
1283 /// \brief Get the source location in \p FID for the given line:col.
1284 /// Returns null location if \p FID is not a file SLocEntry.
1285 SourceLocation translateLineCol(FileID FID,
1286 unsigned Line, unsigned Col) const;
1288 /// \brief If \p Loc points inside a function macro argument, the returned
1289 /// location will be the macro location in which the argument was expanded.
1290 /// If a macro argument is used multiple times, the expanded location will
1291 /// be at the first expansion of the argument.
1295 /// Passing a file location pointing at 'foo', will yield a macro location
1296 /// where 'foo' was expanded into.
1297 SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1299 /// \brief Determines the order of 2 source locations in the translation unit.
1301 /// \returns true if LHS source location comes before RHS, false otherwise.
1302 bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1304 /// \brief Determines the order of 2 source locations in the "source location
1306 bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1307 return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1310 /// \brief Determines the order of a source location and a source location
1311 /// offset in the "source location address space".
1313 /// Note that we always consider source locations loaded from
1314 bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1315 unsigned LHSOffset = LHS.getOffset();
1316 bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1317 bool RHSLoaded = RHS >= CurrentLoadedOffset;
1318 if (LHSLoaded == RHSLoaded)
1319 return LHSOffset < RHS;
1324 // Iterators over FileInfos.
1325 typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1326 ::const_iterator fileinfo_iterator;
1327 fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1328 fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1329 bool hasFileInfo(const FileEntry *File) const {
1330 return FileInfos.find(File) != FileInfos.end();
1333 /// \brief Print statistics to stderr.
1335 void PrintStats() const;
1337 /// \brief Get the number of local SLocEntries we have.
1338 unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1340 /// \brief Get a local SLocEntry. This is exposed for indexing.
1341 const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index,
1342 bool *Invalid = 0) const {
1343 assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1344 return LocalSLocEntryTable[Index];
1347 /// \brief Get the number of loaded SLocEntries we have.
1348 unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1350 /// \brief Get a loaded SLocEntry. This is exposed for indexing.
1351 const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1352 bool *Invalid = 0) const {
1353 assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1354 if (SLocEntryLoaded[Index])
1355 return LoadedSLocEntryTable[Index];
1356 return loadSLocEntry(Index, Invalid);
1359 const SrcMgr::SLocEntry &getSLocEntry(FileID FID, bool *Invalid = 0) const {
1360 if (FID.ID == 0 || FID.ID == -1) {
1361 if (Invalid) *Invalid = true;
1362 return LocalSLocEntryTable[0];
1364 return getSLocEntryByID(FID.ID);
1367 unsigned getNextLocalOffset() const { return NextLocalOffset; }
1369 void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1370 assert(LoadedSLocEntryTable.empty() &&
1371 "Invalidating existing loaded entries");
1372 ExternalSLocEntries = Source;
1375 /// \brief Allocate a number of loaded SLocEntries, which will be actually
1376 /// loaded on demand from the external source.
1378 /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1379 /// in the global source view. The lowest ID and the base offset of the
1380 /// entries will be returned.
1381 std::pair<int, unsigned>
1382 AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1384 /// \brief Returns true if \p Loc came from a PCH/Module.
1385 bool isLoadedSourceLocation(SourceLocation Loc) const {
1386 return Loc.getOffset() >= CurrentLoadedOffset;
1389 /// \brief Returns true if \p Loc did not come from a PCH/Module.
1390 bool isLocalSourceLocation(SourceLocation Loc) const {
1391 return Loc.getOffset() < NextLocalOffset;
1394 /// \brief Returns true if \p FID came from a PCH/Module.
1395 bool isLoadedFileID(FileID FID) const {
1396 assert(FID.ID != -1 && "Using FileID sentinel value");
1400 /// \brief Returns true if \p FID did not come from a PCH/Module.
1401 bool isLocalFileID(FileID FID) const {
1402 return !isLoadedFileID(FID);
1405 /// Get a presumed location suitable for displaying in a diagnostic message,
1406 /// taking into account macro arguments and expansions.
1407 PresumedLoc getPresumedLocForDisplay(SourceLocation Loc) const {
1408 // This is a condensed form of the algorithm used by emitCaretDiagnostic to
1409 // walk to the top of the macro call stack.
1410 while (Loc.isMacroID()) {
1411 Loc = skipToMacroArgExpansion(Loc);
1412 Loc = getImmediateMacroCallerLoc(Loc);
1415 return getPresumedLoc(Loc);
1418 /// Look through spelling locations for a macro argument expansion, and if
1419 /// found skip to it so that we can trace the argument rather than the macros
1420 /// in which that argument is used. If no macro argument expansion is found,
1421 /// don't skip anything and return the starting location.
1422 SourceLocation skipToMacroArgExpansion(SourceLocation StartLoc) const {
1423 for (SourceLocation L = StartLoc; L.isMacroID();
1424 L = getImmediateSpellingLoc(L)) {
1425 if (isMacroArgExpansion(L))
1428 // Otherwise just return initial location, there's nothing to skip.
1432 /// Gets the location of the immediate macro caller, one level up the stack
1433 /// toward the initial macro typed into the source.
1434 SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1435 if (!Loc.isMacroID()) return Loc;
1437 // When we have the location of (part of) an expanded parameter, its
1438 // spelling location points to the argument as typed into the macro call,
1439 // and therefore is used to locate the macro caller.
1440 if (isMacroArgExpansion(Loc))
1441 return getImmediateSpellingLoc(Loc);
1443 // Otherwise, the caller of the macro is located where this macro is
1444 // expanded (while the spelling is part of the macro definition).
1445 return getImmediateExpansionRange(Loc).first;
1448 /// Gets the location of the immediate macro callee, one level down the stack
1449 /// toward the leaf macro.
1450 SourceLocation getImmediateMacroCalleeLoc(SourceLocation Loc) const {
1451 if (!Loc.isMacroID()) return Loc;
1453 // When we have the location of (part of) an expanded parameter, its
1454 // expansion location points to the unexpanded parameter reference within
1455 // the macro definition (or callee).
1456 if (isMacroArgExpansion(Loc))
1457 return getImmediateExpansionRange(Loc).first;
1459 // Otherwise, the callee of the macro is located where this location was
1460 // spelled inside the macro definition.
1461 return getImmediateSpellingLoc(Loc);
1465 const llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1466 const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1468 const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1470 /// \brief Get the entry with the given unwrapped FileID.
1471 const SrcMgr::SLocEntry &getSLocEntryByID(int ID) const {
1472 assert(ID != -1 && "Using FileID sentinel value");
1474 return getLoadedSLocEntryByID(ID);
1475 return getLocalSLocEntry(static_cast<unsigned>(ID));
1478 const SrcMgr::SLocEntry &getLoadedSLocEntryByID(int ID,
1479 bool *Invalid = 0) const {
1480 return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1483 /// Implements the common elements of storing an expansion info struct into
1484 /// the SLocEntry table and producing a source location that refers to it.
1485 SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1488 unsigned LoadedOffset = 0);
1490 /// \brief Return true if the specified FileID contains the
1491 /// specified SourceLocation offset. This is a very hot method.
1492 inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1493 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1494 // If the entry is after the offset, it can't contain it.
1495 if (SLocOffset < Entry.getOffset()) return false;
1497 // If this is the very last entry then it does.
1501 // If it is the last local entry, then it does if the location is local.
1502 if (static_cast<unsigned>(FID.ID+1) == LocalSLocEntryTable.size()) {
1503 return SLocOffset < NextLocalOffset;
1506 // Otherwise, the entry after it has to not include it. This works for both
1507 // local and loaded entries.
1508 return SLocOffset < getSLocEntry(FileID::get(FID.ID+1)).getOffset();
1511 /// \brief Create a new fileID for the specified ContentCache and
1512 /// include position.
1514 /// This works regardless of whether the ContentCache corresponds to a
1515 /// file or some other input source.
1516 FileID createFileID(const SrcMgr::ContentCache* File,
1517 SourceLocation IncludePos,
1518 SrcMgr::CharacteristicKind DirCharacter,
1519 int LoadedID, unsigned LoadedOffset);
1521 const SrcMgr::ContentCache *
1522 getOrCreateContentCache(const FileEntry *SourceFile);
1524 /// \brief Create a new ContentCache for the specified memory buffer.
1525 const SrcMgr::ContentCache*
1526 createMemBufferContentCache(const llvm::MemoryBuffer *Buf);
1528 FileID getFileIDSlow(unsigned SLocOffset) const;
1529 FileID getFileIDLocal(unsigned SLocOffset) const;
1530 FileID getFileIDLoaded(unsigned SLocOffset) const;
1532 SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1533 SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1534 SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1536 std::pair<FileID, unsigned>
1537 getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1538 std::pair<FileID, unsigned>
1539 getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1540 unsigned Offset) const;
1541 void computeMacroArgsCache(MacroArgsMap *&MacroArgsCache, FileID FID) const;
1543 friend class ASTReader;
1544 friend class ASTWriter;
1547 /// \brief Comparison function object.
1548 template<typename T>
1549 class BeforeThanCompare;
1551 /// \brief Compare two source locations.
1553 class BeforeThanCompare<SourceLocation> {
1557 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1559 bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1560 return SM.isBeforeInTranslationUnit(LHS, RHS);
1564 /// \brief Compare two non-overlapping source ranges.
1566 class BeforeThanCompare<SourceRange> {
1570 explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1572 bool operator()(SourceRange LHS, SourceRange RHS) {
1573 return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1577 } // end namespace clang