SourceManager.h revision c50c6ff49aa3648ae031349de6f09439f52425f0
1//===--- SourceManager.h - Track and cache source files ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief Defines the SourceManager interface.
12///
13/// There are three different types of locations in a %file: a spelling
14/// location, an expansion location, and a presumed location.
15///
16/// Given an example of:
17/// \code
18/// #define min(x, y) x < y ? x : y
19/// \endcode
20///
21/// and then later on a use of min:
22/// \code
23/// #line 17
24/// return min(a, b);
25/// \endcode
26///
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.
32///
33//===----------------------------------------------------------------------===//
34
35#ifndef LLVM_CLANG_SOURCEMANAGER_H
36#define LLVM_CLANG_SOURCEMANAGER_H
37
38#include "clang/Basic/FileManager.h"
39#include "clang/Basic/LLVM.h"
40#include "clang/Basic/SourceLocation.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/DenseSet.h"
44#include "llvm/ADT/IntrusiveRefCntPtr.h"
45#include "llvm/ADT/OwningPtr.h"
46#include "llvm/ADT/PointerIntPair.h"
47#include "llvm/ADT/PointerUnion.h"
48#include "llvm/Support/Allocator.h"
49#include "llvm/Support/DataTypes.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include <cassert>
52#include <map>
53#include <vector>
54
55namespace clang {
56
57class DiagnosticsEngine;
58class SourceManager;
59class FileManager;
60class FileEntry;
61class LineTableInfo;
62class LangOptions;
63class ASTWriter;
64class ASTReader;
65
66/// \brief Public enums and private classes that are part of the
67/// SourceManager implementation.
68///
69namespace SrcMgr {
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.
72  ///
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.
76  ///
77  enum CharacteristicKind {
78    C_User, C_System, C_ExternCSystem
79  };
80
81  /// \brief One instance of this struct is kept for every file loaded or used.
82  ///
83  /// This object owns the MemoryBuffer object.
84  class ContentCache {
85    enum CCFlags {
86      /// \brief Whether the buffer is invalid.
87      InvalidFlag = 0x01,
88      /// \brief Whether the buffer should not be freed on destruction.
89      DoNotFreeFlag = 0x02
90    };
91
92    /// \brief The actual buffer containing the characters from the input
93    /// file.
94    ///
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;
98
99  public:
100    /// \brief Reference to the file entry representing this ContentCache.
101    ///
102    /// This reference does not own the FileEntry object.
103    ///
104    /// It is possible for this to be NULL if the ContentCache encapsulates
105    /// an imaginary text buffer.
106    const FileEntry *OrigEntry;
107
108    /// \brief References the file which the contents were actually loaded from.
109    ///
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;
113
114    /// \brief A bump pointer allocated array of offsets for each source line.
115    ///
116    /// This is lazily computed.  This is owned by the SourceManager
117    /// BumpPointerAllocator object.
118    unsigned *SourceLineCache;
119
120    /// \brief The number of lines in this ContentCache.
121    ///
122    /// This is only valid if SourceLineCache is non-null.
123    unsigned NumLines : 31;
124
125    /// \brief Indicates whether the buffer itself was provided to override
126    /// the actual file contents.
127    ///
128    /// When true, the original entry may be a virtual file that does not
129    /// exist.
130    unsigned BufferOverridden : 1;
131
132    /// \brief True if this content cache was initially created for a source
133    /// file considered as a system one.
134    unsigned IsSystemFile : 1;
135
136    ContentCache(const FileEntry *Ent = 0)
137      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent),
138        SourceLineCache(0), NumLines(0), BufferOverridden(false),
139        IsSystemFile(false) {}
140
141    ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
142      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt),
143        SourceLineCache(0), NumLines(0), BufferOverridden(false),
144        IsSystemFile(false) {}
145
146    ~ContentCache();
147
148    /// The copy ctor does not allow copies where source object has either
149    /// a non-NULL Buffer or SourceLineCache.  Ownership of allocated memory
150    /// is not transferred, so this is a logical error.
151    ContentCache(const ContentCache &RHS)
152      : Buffer(0, false), SourceLineCache(0), BufferOverridden(false),
153        IsSystemFile(false)
154    {
155      OrigEntry = RHS.OrigEntry;
156      ContentsEntry = RHS.ContentsEntry;
157
158      assert (RHS.Buffer.getPointer() == 0 && RHS.SourceLineCache == 0 &&
159              "Passed ContentCache object cannot own a buffer.");
160
161      NumLines = RHS.NumLines;
162    }
163
164    /// \brief Returns the memory buffer for the associated content.
165    ///
166    /// \param Diag Object through which diagnostics will be emitted if the
167    ///   buffer cannot be retrieved.
168    ///
169    /// \param Loc If specified, is the location that invalid file diagnostics
170    ///   will be emitted at.
171    ///
172    /// \param Invalid If non-NULL, will be set \c true if an error occurred.
173    const llvm::MemoryBuffer *getBuffer(DiagnosticsEngine &Diag,
174                                        const SourceManager &SM,
175                                        SourceLocation Loc = SourceLocation(),
176                                        bool *Invalid = 0) const;
177
178    /// \brief Returns the size of the content encapsulated by this
179    /// ContentCache.
180    ///
181    /// This can be the size of the source file or the size of an
182    /// arbitrary scratch buffer.  If the ContentCache encapsulates a source
183    /// file this size is retrieved from the file's FileEntry.
184    unsigned getSize() const;
185
186    /// \brief Returns the number of bytes actually mapped for this
187    /// ContentCache.
188    ///
189    /// This can be 0 if the MemBuffer was not actually expanded.
190    unsigned getSizeBytesMapped() const;
191
192    /// Returns the kind of memory used to back the memory buffer for
193    /// this content cache.  This is used for performance analysis.
194    llvm::MemoryBuffer::BufferKind getMemoryBufferKind() const;
195
196    void setBuffer(const llvm::MemoryBuffer *B) {
197      assert(!Buffer.getPointer() && "MemoryBuffer already set.");
198      Buffer.setPointer(B);
199      Buffer.setInt(false);
200    }
201
202    /// \brief Get the underlying buffer, returning NULL if the buffer is not
203    /// yet available.
204    const llvm::MemoryBuffer *getRawBuffer() const {
205      return Buffer.getPointer();
206    }
207
208    /// \brief Replace the existing buffer (which will be deleted)
209    /// with the given buffer.
210    void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
211
212    /// \brief Determine whether the buffer itself is invalid.
213    bool isBufferInvalid() const {
214      return Buffer.getInt() & InvalidFlag;
215    }
216
217    /// \brief Determine whether the buffer should be freed.
218    bool shouldFreeBuffer() const {
219      return (Buffer.getInt() & DoNotFreeFlag) == 0;
220    }
221
222  private:
223    // Disable assignments.
224    ContentCache &operator=(const ContentCache& RHS) LLVM_DELETED_FUNCTION;
225  };
226
227  /// \brief Information about a FileID, basically just the logical file
228  /// that it represents and include stack information.
229  ///
230  /// Each FileInfo has include stack information, indicating where it came
231  /// from. This information encodes the \#include chain that a token was
232  /// expanded from. The main include file has an invalid IncludeLoc.
233  ///
234  /// FileInfos contain a "ContentCache *", with the contents of the file.
235  ///
236  class FileInfo {
237    /// \brief The location of the \#include that brought in this file.
238    ///
239    /// This is an invalid SLOC for the main file (top of the \#include chain).
240    unsigned IncludeLoc;  // Really a SourceLocation
241
242    /// \brief Number of FileIDs (files and macros) that were created during
243    /// preprocessing of this \#include, including this SLocEntry.
244    ///
245    /// Zero means the preprocessor didn't provide such info for this SLocEntry.
246    unsigned NumCreatedFIDs;
247
248    /// \brief Contains the ContentCache* and the bits indicating the
249    /// characteristic of the file and whether it has \#line info, all
250    /// bitmangled together.
251    uintptr_t Data;
252
253    friend class clang::SourceManager;
254    friend class clang::ASTWriter;
255    friend class clang::ASTReader;
256  public:
257    /// \brief Return a FileInfo object.
258    static FileInfo get(SourceLocation IL, const ContentCache *Con,
259                        CharacteristicKind FileCharacter) {
260      FileInfo X;
261      X.IncludeLoc = IL.getRawEncoding();
262      X.NumCreatedFIDs = 0;
263      X.Data = (uintptr_t)Con;
264      assert((X.Data & 7) == 0 &&"ContentCache pointer insufficiently aligned");
265      assert((unsigned)FileCharacter < 4 && "invalid file character");
266      X.Data |= (unsigned)FileCharacter;
267      return X;
268    }
269
270    SourceLocation getIncludeLoc() const {
271      return SourceLocation::getFromRawEncoding(IncludeLoc);
272    }
273    const ContentCache* getContentCache() const {
274      return reinterpret_cast<const ContentCache*>(Data & ~uintptr_t(7));
275    }
276
277    /// \brief Return whether this is a system header or not.
278    CharacteristicKind getFileCharacteristic() const {
279      return (CharacteristicKind)(Data & 3);
280    }
281
282    /// \brief Return true if this FileID has \#line directives in it.
283    bool hasLineDirectives() const { return (Data & 4) != 0; }
284
285    /// \brief Set the flag that indicates that this FileID has
286    /// line table entries associated with it.
287    void setHasLineDirectives() {
288      Data |= 4;
289    }
290  };
291
292  /// \brief Each ExpansionInfo encodes the expansion location - where
293  /// the token was ultimately expanded, and the SpellingLoc - where the actual
294  /// character data for the token came from.
295  class ExpansionInfo {
296    // Really these are all SourceLocations.
297
298    /// \brief Where the spelling for the token can be found.
299    unsigned SpellingLoc;
300
301    /// In a macro expansion, ExpansionLocStart and ExpansionLocEnd
302    /// indicate the start and end of the expansion. In object-like macros,
303    /// they will be the same. In a function-like macro expansion, the start
304    /// will be the identifier and the end will be the ')'. Finally, in
305    /// macro-argument instantiations, the end will be 'SourceLocation()', an
306    /// invalid location.
307    unsigned ExpansionLocStart, ExpansionLocEnd;
308
309  public:
310    SourceLocation getSpellingLoc() const {
311      return SourceLocation::getFromRawEncoding(SpellingLoc);
312    }
313    SourceLocation getExpansionLocStart() const {
314      return SourceLocation::getFromRawEncoding(ExpansionLocStart);
315    }
316    SourceLocation getExpansionLocEnd() const {
317      SourceLocation EndLoc =
318        SourceLocation::getFromRawEncoding(ExpansionLocEnd);
319      return EndLoc.isInvalid() ? getExpansionLocStart() : EndLoc;
320    }
321
322    std::pair<SourceLocation,SourceLocation> getExpansionLocRange() const {
323      return std::make_pair(getExpansionLocStart(), getExpansionLocEnd());
324    }
325
326    bool isMacroArgExpansion() const {
327      // Note that this needs to return false for default constructed objects.
328      return getExpansionLocStart().isValid() &&
329        SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
330    }
331
332    bool isMacroBodyExpansion() const {
333      return getExpansionLocStart().isValid() &&
334        SourceLocation::getFromRawEncoding(ExpansionLocEnd).isValid();
335    }
336
337    bool isFunctionMacroExpansion() const {
338      return getExpansionLocStart().isValid() &&
339          getExpansionLocStart() != getExpansionLocEnd();
340    }
341
342    /// \brief Return a ExpansionInfo for an expansion.
343    ///
344    /// Start and End specify the expansion range (where the macro is
345    /// expanded), and SpellingLoc specifies the spelling location (where
346    /// the characters from the token come from). All three can refer to
347    /// normal File SLocs or expansion locations.
348    static ExpansionInfo create(SourceLocation SpellingLoc,
349                                SourceLocation Start, SourceLocation End) {
350      ExpansionInfo X;
351      X.SpellingLoc = SpellingLoc.getRawEncoding();
352      X.ExpansionLocStart = Start.getRawEncoding();
353      X.ExpansionLocEnd = End.getRawEncoding();
354      return X;
355    }
356
357    /// \brief Return a special ExpansionInfo for the expansion of
358    /// a macro argument into a function-like macro's body.
359    ///
360    /// ExpansionLoc specifies the expansion location (where the macro is
361    /// expanded). This doesn't need to be a range because a macro is always
362    /// expanded at a macro parameter reference, and macro parameters are
363    /// always exactly one token. SpellingLoc specifies the spelling location
364    /// (where the characters from the token come from). ExpansionLoc and
365    /// SpellingLoc can both refer to normal File SLocs or expansion locations.
366    ///
367    /// Given the code:
368    /// \code
369    ///   #define F(x) f(x)
370    ///   F(42);
371    /// \endcode
372    ///
373    /// When expanding '\c F(42)', the '\c x' would call this with an
374    /// SpellingLoc pointing at '\c 42' and an ExpansionLoc pointing at its
375    /// location in the definition of '\c F'.
376    static ExpansionInfo createForMacroArg(SourceLocation SpellingLoc,
377                                           SourceLocation ExpansionLoc) {
378      // We store an intentionally invalid source location for the end of the
379      // expansion range to mark that this is a macro argument ion rather than
380      // a normal one.
381      return create(SpellingLoc, ExpansionLoc, SourceLocation());
382    }
383  };
384
385  /// \brief This is a discriminated union of FileInfo and ExpansionInfo.
386  ///
387  /// SourceManager keeps an array of these objects, and they are uniquely
388  /// identified by the FileID datatype.
389  class SLocEntry {
390    unsigned Offset;   // low bit is set for expansion info.
391    union {
392      FileInfo File;
393      ExpansionInfo Expansion;
394    };
395  public:
396    unsigned getOffset() const { return Offset >> 1; }
397
398    bool isExpansion() const { return Offset & 1; }
399    bool isFile() const { return !isExpansion(); }
400
401    const FileInfo &getFile() const {
402      assert(isFile() && "Not a file SLocEntry!");
403      return File;
404    }
405
406    const ExpansionInfo &getExpansion() const {
407      assert(isExpansion() && "Not a macro expansion SLocEntry!");
408      return Expansion;
409    }
410
411    static SLocEntry get(unsigned Offset, const FileInfo &FI) {
412      SLocEntry E;
413      E.Offset = Offset << 1;
414      E.File = FI;
415      return E;
416    }
417
418    static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
419      SLocEntry E;
420      E.Offset = (Offset << 1) | 1;
421      E.Expansion = Expansion;
422      return E;
423    }
424  };
425}  // end SrcMgr namespace.
426
427/// \brief External source of source location entries.
428class ExternalSLocEntrySource {
429public:
430  virtual ~ExternalSLocEntrySource();
431
432  /// \brief Read the source location entry with index ID, which will always be
433  /// less than -1.
434  ///
435  /// \returns true if an error occurred that prevented the source-location
436  /// entry from being loaded.
437  virtual bool ReadSLocEntry(int ID) = 0;
438
439  /// \brief Retrieve the module import location and name for the given ID, if
440  /// in fact it was loaded from a module (rather than, say, a precompiled
441  /// header).
442  virtual std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) = 0;
443};
444
445
446/// \brief Holds the cache used by isBeforeInTranslationUnit.
447///
448/// The cache structure is complex enough to be worth breaking out of
449/// SourceManager.
450class InBeforeInTUCacheEntry {
451  /// \brief The FileID's of the cached query.
452  ///
453  /// If these match up with a subsequent query, the result can be reused.
454  FileID LQueryFID, RQueryFID;
455
456  /// \brief True if LQueryFID was created before RQueryFID.
457  ///
458  /// This is used to compare macro expansion locations.
459  bool IsLQFIDBeforeRQFID;
460
461  /// \brief The file found in common between the two \#include traces, i.e.,
462  /// the nearest common ancestor of the \#include tree.
463  FileID CommonFID;
464
465  /// \brief The offset of the previous query in CommonFID.
466  ///
467  /// Usually, this represents the location of the \#include for QueryFID, but
468  /// if LQueryFID is a parent of RQueryFID (or vice versa) then these can be a
469  /// random token in the parent.
470  unsigned LCommonOffset, RCommonOffset;
471public:
472  /// \brief Return true if the currently cached values match up with
473  /// the specified LHS/RHS query.
474  ///
475  /// If not, we can't use the cache.
476  bool isCacheValid(FileID LHS, FileID RHS) const {
477    return LQueryFID == LHS && RQueryFID == RHS;
478  }
479
480  /// \brief If the cache is valid, compute the result given the
481  /// specified offsets in the LHS/RHS FileID's.
482  bool getCachedResult(unsigned LOffset, unsigned ROffset) const {
483    // If one of the query files is the common file, use the offset.  Otherwise,
484    // use the #include loc in the common file.
485    if (LQueryFID != CommonFID) LOffset = LCommonOffset;
486    if (RQueryFID != CommonFID) ROffset = RCommonOffset;
487
488    // It is common for multiple macro expansions to be "included" from the same
489    // location (expansion location), in which case use the order of the FileIDs
490    // to determine which came first. This will also take care the case where
491    // one of the locations points at the inclusion/expansion point of the other
492    // in which case its FileID will come before the other.
493    if (LOffset == ROffset)
494      return IsLQFIDBeforeRQFID;
495
496    return LOffset < ROffset;
497  }
498
499  /// \brief Set up a new query.
500  void setQueryFIDs(FileID LHS, FileID RHS, bool isLFIDBeforeRFID) {
501    assert(LHS != RHS);
502    LQueryFID = LHS;
503    RQueryFID = RHS;
504    IsLQFIDBeforeRQFID = isLFIDBeforeRFID;
505  }
506
507  void clear() {
508    LQueryFID = RQueryFID = FileID();
509    IsLQFIDBeforeRQFID = false;
510  }
511
512  void setCommonLoc(FileID commonFID, unsigned lCommonOffset,
513                    unsigned rCommonOffset) {
514    CommonFID = commonFID;
515    LCommonOffset = lCommonOffset;
516    RCommonOffset = rCommonOffset;
517  }
518
519};
520
521/// \brief The stack used when building modules on demand, which is used
522/// to provide a link between the source managers of the different compiler
523/// instances.
524typedef ArrayRef<std::pair<std::string, FullSourceLoc> > ModuleBuildStack;
525
526/// \brief This class handles loading and caching of source files into memory.
527///
528/// This object owns the MemoryBuffer objects for all of the loaded
529/// files and assigns unique FileID's for each unique \#include chain.
530///
531/// The SourceManager can be queried for information about SourceLocation
532/// objects, turning them into either spelling or expansion locations. Spelling
533/// locations represent where the bytes corresponding to a token came from and
534/// expansion locations represent where the location is in the user's view. In
535/// the case of a macro expansion, for example, the spelling location indicates
536/// where the expanded token came from and the expansion location specifies
537/// where it was expanded.
538class SourceManager : public RefCountedBase<SourceManager> {
539  /// \brief DiagnosticsEngine object.
540  DiagnosticsEngine &Diag;
541
542  FileManager &FileMgr;
543
544  mutable llvm::BumpPtrAllocator ContentCacheAlloc;
545
546  /// \brief Memoized information about all of the files tracked by this
547  /// SourceManager.
548  ///
549  /// This map allows us to merge ContentCache entries based
550  /// on their FileEntry*.  All ContentCache objects will thus have unique,
551  /// non-null, FileEntry pointers.
552  llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*> FileInfos;
553
554  /// \brief True if the ContentCache for files that are overriden by other
555  /// files, should report the original file name. Defaults to true.
556  bool OverridenFilesKeepOriginalName;
557
558  /// \brief True if non-system source files should be treated as volatile
559  /// (likely to change while trying to use them). Defaults to false.
560  bool UserFilesAreVolatile;
561
562  struct OverriddenFilesInfoTy {
563    /// \brief Files that have been overriden with the contents from another
564    /// file.
565    llvm::DenseMap<const FileEntry *, const FileEntry *> OverriddenFiles;
566    /// \brief Files that were overridden with a memory buffer.
567    llvm::DenseSet<const FileEntry *> OverriddenFilesWithBuffer;
568  };
569
570  /// \brief Lazily create the object keeping overridden files info, since
571  /// it is uncommonly used.
572  OwningPtr<OverriddenFilesInfoTy> OverriddenFilesInfo;
573
574  OverriddenFilesInfoTy &getOverriddenFilesInfo() {
575    if (!OverriddenFilesInfo)
576      OverriddenFilesInfo.reset(new OverriddenFilesInfoTy);
577    return *OverriddenFilesInfo;
578  }
579
580  /// \brief Information about various memory buffers that we have read in.
581  ///
582  /// All FileEntry* within the stored ContentCache objects are NULL,
583  /// as they do not refer to a file.
584  std::vector<SrcMgr::ContentCache*> MemBufferInfos;
585
586  /// \brief The table of SLocEntries that are local to this module.
587  ///
588  /// Positive FileIDs are indexes into this table. Entry 0 indicates an invalid
589  /// expansion.
590  SmallVector<SrcMgr::SLocEntry, 0> LocalSLocEntryTable;
591
592  /// \brief The table of SLocEntries that are loaded from other modules.
593  ///
594  /// Negative FileIDs are indexes into this table. To get from ID to an index,
595  /// use (-ID - 2).
596  mutable SmallVector<SrcMgr::SLocEntry, 0> LoadedSLocEntryTable;
597
598  /// \brief The starting offset of the next local SLocEntry.
599  ///
600  /// This is LocalSLocEntryTable.back().Offset + the size of that entry.
601  unsigned NextLocalOffset;
602
603  /// \brief The starting offset of the latest batch of loaded SLocEntries.
604  ///
605  /// This is LoadedSLocEntryTable.back().Offset, except that that entry might
606  /// not have been loaded, so that value would be unknown.
607  unsigned CurrentLoadedOffset;
608
609  /// \brief The highest possible offset is 2^31-1, so CurrentLoadedOffset
610  /// starts at 2^31.
611  static const unsigned MaxLoadedOffset = 1U << 31U;
612
613  /// \brief A bitmap that indicates whether the entries of LoadedSLocEntryTable
614  /// have already been loaded from the external source.
615  ///
616  /// Same indexing as LoadedSLocEntryTable.
617  std::vector<bool> SLocEntryLoaded;
618
619  /// \brief An external source for source location entries.
620  ExternalSLocEntrySource *ExternalSLocEntries;
621
622  /// \brief A one-entry cache to speed up getFileID.
623  ///
624  /// LastFileIDLookup records the last FileID looked up or created, because it
625  /// is very common to look up many tokens from the same file.
626  mutable FileID LastFileIDLookup;
627
628  /// \brief Holds information for \#line directives.
629  ///
630  /// This is referenced by indices from SLocEntryTable.
631  LineTableInfo *LineTable;
632
633  /// \brief These ivars serve as a cache used in the getLineNumber
634  /// method which is used to speedup getLineNumber calls to nearby locations.
635  mutable FileID LastLineNoFileIDQuery;
636  mutable SrcMgr::ContentCache *LastLineNoContentCache;
637  mutable unsigned LastLineNoFilePos;
638  mutable unsigned LastLineNoResult;
639
640  /// \brief The file ID for the main source file of the translation unit.
641  FileID MainFileID;
642
643  /// \brief The file ID for the precompiled preamble there is one.
644  FileID PreambleFileID;
645
646  // Statistics for -print-stats.
647  mutable unsigned NumLinearScans, NumBinaryProbes;
648
649  /// \brief Associates a FileID with its "included/expanded in" decomposed
650  /// location.
651  ///
652  /// Used to cache results from and speed-up \c getDecomposedIncludedLoc
653  /// function.
654  mutable llvm::DenseMap<FileID, std::pair<FileID, unsigned> > IncludedLocMap;
655
656  /// The key value into the IsBeforeInTUCache table.
657  typedef std::pair<FileID, FileID> IsBeforeInTUCacheKey;
658
659  /// The IsBeforeInTranslationUnitCache is a mapping from FileID pairs
660  /// to cache results.
661  typedef llvm::DenseMap<IsBeforeInTUCacheKey, InBeforeInTUCacheEntry>
662          InBeforeInTUCache;
663
664  /// Cache results for the isBeforeInTranslationUnit method.
665  mutable InBeforeInTUCache IBTUCache;
666  mutable InBeforeInTUCacheEntry IBTUCacheOverflow;
667
668  /// Return the cache entry for comparing the given file IDs
669  /// for isBeforeInTranslationUnit.
670  InBeforeInTUCacheEntry &getInBeforeInTUCache(FileID LFID, FileID RFID) const;
671
672  // Cache for the "fake" buffer used for error-recovery purposes.
673  mutable llvm::MemoryBuffer *FakeBufferForRecovery;
674
675  mutable SrcMgr::ContentCache *FakeContentCacheForRecovery;
676
677  /// \brief Lazily computed map of macro argument chunks to their expanded
678  /// source location.
679  typedef std::map<unsigned, SourceLocation> MacroArgsMap;
680
681  mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
682
683  /// \brief The stack of modules being built, which is used to detect
684  /// cycles in the module dependency graph as modules are being built, as
685  /// well as to describe why we're rebuilding a particular module.
686  ///
687  /// There is no way to set this value from the command line. If we ever need
688  /// to do so (e.g., if on-demand module construction moves out-of-process),
689  /// we can add a cc1-level option to do so.
690  SmallVector<std::pair<std::string, FullSourceLoc>, 2> StoredModuleBuildStack;
691
692  // SourceManager doesn't support copy construction.
693  explicit SourceManager(const SourceManager&) LLVM_DELETED_FUNCTION;
694  void operator=(const SourceManager&) LLVM_DELETED_FUNCTION;
695public:
696  SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
697                bool UserFilesAreVolatile = false);
698  ~SourceManager();
699
700  void clearIDTables();
701
702  DiagnosticsEngine &getDiagnostics() const { return Diag; }
703
704  FileManager &getFileManager() const { return FileMgr; }
705
706  /// \brief Set true if the SourceManager should report the original file name
707  /// for contents of files that were overriden by other files.Defaults to true.
708  void setOverridenFilesKeepOriginalName(bool value) {
709    OverridenFilesKeepOriginalName = value;
710  }
711
712  /// \brief True if non-system source files should be treated as volatile
713  /// (likely to change while trying to use them).
714  bool userFilesAreVolatile() const { return UserFilesAreVolatile; }
715
716  /// \brief Retrieve the module build stack.
717  ModuleBuildStack getModuleBuildStack() const {
718    return StoredModuleBuildStack;
719  }
720
721  /// \brief Set the module build stack.
722  void setModuleBuildStack(ModuleBuildStack stack) {
723    StoredModuleBuildStack.clear();
724    StoredModuleBuildStack.append(stack.begin(), stack.end());
725  }
726
727  /// \brief Push an entry to the module build stack.
728  void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc) {
729    StoredModuleBuildStack.push_back(std::make_pair(moduleName.str(),importLoc));
730  }
731
732  /// \brief Create the FileID for a memory buffer that will represent the
733  /// FileID for the main source.
734  ///
735  /// One example of when this would be used is when the main source is read
736  /// from STDIN.
737  FileID createMainFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
738                             SrcMgr::CharacteristicKind Kind = SrcMgr::C_User) {
739    assert(MainFileID.isInvalid() && "MainFileID already set!");
740    MainFileID = createFileIDForMemBuffer(Buffer, Kind);
741    return MainFileID;
742  }
743
744  //===--------------------------------------------------------------------===//
745  // MainFileID creation and querying methods.
746  //===--------------------------------------------------------------------===//
747
748  /// \brief Returns the FileID of the main source file.
749  FileID getMainFileID() const { return MainFileID; }
750
751  /// \brief Create the FileID for the main source file.
752  FileID createMainFileID(const FileEntry *SourceFile,
753                          SrcMgr::CharacteristicKind Kind = SrcMgr::C_User) {
754    assert(MainFileID.isInvalid() && "MainFileID already set!");
755    MainFileID = createFileID(SourceFile, SourceLocation(), Kind);
756    return MainFileID;
757  }
758
759  /// \brief Set the file ID for the main source file.
760  void setMainFileID(FileID FID) {
761    assert(MainFileID.isInvalid() && "MainFileID already set!");
762    MainFileID = FID;
763  }
764
765  /// \brief Set the file ID for the precompiled preamble.
766  void setPreambleFileID(FileID Preamble) {
767    assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
768    PreambleFileID = Preamble;
769  }
770
771  /// \brief Get the file ID for the precompiled preamble if there is one.
772  FileID getPreambleFileID() const { return PreambleFileID; }
773
774  //===--------------------------------------------------------------------===//
775  // Methods to create new FileID's and macro expansions.
776  //===--------------------------------------------------------------------===//
777
778  /// \brief Create a new FileID that represents the specified file
779  /// being \#included from the specified IncludePosition.
780  ///
781  /// This translates NULL into standard input.
782  FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos,
783                      SrcMgr::CharacteristicKind FileCharacter,
784                      int LoadedID = 0, unsigned LoadedOffset = 0) {
785    const SrcMgr::ContentCache *
786      IR = getOrCreateContentCache(SourceFile,
787                              /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
788    assert(IR && "getOrCreateContentCache() cannot return NULL");
789    return createFileID(IR, IncludePos, FileCharacter, LoadedID, LoadedOffset);
790  }
791
792  /// \brief Create a new FileID that represents the specified memory buffer.
793  ///
794  /// This does no caching of the buffer and takes ownership of the
795  /// MemoryBuffer, so only pass a MemoryBuffer to this once.
796  FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
797                      SrcMgr::CharacteristicKind FileCharacter = SrcMgr::C_User,
798                                  int LoadedID = 0, unsigned LoadedOffset = 0,
799                                 SourceLocation IncludeLoc = SourceLocation()) {
800    return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
801                        FileCharacter, LoadedID, LoadedOffset);
802  }
803
804  /// \brief Return a new SourceLocation that encodes the
805  /// fact that a token from SpellingLoc should actually be referenced from
806  /// ExpansionLoc, and that it represents the expansion of a macro argument
807  /// into the function-like macro body.
808  SourceLocation createMacroArgExpansionLoc(SourceLocation Loc,
809                                            SourceLocation ExpansionLoc,
810                                            unsigned TokLength);
811
812  /// \brief Return a new SourceLocation that encodes the fact
813  /// that a token from SpellingLoc should actually be referenced from
814  /// ExpansionLoc.
815  SourceLocation createExpansionLoc(SourceLocation Loc,
816                                    SourceLocation ExpansionLocStart,
817                                    SourceLocation ExpansionLocEnd,
818                                    unsigned TokLength,
819                                    int LoadedID = 0,
820                                    unsigned LoadedOffset = 0);
821
822  /// \brief Retrieve the memory buffer associated with the given file.
823  ///
824  /// \param Invalid If non-NULL, will be set \c true if an error
825  /// occurs while retrieving the memory buffer.
826  const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
827                                                   bool *Invalid = 0);
828
829  /// \brief Override the contents of the given source file by providing an
830  /// already-allocated buffer.
831  ///
832  /// \param SourceFile the source file whose contents will be overriden.
833  ///
834  /// \param Buffer the memory buffer whose contents will be used as the
835  /// data in the given source file.
836  ///
837  /// \param DoNotFree If true, then the buffer will not be freed when the
838  /// source manager is destroyed.
839  void overrideFileContents(const FileEntry *SourceFile,
840                            const llvm::MemoryBuffer *Buffer,
841                            bool DoNotFree = false);
842
843  /// \brief Override the given source file with another one.
844  ///
845  /// \param SourceFile the source file which will be overriden.
846  ///
847  /// \param NewFile the file whose contents will be used as the
848  /// data instead of the contents of the given source file.
849  void overrideFileContents(const FileEntry *SourceFile,
850                            const FileEntry *NewFile);
851
852  /// \brief Returns true if the file contents have been overridden.
853  bool isFileOverridden(const FileEntry *File) {
854    if (OverriddenFilesInfo) {
855      if (OverriddenFilesInfo->OverriddenFilesWithBuffer.count(File))
856        return true;
857      if (OverriddenFilesInfo->OverriddenFiles.find(File) !=
858          OverriddenFilesInfo->OverriddenFiles.end())
859        return true;
860    }
861    return false;
862  }
863
864  /// \brief Disable overridding the contents of a file, previously enabled
865  /// with #overrideFileContents.
866  ///
867  /// This should be called before parsing has begun.
868  void disableFileContentsOverride(const FileEntry *File);
869
870  //===--------------------------------------------------------------------===//
871  // FileID manipulation methods.
872  //===--------------------------------------------------------------------===//
873
874  /// \brief Return the buffer for the specified FileID.
875  ///
876  /// If there is an error opening this buffer the first time, this
877  /// manufactures a temporary buffer and returns a non-empty error string.
878  const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
879                                      bool *Invalid = 0) const {
880    bool MyInvalid = false;
881    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
882    if (MyInvalid || !Entry.isFile()) {
883      if (Invalid)
884        *Invalid = true;
885
886      return getFakeBufferForRecovery();
887    }
888
889    return Entry.getFile().getContentCache()->getBuffer(Diag, *this, Loc,
890                                                        Invalid);
891  }
892
893  const llvm::MemoryBuffer *getBuffer(FileID FID, bool *Invalid = 0) const {
894    bool MyInvalid = false;
895    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
896    if (MyInvalid || !Entry.isFile()) {
897      if (Invalid)
898        *Invalid = true;
899
900      return getFakeBufferForRecovery();
901    }
902
903    return Entry.getFile().getContentCache()->getBuffer(Diag, *this,
904                                                        SourceLocation(),
905                                                        Invalid);
906  }
907
908  /// \brief Returns the FileEntry record for the provided FileID.
909  const FileEntry *getFileEntryForID(FileID FID) const {
910    bool MyInvalid = false;
911    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
912    if (MyInvalid || !Entry.isFile())
913      return 0;
914
915    const SrcMgr::ContentCache *Content = Entry.getFile().getContentCache();
916    if (!Content)
917      return 0;
918    return Content->OrigEntry;
919  }
920
921  /// \brief Returns the FileEntry record for the provided SLocEntry.
922  const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc) const
923  {
924    const SrcMgr::ContentCache *Content = sloc.getFile().getContentCache();
925    if (!Content)
926      return 0;
927    return Content->OrigEntry;
928  }
929
930  /// \brief Return a StringRef to the source buffer data for the
931  /// specified FileID.
932  ///
933  /// \param FID The file ID whose contents will be returned.
934  /// \param Invalid If non-NULL, will be set true if an error occurred.
935  StringRef getBufferData(FileID FID, bool *Invalid = 0) const;
936
937  /// \brief Get the number of FileIDs (files and macros) that were created
938  /// during preprocessing of \p FID, including it.
939  unsigned getNumCreatedFIDsForFileID(FileID FID) const {
940    bool Invalid = false;
941    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
942    if (Invalid || !Entry.isFile())
943      return 0;
944
945    return Entry.getFile().NumCreatedFIDs;
946  }
947
948  /// \brief Set the number of FileIDs (files and macros) that were created
949  /// during preprocessing of \p FID, including it.
950  void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
951    bool Invalid = false;
952    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
953    if (Invalid || !Entry.isFile())
954      return;
955
956    assert(Entry.getFile().NumCreatedFIDs == 0 && "Already set!");
957    const_cast<SrcMgr::FileInfo &>(Entry.getFile()).NumCreatedFIDs = NumFIDs;
958  }
959
960  //===--------------------------------------------------------------------===//
961  // SourceLocation manipulation methods.
962  //===--------------------------------------------------------------------===//
963
964  /// \brief Return the FileID for a SourceLocation.
965  ///
966  /// This is a very hot method that is used for all SourceManager queries
967  /// that start with a SourceLocation object.  It is responsible for finding
968  /// the entry in SLocEntryTable which contains the specified location.
969  ///
970  FileID getFileID(SourceLocation SpellingLoc) const {
971    unsigned SLocOffset = SpellingLoc.getOffset();
972
973    // If our one-entry cache covers this offset, just return it.
974    if (isOffsetInFileID(LastFileIDLookup, SLocOffset))
975      return LastFileIDLookup;
976
977    return getFileIDSlow(SLocOffset);
978  }
979
980  /// \brief Return the filename of the file containing a SourceLocation.
981  StringRef getFilename(SourceLocation SpellingLoc) const {
982    if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
983      return F->getName();
984    return StringRef();
985  }
986
987  /// \brief Return the source location corresponding to the first byte of
988  /// the specified file.
989  SourceLocation getLocForStartOfFile(FileID FID) const {
990    bool Invalid = false;
991    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
992    if (Invalid || !Entry.isFile())
993      return SourceLocation();
994
995    unsigned FileOffset = Entry.getOffset();
996    return SourceLocation::getFileLoc(FileOffset);
997  }
998
999  /// \brief Return the source location corresponding to the last byte of the
1000  /// specified file.
1001  SourceLocation getLocForEndOfFile(FileID FID) const {
1002    bool Invalid = false;
1003    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1004    if (Invalid || !Entry.isFile())
1005      return SourceLocation();
1006
1007    unsigned FileOffset = Entry.getOffset();
1008    return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID));
1009  }
1010
1011  /// \brief Returns the include location if \p FID is a \#include'd file
1012  /// otherwise it returns an invalid location.
1013  SourceLocation getIncludeLoc(FileID FID) const {
1014    bool Invalid = false;
1015    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1016    if (Invalid || !Entry.isFile())
1017      return SourceLocation();
1018
1019    return Entry.getFile().getIncludeLoc();
1020  }
1021
1022  // \brief Returns the import location if the given source location is
1023  // located within a module, or an invalid location if the source location
1024  // is within the current translation unit.
1025  std::pair<SourceLocation, StringRef>
1026  getModuleImportLoc(SourceLocation Loc) const {
1027    FileID FID = getFileID(Loc);
1028
1029    // Positive file IDs are in the current translation unit, and -1 is a
1030    // placeholder.
1031    if (FID.ID >= -1)
1032      return std::make_pair(SourceLocation(), "");
1033
1034    return ExternalSLocEntries->getModuleImportLoc(FID.ID);
1035  }
1036
1037  /// \brief Given a SourceLocation object \p Loc, return the expansion
1038  /// location referenced by the ID.
1039  SourceLocation getExpansionLoc(SourceLocation Loc) const {
1040    // Handle the non-mapped case inline, defer to out of line code to handle
1041    // expansions.
1042    if (Loc.isFileID()) return Loc;
1043    return getExpansionLocSlowCase(Loc);
1044  }
1045
1046  /// \brief Given \p Loc, if it is a macro location return the expansion
1047  /// location or the spelling location, depending on if it comes from a
1048  /// macro argument or not.
1049  SourceLocation getFileLoc(SourceLocation Loc) const {
1050    if (Loc.isFileID()) return Loc;
1051    return getFileLocSlowCase(Loc);
1052  }
1053
1054  /// \brief Return the start/end of the expansion information for an
1055  /// expansion location.
1056  ///
1057  /// \pre \p Loc is required to be an expansion location.
1058  std::pair<SourceLocation,SourceLocation>
1059  getImmediateExpansionRange(SourceLocation Loc) const;
1060
1061  /// \brief Given a SourceLocation object, return the range of
1062  /// tokens covered by the expansion the ultimate file.
1063  std::pair<SourceLocation,SourceLocation>
1064  getExpansionRange(SourceLocation Loc) const;
1065
1066
1067  /// \brief Given a SourceLocation object, return the spelling
1068  /// location referenced by the ID.
1069  ///
1070  /// This is the place where the characters that make up the lexed token
1071  /// can be found.
1072  SourceLocation getSpellingLoc(SourceLocation Loc) const {
1073    // Handle the non-mapped case inline, defer to out of line code to handle
1074    // expansions.
1075    if (Loc.isFileID()) return Loc;
1076    return getSpellingLocSlowCase(Loc);
1077  }
1078
1079  /// \brief Given a SourceLocation object, return the spelling location
1080  /// referenced by the ID.
1081  ///
1082  /// This is the first level down towards the place where the characters
1083  /// that make up the lexed token can be found.  This should not generally
1084  /// be used by clients.
1085  SourceLocation getImmediateSpellingLoc(SourceLocation Loc) const;
1086
1087  /// \brief Decompose the specified location into a raw FileID + Offset pair.
1088  ///
1089  /// The first element is the FileID, the second is the offset from the
1090  /// start of the buffer of the location.
1091  std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
1092    FileID FID = getFileID(Loc);
1093    bool Invalid = false;
1094    const SrcMgr::SLocEntry &E = getSLocEntry(FID, &Invalid);
1095    if (Invalid)
1096      return std::make_pair(FileID(), 0);
1097    return std::make_pair(FID, Loc.getOffset()-E.getOffset());
1098  }
1099
1100  /// \brief Decompose the specified location into a raw FileID + Offset pair.
1101  ///
1102  /// If the location is an expansion record, walk through it until we find
1103  /// the final location expanded.
1104  std::pair<FileID, unsigned>
1105  getDecomposedExpansionLoc(SourceLocation Loc) const {
1106    FileID FID = getFileID(Loc);
1107    bool Invalid = false;
1108    const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1109    if (Invalid)
1110      return std::make_pair(FileID(), 0);
1111
1112    unsigned Offset = Loc.getOffset()-E->getOffset();
1113    if (Loc.isFileID())
1114      return std::make_pair(FID, Offset);
1115
1116    return getDecomposedExpansionLocSlowCase(E);
1117  }
1118
1119  /// \brief Decompose the specified location into a raw FileID + Offset pair.
1120  ///
1121  /// If the location is an expansion record, walk through it until we find
1122  /// its spelling record.
1123  std::pair<FileID, unsigned>
1124  getDecomposedSpellingLoc(SourceLocation Loc) const {
1125    FileID FID = getFileID(Loc);
1126    bool Invalid = false;
1127    const SrcMgr::SLocEntry *E = &getSLocEntry(FID, &Invalid);
1128    if (Invalid)
1129      return std::make_pair(FileID(), 0);
1130
1131    unsigned Offset = Loc.getOffset()-E->getOffset();
1132    if (Loc.isFileID())
1133      return std::make_pair(FID, Offset);
1134    return getDecomposedSpellingLocSlowCase(E, Offset);
1135  }
1136
1137  /// \brief Returns the "included/expanded in" decomposed location of the given
1138  /// FileID.
1139  std::pair<FileID, unsigned> getDecomposedIncludedLoc(FileID FID) const;
1140
1141  /// \brief Returns the offset from the start of the file that the
1142  /// specified SourceLocation represents.
1143  ///
1144  /// This is not very meaningful for a macro ID.
1145  unsigned getFileOffset(SourceLocation SpellingLoc) const {
1146    return getDecomposedLoc(SpellingLoc).second;
1147  }
1148
1149  /// \brief Tests whether the given source location represents a macro
1150  /// argument's expansion into the function-like macro definition.
1151  ///
1152  /// Such source locations only appear inside of the expansion
1153  /// locations representing where a particular function-like macro was
1154  /// expanded.
1155  bool isMacroArgExpansion(SourceLocation Loc) const;
1156
1157  /// \brief Tests whether the given source location represents the expansion of
1158  /// a macro body.
1159  ///
1160  /// This is equivalent to testing whether the location is part of a macro
1161  /// expansion but not the expansion of an argument to a function-like macro.
1162  bool isMacroBodyExpansion(SourceLocation Loc) const;
1163
1164  /// \brief Returns true if the given MacroID location points at the beginning
1165  /// of the immediate macro expansion.
1166  ///
1167  /// \param MacroBegin If non-null and function returns true, it is set to the
1168  /// begin location of the immediate macro expansion.
1169  bool isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1170                                          SourceLocation *MacroBegin = 0) const;
1171
1172  /// \brief Returns true if the given MacroID location points at the character
1173  /// end of the immediate macro expansion.
1174  ///
1175  /// \param MacroEnd If non-null and function returns true, it is set to the
1176  /// character end location of the immediate macro expansion.
1177  bool isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1178                                        SourceLocation *MacroEnd = 0) const;
1179
1180  /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
1181  /// chunk of the source location address space.
1182  ///
1183  /// If it's true and \p RelativeOffset is non-null, it will be set to the
1184  /// relative offset of \p Loc inside the chunk.
1185  bool isInSLocAddrSpace(SourceLocation Loc,
1186                         SourceLocation Start, unsigned Length,
1187                         unsigned *RelativeOffset = 0) const {
1188    assert(((Start.getOffset() < NextLocalOffset &&
1189               Start.getOffset()+Length <= NextLocalOffset) ||
1190            (Start.getOffset() >= CurrentLoadedOffset &&
1191                Start.getOffset()+Length < MaxLoadedOffset)) &&
1192           "Chunk is not valid SLoc address space");
1193    unsigned LocOffs = Loc.getOffset();
1194    unsigned BeginOffs = Start.getOffset();
1195    unsigned EndOffs = BeginOffs + Length;
1196    if (LocOffs >= BeginOffs && LocOffs < EndOffs) {
1197      if (RelativeOffset)
1198        *RelativeOffset = LocOffs - BeginOffs;
1199      return true;
1200    }
1201
1202    return false;
1203  }
1204
1205  /// \brief Return true if both \p LHS and \p RHS are in the local source
1206  /// location address space or the loaded one.
1207  ///
1208  /// If it's true and \p RelativeOffset is non-null, it will be set to the
1209  /// offset of \p RHS relative to \p LHS.
1210  bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
1211                             int *RelativeOffset) const {
1212    unsigned LHSOffs = LHS.getOffset(), RHSOffs = RHS.getOffset();
1213    bool LHSLoaded = LHSOffs >= CurrentLoadedOffset;
1214    bool RHSLoaded = RHSOffs >= CurrentLoadedOffset;
1215
1216    if (LHSLoaded == RHSLoaded) {
1217      if (RelativeOffset)
1218        *RelativeOffset = RHSOffs - LHSOffs;
1219      return true;
1220    }
1221
1222    return false;
1223  }
1224
1225  //===--------------------------------------------------------------------===//
1226  // Queries about the code at a SourceLocation.
1227  //===--------------------------------------------------------------------===//
1228
1229  /// \brief Return a pointer to the start of the specified location
1230  /// in the appropriate spelling MemoryBuffer.
1231  ///
1232  /// \param Invalid If non-NULL, will be set \c true if an error occurs.
1233  const char *getCharacterData(SourceLocation SL, bool *Invalid = 0) const;
1234
1235  /// \brief Return the column # for the specified file position.
1236  ///
1237  /// This is significantly cheaper to compute than the line number.  This
1238  /// returns zero if the column number isn't known.  This may only be called
1239  /// on a file sloc, so you must choose a spelling or expansion location
1240  /// before calling this method.
1241  unsigned getColumnNumber(FileID FID, unsigned FilePos,
1242                           bool *Invalid = 0) const;
1243  unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1244  unsigned getExpansionColumnNumber(SourceLocation Loc,
1245                                    bool *Invalid = 0) const;
1246  unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid = 0) const;
1247
1248
1249  /// \brief Given a SourceLocation, return the spelling line number
1250  /// for the position indicated.
1251  ///
1252  /// This requires building and caching a table of line offsets for the
1253  /// MemoryBuffer, so this is not cheap: use only when about to emit a
1254  /// diagnostic.
1255  unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid = 0) const;
1256  unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1257  unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1258  unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid = 0) const;
1259
1260  /// \brief Return the filename or buffer identifier of the buffer the
1261  /// location is in.
1262  ///
1263  /// Note that this name does not respect \#line directives.  Use
1264  /// getPresumedLoc for normal clients.
1265  const char *getBufferName(SourceLocation Loc, bool *Invalid = 0) const;
1266
1267  /// \brief Return the file characteristic of the specified source
1268  /// location, indicating whether this is a normal file, a system
1269  /// header, or an "implicit extern C" system header.
1270  ///
1271  /// This state can be modified with flags on GNU linemarker directives like:
1272  /// \code
1273  ///   # 4 "foo.h" 3
1274  /// \endcode
1275  /// which changes all source locations in the current file after that to be
1276  /// considered to be from a system header.
1277  SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const;
1278
1279  /// \brief Returns the "presumed" location of a SourceLocation specifies.
1280  ///
1281  /// A "presumed location" can be modified by \#line or GNU line marker
1282  /// directives.  This provides a view on the data that a user should see
1283  /// in diagnostics, for example.
1284  ///
1285  /// Note that a presumed location is always given as the expansion point of
1286  /// an expansion location, not at the spelling location.
1287  ///
1288  /// \returns The presumed location of the specified SourceLocation. If the
1289  /// presumed location cannot be calculate (e.g., because \p Loc is invalid
1290  /// or the file containing \p Loc has changed on disk), returns an invalid
1291  /// presumed location.
1292  PresumedLoc getPresumedLoc(SourceLocation Loc,
1293                             bool UseLineDirectives = true) const;
1294
1295  /// \brief Returns true if both SourceLocations correspond to the same file.
1296  bool isFromSameFile(SourceLocation Loc1, SourceLocation Loc2) const {
1297    return getFileID(Loc1) == getFileID(Loc2);
1298  }
1299
1300  /// \brief Returns true if the file of provided SourceLocation is the main
1301  /// file.
1302  bool isFromMainFile(SourceLocation Loc) const {
1303    return getFileID(Loc) == getMainFileID();
1304  }
1305
1306  /// \brief Returns if a SourceLocation is in a system header.
1307  bool isInSystemHeader(SourceLocation Loc) const {
1308    return getFileCharacteristic(Loc) != SrcMgr::C_User;
1309  }
1310
1311  /// \brief Returns if a SourceLocation is in an "extern C" system header.
1312  bool isInExternCSystemHeader(SourceLocation Loc) const {
1313    return getFileCharacteristic(Loc) == SrcMgr::C_ExternCSystem;
1314  }
1315
1316  /// \brief Returns whether \p Loc is expanded from a macro in a system header.
1317  bool isInSystemMacro(SourceLocation loc) {
1318    return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
1319  }
1320
1321  /// \brief The size of the SLocEnty that \p FID represents.
1322  unsigned getFileIDSize(FileID FID) const;
1323
1324  /// \brief Given a specific FileID, returns true if \p Loc is inside that
1325  /// FileID chunk and sets relative offset (offset of \p Loc from beginning
1326  /// of FileID) to \p relativeOffset.
1327  bool isInFileID(SourceLocation Loc, FileID FID,
1328                  unsigned *RelativeOffset = 0) const {
1329    unsigned Offs = Loc.getOffset();
1330    if (isOffsetInFileID(FID, Offs)) {
1331      if (RelativeOffset)
1332        *RelativeOffset = Offs - getSLocEntry(FID).getOffset();
1333      return true;
1334    }
1335
1336    return false;
1337  }
1338
1339  //===--------------------------------------------------------------------===//
1340  // Line Table Manipulation Routines
1341  //===--------------------------------------------------------------------===//
1342
1343  /// \brief Return the uniqued ID for the specified filename.
1344  ///
1345  unsigned getLineTableFilenameID(StringRef Str);
1346
1347  /// \brief Add a line note to the line table for the FileID and offset
1348  /// specified by Loc.
1349  ///
1350  /// If FilenameID is -1, it is considered to be unspecified.
1351  void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID);
1352  void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID,
1353                   bool IsFileEntry, bool IsFileExit,
1354                   bool IsSystemHeader, bool IsExternCHeader);
1355
1356  /// \brief Determine if the source manager has a line table.
1357  bool hasLineTable() const { return LineTable != 0; }
1358
1359  /// \brief Retrieve the stored line table.
1360  LineTableInfo &getLineTable();
1361
1362  //===--------------------------------------------------------------------===//
1363  // Queries for performance analysis.
1364  //===--------------------------------------------------------------------===//
1365
1366  /// \brief Return the total amount of physical memory allocated by the
1367  /// ContentCache allocator.
1368  size_t getContentCacheSize() const {
1369    return ContentCacheAlloc.getTotalMemory();
1370  }
1371
1372  struct MemoryBufferSizes {
1373    const size_t malloc_bytes;
1374    const size_t mmap_bytes;
1375
1376    MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
1377      : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
1378  };
1379
1380  /// \brief Return the amount of memory used by memory buffers, breaking down
1381  /// by heap-backed versus mmap'ed memory.
1382  MemoryBufferSizes getMemoryBufferSizes() const;
1383
1384  /// \brief Return the amount of memory used for various side tables and
1385  /// data structures in the SourceManager.
1386  size_t getDataStructureSizes() const;
1387
1388  //===--------------------------------------------------------------------===//
1389  // Other miscellaneous methods.
1390  //===--------------------------------------------------------------------===//
1391
1392  /// \brief Get the source location for the given file:line:col triplet.
1393  ///
1394  /// If the source file is included multiple times, the source location will
1395  /// be based upon the first inclusion.
1396  SourceLocation translateFileLineCol(const FileEntry *SourceFile,
1397                                      unsigned Line, unsigned Col) const;
1398
1399  /// \brief Get the FileID for the given file.
1400  ///
1401  /// If the source file is included multiple times, the FileID will be the
1402  /// first inclusion.
1403  FileID translateFile(const FileEntry *SourceFile) const;
1404
1405  /// \brief Get the source location in \p FID for the given line:col.
1406  /// Returns null location if \p FID is not a file SLocEntry.
1407  SourceLocation translateLineCol(FileID FID,
1408                                  unsigned Line, unsigned Col) const;
1409
1410  /// \brief If \p Loc points inside a function macro argument, the returned
1411  /// location will be the macro location in which the argument was expanded.
1412  /// If a macro argument is used multiple times, the expanded location will
1413  /// be at the first expansion of the argument.
1414  /// e.g.
1415  ///   MY_MACRO(foo);
1416  ///             ^
1417  /// Passing a file location pointing at 'foo', will yield a macro location
1418  /// where 'foo' was expanded into.
1419  SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const;
1420
1421  /// \brief Determines the order of 2 source locations in the translation unit.
1422  ///
1423  /// \returns true if LHS source location comes before RHS, false otherwise.
1424  bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const;
1425
1426  /// \brief Determines the order of 2 source locations in the "source location
1427  /// address space".
1428  bool isBeforeInSLocAddrSpace(SourceLocation LHS, SourceLocation RHS) const {
1429    return isBeforeInSLocAddrSpace(LHS, RHS.getOffset());
1430  }
1431
1432  /// \brief Determines the order of a source location and a source location
1433  /// offset in the "source location address space".
1434  ///
1435  /// Note that we always consider source locations loaded from
1436  bool isBeforeInSLocAddrSpace(SourceLocation LHS, unsigned RHS) const {
1437    unsigned LHSOffset = LHS.getOffset();
1438    bool LHSLoaded = LHSOffset >= CurrentLoadedOffset;
1439    bool RHSLoaded = RHS >= CurrentLoadedOffset;
1440    if (LHSLoaded == RHSLoaded)
1441      return LHSOffset < RHS;
1442
1443    return LHSLoaded;
1444  }
1445
1446  // Iterators over FileInfos.
1447  typedef llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>
1448      ::const_iterator fileinfo_iterator;
1449  fileinfo_iterator fileinfo_begin() const { return FileInfos.begin(); }
1450  fileinfo_iterator fileinfo_end() const { return FileInfos.end(); }
1451  bool hasFileInfo(const FileEntry *File) const {
1452    return FileInfos.find(File) != FileInfos.end();
1453  }
1454
1455  /// \brief Print statistics to stderr.
1456  ///
1457  void PrintStats() const;
1458
1459  /// \brief Get the number of local SLocEntries we have.
1460  unsigned local_sloc_entry_size() const { return LocalSLocEntryTable.size(); }
1461
1462  /// \brief Get a local SLocEntry. This is exposed for indexing.
1463  const SrcMgr::SLocEntry &getLocalSLocEntry(unsigned Index,
1464                                             bool *Invalid = 0) const {
1465    assert(Index < LocalSLocEntryTable.size() && "Invalid index");
1466    return LocalSLocEntryTable[Index];
1467  }
1468
1469  /// \brief Get the number of loaded SLocEntries we have.
1470  unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.size();}
1471
1472  /// \brief Get a loaded SLocEntry. This is exposed for indexing.
1473  const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
1474                                              bool *Invalid = 0) const {
1475    assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
1476    if (SLocEntryLoaded[Index])
1477      return LoadedSLocEntryTable[Index];
1478    return loadSLocEntry(Index, Invalid);
1479  }
1480
1481  const SrcMgr::SLocEntry &getSLocEntry(FileID FID, bool *Invalid = 0) const {
1482    if (FID.ID == 0 || FID.ID == -1) {
1483      if (Invalid) *Invalid = true;
1484      return LocalSLocEntryTable[0];
1485    }
1486    return getSLocEntryByID(FID.ID);
1487  }
1488
1489  unsigned getNextLocalOffset() const { return NextLocalOffset; }
1490
1491  void setExternalSLocEntrySource(ExternalSLocEntrySource *Source) {
1492    assert(LoadedSLocEntryTable.empty() &&
1493           "Invalidating existing loaded entries");
1494    ExternalSLocEntries = Source;
1495  }
1496
1497  /// \brief Allocate a number of loaded SLocEntries, which will be actually
1498  /// loaded on demand from the external source.
1499  ///
1500  /// NumSLocEntries will be allocated, which occupy a total of TotalSize space
1501  /// in the global source view. The lowest ID and the base offset of the
1502  /// entries will be returned.
1503  std::pair<int, unsigned>
1504  AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
1505
1506  /// \brief Returns true if \p Loc came from a PCH/Module.
1507  bool isLoadedSourceLocation(SourceLocation Loc) const {
1508    return Loc.getOffset() >= CurrentLoadedOffset;
1509  }
1510
1511  /// \brief Returns true if \p Loc did not come from a PCH/Module.
1512  bool isLocalSourceLocation(SourceLocation Loc) const {
1513    return Loc.getOffset() < NextLocalOffset;
1514  }
1515
1516  /// \brief Returns true if \p FID came from a PCH/Module.
1517  bool isLoadedFileID(FileID FID) const {
1518    assert(FID.ID != -1 && "Using FileID sentinel value");
1519    return FID.ID < 0;
1520  }
1521
1522  /// \brief Returns true if \p FID did not come from a PCH/Module.
1523  bool isLocalFileID(FileID FID) const {
1524    return !isLoadedFileID(FID);
1525  }
1526
1527  /// Gets the location of the immediate macro caller, one level up the stack
1528  /// toward the initial macro typed into the source.
1529  SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const {
1530    if (!Loc.isMacroID()) return Loc;
1531
1532    // When we have the location of (part of) an expanded parameter, its
1533    // spelling location points to the argument as expanded in the macro call,
1534    // and therefore is used to locate the macro caller.
1535    if (isMacroArgExpansion(Loc))
1536      return getImmediateSpellingLoc(Loc);
1537
1538    // Otherwise, the caller of the macro is located where this macro is
1539    // expanded (while the spelling is part of the macro definition).
1540    return getImmediateExpansionRange(Loc).first;
1541  }
1542
1543private:
1544  const llvm::MemoryBuffer *getFakeBufferForRecovery() const;
1545  const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
1546
1547  const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) const;
1548
1549  /// \brief Get the entry with the given unwrapped FileID.
1550  const SrcMgr::SLocEntry &getSLocEntryByID(int ID) const {
1551    assert(ID != -1 && "Using FileID sentinel value");
1552    if (ID < 0)
1553      return getLoadedSLocEntryByID(ID);
1554    return getLocalSLocEntry(static_cast<unsigned>(ID));
1555  }
1556
1557  const SrcMgr::SLocEntry &getLoadedSLocEntryByID(int ID,
1558                                                  bool *Invalid = 0) const {
1559    return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
1560  }
1561
1562  /// Implements the common elements of storing an expansion info struct into
1563  /// the SLocEntry table and producing a source location that refers to it.
1564  SourceLocation createExpansionLocImpl(const SrcMgr::ExpansionInfo &Expansion,
1565                                        unsigned TokLength,
1566                                        int LoadedID = 0,
1567                                        unsigned LoadedOffset = 0);
1568
1569  /// \brief Return true if the specified FileID contains the
1570  /// specified SourceLocation offset.  This is a very hot method.
1571  inline bool isOffsetInFileID(FileID FID, unsigned SLocOffset) const {
1572    const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
1573    // If the entry is after the offset, it can't contain it.
1574    if (SLocOffset < Entry.getOffset()) return false;
1575
1576    // If this is the very last entry then it does.
1577    if (FID.ID == -2)
1578      return true;
1579
1580    // If it is the last local entry, then it does if the location is local.
1581    if (FID.ID+1 == static_cast<int>(LocalSLocEntryTable.size()))
1582      return SLocOffset < NextLocalOffset;
1583
1584    // Otherwise, the entry after it has to not include it. This works for both
1585    // local and loaded entries.
1586    return SLocOffset < getSLocEntryByID(FID.ID+1).getOffset();
1587  }
1588
1589  /// \brief Returns the previous in-order FileID or an invalid FileID if there
1590  /// is no previous one.
1591  FileID getPreviousFileID(FileID FID) const;
1592
1593  /// \brief Returns the next in-order FileID or an invalid FileID if there is
1594  /// no next one.
1595  FileID getNextFileID(FileID FID) const;
1596
1597  /// \brief Create a new fileID for the specified ContentCache and
1598  /// include position.
1599  ///
1600  /// This works regardless of whether the ContentCache corresponds to a
1601  /// file or some other input source.
1602  FileID createFileID(const SrcMgr::ContentCache* File,
1603                      SourceLocation IncludePos,
1604                      SrcMgr::CharacteristicKind DirCharacter,
1605                      int LoadedID, unsigned LoadedOffset);
1606
1607  const SrcMgr::ContentCache *
1608    getOrCreateContentCache(const FileEntry *SourceFile,
1609                            bool isSystemFile = false);
1610
1611  /// \brief Create a new ContentCache for the specified  memory buffer.
1612  const SrcMgr::ContentCache*
1613  createMemBufferContentCache(const llvm::MemoryBuffer *Buf);
1614
1615  FileID getFileIDSlow(unsigned SLocOffset) const;
1616  FileID getFileIDLocal(unsigned SLocOffset) const;
1617  FileID getFileIDLoaded(unsigned SLocOffset) const;
1618
1619  SourceLocation getExpansionLocSlowCase(SourceLocation Loc) const;
1620  SourceLocation getSpellingLocSlowCase(SourceLocation Loc) const;
1621  SourceLocation getFileLocSlowCase(SourceLocation Loc) const;
1622
1623  std::pair<FileID, unsigned>
1624  getDecomposedExpansionLocSlowCase(const SrcMgr::SLocEntry *E) const;
1625  std::pair<FileID, unsigned>
1626  getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
1627                                   unsigned Offset) const;
1628  void computeMacroArgsCache(MacroArgsMap *&MacroArgsCache, FileID FID) const;
1629  void associateFileChunkWithMacroArgExp(MacroArgsMap &MacroArgsCache,
1630                                         FileID FID,
1631                                         SourceLocation SpellLoc,
1632                                         SourceLocation ExpansionLoc,
1633                                         unsigned ExpansionLength) const;
1634  friend class ASTReader;
1635  friend class ASTWriter;
1636};
1637
1638/// \brief Comparison function object.
1639template<typename T>
1640class BeforeThanCompare;
1641
1642/// \brief Compare two source locations.
1643template<>
1644class BeforeThanCompare<SourceLocation> {
1645  SourceManager &SM;
1646
1647public:
1648  explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1649
1650  bool operator()(SourceLocation LHS, SourceLocation RHS) const {
1651    return SM.isBeforeInTranslationUnit(LHS, RHS);
1652  }
1653};
1654
1655/// \brief Compare two non-overlapping source ranges.
1656template<>
1657class BeforeThanCompare<SourceRange> {
1658  SourceManager &SM;
1659
1660public:
1661  explicit BeforeThanCompare(SourceManager &SM) : SM(SM) { }
1662
1663  bool operator()(SourceRange LHS, SourceRange RHS) {
1664    return SM.isBeforeInTranslationUnit(LHS.getBegin(), RHS.getBegin());
1665  }
1666};
1667
1668}  // end namespace clang
1669
1670
1671#endif
1672