Clang Project

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