Coverage Report

Created: 2020-09-19 12:23

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