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