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