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