-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathSourceManager.cpp
2417 lines (2095 loc) · 90.8 KB
/
SourceManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- SourceManager.cpp - Track and cache source files -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the SourceManager interface.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManagerInternals.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Capacity.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ConvertUTF.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
using namespace clang;
using namespace SrcMgr;
using llvm::MemoryBuffer;
//===----------------------------------------------------------------------===//
// SourceManager Helper Classes
//===----------------------------------------------------------------------===//
/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
unsigned ContentCache::getSizeBytesMapped() const {
return Buffer ? Buffer->getBufferSize() : 0;
}
/// Returns the kind of memory used to back the memory buffer for
/// this content cache. This is used for performance analysis.
llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
if (Buffer == nullptr) {
assert(0 && "Buffer should never be null");
return llvm::MemoryBuffer::MemoryBuffer_Malloc;
}
return Buffer->getBufferKind();
}
/// getSize - Returns the size of the content encapsulated by this ContentCache.
/// This can be the size of the source file or the size of an arbitrary
/// scratch buffer. If the ContentCache encapsulates a source file, that
/// file is not lazily brought in from disk to satisfy this query.
unsigned ContentCache::getSize() const {
return Buffer ? (unsigned)Buffer->getBufferSize()
: (unsigned)ContentsEntry->getSize();
}
const char *ContentCache::getInvalidBOM(StringRef BufStr) {
// If the buffer is valid, check to see if it has a UTF Byte Order Mark
// (BOM). We only support UTF-8 with and without a BOM right now. See
// http://en.wikipedia.org/wiki/Byte_order_mark for more information.
const char *InvalidBOM =
llvm::StringSwitch<const char *>(BufStr)
.StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
"UTF-32 (BE)")
.StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
"UTF-32 (LE)")
.StartsWith("\xFE\xFF", "UTF-16 (BE)")
.StartsWith("\xFF\xFE", "UTF-16 (LE)")
.StartsWith("\x2B\x2F\x76", "UTF-7")
.StartsWith("\xF7\x64\x4C", "UTF-1")
.StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
.StartsWith("\x0E\xFE\xFF", "SCSU")
.StartsWith("\xFB\xEE\x28", "BOCU-1")
.StartsWith("\x84\x31\x95\x33", "GB-18030")
.Default(nullptr);
return InvalidBOM;
}
// Check buffer is UTF16
bool ContentCache::checkBufUTF16(StringRef BufStr) {
const char *Result = llvm::StringSwitch<const char *>(BufStr)
.StartsWith("\xFE\xFF", "UTF-16 (BE)")
.StartsWith("\xFF\xFE", "UTF-16 (LE)")
.Default(nullptr);
if (Result) {
return true;
}
return false;
}
// Check buffer is UTF32
bool ContentCache::checkBufUTF32(StringRef BufStr) {
const char *Result =
llvm::StringSwitch<const char *>(BufStr)
.StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
"UTF-32 (BE)")
.StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
"UTF-32 (LE)")
.Default(nullptr);
if (Result) {
return true;
}
return false;
}
std::optional<llvm::MemoryBufferRef>
ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
SourceLocation Loc) const {
// Lazily create the Buffer for ContentCaches that wrap files. If we already
// computed it, just return what we have.
if (IsBufferInvalid)
return std::nullopt;
if (Buffer)
return Buffer->getMemBufferRef();
if (!ContentsEntry)
return std::nullopt;
// Start with the assumption that the buffer is invalid to simplify early
// return paths.
IsBufferInvalid = true;
auto BufferOrError = FM.getBufferForFile(*ContentsEntry, IsFileVolatile);
// If we were unable to open the file, then we are in an inconsistent
// situation where the content cache referenced a file which no longer
// exists. Most likely, we were using a stat cache with an invalid entry but
// the file could also have been removed during processing. Since we can't
// really deal with this situation, just create an empty buffer.
if (!BufferOrError) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
ContentsEntry->getName(),
BufferOrError.getError().message());
else
Diag.Report(Loc, diag::err_cannot_open_file)
<< ContentsEntry->getName() << BufferOrError.getError().message();
return std::nullopt;
}
Buffer = std::move(*BufferOrError);
// Check that the file's size fits in an 'unsigned' (with room for a
// past-the-end value). This is deeply regrettable, but various parts of
// Clang (including elsewhere in this file!) use 'unsigned' to represent file
// offsets, line numbers, string literal lengths, and so on, and fail
// miserably on large source files.
//
// Note: ContentsEntry could be a named pipe, in which case
// ContentsEntry::getSize() could have the wrong size. Use
// MemoryBuffer::getBufferSize() instead.
if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_file_too_large,
ContentsEntry->getName());
else
Diag.Report(Loc, diag::err_file_too_large)
<< ContentsEntry->getName();
return std::nullopt;
}
// Unless this is a named pipe (in which case we can handle a mismatch),
// check that the file's size is the same as in the file entry (which may
// have come from a stat cache).
if (!ContentsEntry->isNamedPipe() &&
Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
if (Diag.isDiagnosticInFlight())
Diag.SetDelayedDiagnostic(diag::err_file_modified,
ContentsEntry->getName());
else
Diag.Report(Loc, diag::err_file_modified)
<< ContentsEntry->getName();
return std::nullopt;
}
// If the buffer is valid, check to see if it has a UTF Byte Order Mark
// (BOM). We only support UTF-8 with and without a BOM right now. See
// http://en.wikipedia.org/wiki/Byte_order_mark for more information.
StringRef BufStr = Buffer->getBuffer();
const char *InvalidBOM = getInvalidBOM(BufStr);
auto moveBuffer = [this](const std::string &StrUtf8) {
auto NewBuf =
llvm::WritableMemoryBuffer::getNewUninitMemBuffer(StrUtf8.size());
if (NewBuf) {
memcpy(NewBuf->getBufferStart(), StrUtf8.data(), StrUtf8.size());
Buffer = std::move(NewBuf);
}
};
// [MSVC Compatibility] Trying to convert UTF16 to UTF8.
std::string StrUtf8;
if (InvalidBOM && checkBufUTF16(BufStr)) {
if (llvm::convertUTF16ToUTF8String(
llvm::makeArrayRef(BufStr.data(), BufStr.size()), StrUtf8)) {
moveBuffer(StrUtf8);
BufStr = Buffer->getBuffer();
// Verify it again.
InvalidBOM = getInvalidBOM(BufStr);
}
} else {
#ifdef _WIN32
// Trying to convert GBK to UTF8.
if (llvm::convertGBKToUTF8String(BufStr, StrUtf8)) {
moveBuffer(StrUtf8);
BufStr = Buffer->getBuffer();
// Verify it again.
InvalidBOM = getInvalidBOM(BufStr);
}
#endif
}
if (InvalidBOM) {
Diag.Report(Loc, diag::err_unsupported_bom)
<< InvalidBOM << ContentsEntry->getName();
return std::nullopt;
}
// Buffer has been validated.
IsBufferInvalid = false;
return Buffer->getMemBufferRef();
}
unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
if (IterBool.second)
FilenamesByID.push_back(&*IterBool.first);
return IterBool.first->second;
}
/// Add a line note to the line table that indicates that there is a \#line or
/// GNU line marker at the specified FID/Offset location which changes the
/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
/// change the presumed \#include stack. If it is 1, this is a file entry, if
/// it is 2 then this is a file exit. FileKind specifies whether this is a
/// system header or extern C system header.
void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
int FilenameID, unsigned EntryExit,
SrcMgr::CharacteristicKind FileKind) {
std::vector<LineEntry> &Entries = LineEntries[FID];
assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
"Adding line entries out of order!");
unsigned IncludeOffset = 0;
if (EntryExit == 1) {
// Push #include
IncludeOffset = Offset-1;
} else {
const auto *PrevEntry = Entries.empty() ? nullptr : &Entries.back();
if (EntryExit == 2) {
// Pop #include
assert(PrevEntry && PrevEntry->IncludeOffset &&
"PPDirectives should have caught case when popping empty include "
"stack");
PrevEntry = FindNearestLineEntry(FID, PrevEntry->IncludeOffset);
}
if (PrevEntry) {
IncludeOffset = PrevEntry->IncludeOffset;
if (FilenameID == -1) {
// An unspecified FilenameID means use the previous (or containing)
// filename if available, or the main source file otherwise.
FilenameID = PrevEntry->FilenameID;
}
}
}
Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
IncludeOffset));
}
/// FindNearestLineEntry - Find the line entry nearest to FID that is before
/// it. If there is no line entry before Offset in FID, return null.
const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
unsigned Offset) {
const std::vector<LineEntry> &Entries = LineEntries[FID];
assert(!Entries.empty() && "No #line entries for this FID after all!");
// It is very common for the query to be after the last #line, check this
// first.
if (Entries.back().FileOffset <= Offset)
return &Entries.back();
// Do a binary search to find the maximal element that is still before Offset.
std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
if (I == Entries.begin())
return nullptr;
return &*--I;
}
/// Add a new line entry that has already been encoded into
/// the internal representation of the line table.
void LineTableInfo::AddEntry(FileID FID,
const std::vector<LineEntry> &Entries) {
LineEntries[FID] = Entries;
}
/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
return getLineTable().getLineTableFilenameID(Name);
}
/// AddLineNote - Add a line note to the line table for the FileID and offset
/// specified by Loc. If FilenameID is -1, it is considered to be
/// unspecified.
void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
int FilenameID, bool IsFileEntry,
bool IsFileExit,
SrcMgr::CharacteristicKind FileKind) {
std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
bool Invalid = false;
const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
if (!Entry.isFile() || Invalid)
return;
const SrcMgr::FileInfo &FileInfo = Entry.getFile();
// Remember that this file has #line directives now if it doesn't already.
const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
(void) getLineTable();
unsigned EntryExit = 0;
if (IsFileEntry)
EntryExit = 1;
else if (IsFileExit)
EntryExit = 2;
LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
EntryExit, FileKind);
}
LineTableInfo &SourceManager::getLineTable() {
if (!LineTable)
LineTable.reset(new LineTableInfo());
return *LineTable;
}
//===----------------------------------------------------------------------===//
// Private 'Create' methods.
//===----------------------------------------------------------------------===//
SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
bool UserFilesAreVolatile)
: Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
clearIDTables();
Diag.setSourceManager(this);
}
SourceManager::~SourceManager() {
// Delete FileEntry objects corresponding to content caches. Since the actual
// content cache objects are bump pointer allocated, we just have to run the
// dtors, but we call the deallocate method for completeness.
for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
if (MemBufferInfos[i]) {
MemBufferInfos[i]->~ContentCache();
ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
}
}
for (auto I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
if (I->second) {
I->second->~ContentCache();
ContentCacheAlloc.Deallocate(I->second);
}
}
}
void SourceManager::clearIDTables() {
MainFileID = FileID();
LocalSLocEntryTable.clear();
LoadedSLocEntryTable.clear();
SLocEntryLoaded.clear();
SLocEntryOffsetLoaded.clear();
LastLineNoFileIDQuery = FileID();
LastLineNoContentCache = nullptr;
LastFileIDLookup = FileID();
if (LineTable)
LineTable->clear();
// Use up FileID #0 as an invalid expansion.
NextLocalOffset = 0;
CurrentLoadedOffset = MaxLoadedOffset;
createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
}
bool SourceManager::isMainFile(const FileEntry &SourceFile) {
assert(MainFileID.isValid() && "expected initialized SourceManager");
if (auto *FE = getFileEntryForID(MainFileID))
return FE->getUID() == SourceFile.getUID();
return false;
}
void SourceManager::initializeForReplay(const SourceManager &Old) {
assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
Clone->OrigEntry = Cache->OrigEntry;
Clone->ContentsEntry = Cache->ContentsEntry;
Clone->BufferOverridden = Cache->BufferOverridden;
Clone->IsFileVolatile = Cache->IsFileVolatile;
Clone->IsTransient = Cache->IsTransient;
Clone->setUnownedBuffer(Cache->getBufferIfLoaded());
return Clone;
};
// Ensure all SLocEntries are loaded from the external source.
for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; ++I)
if (!Old.SLocEntryLoaded[I])
Old.loadSLocEntry(I, nullptr);
// Inherit any content cache data from the old source manager.
for (auto &FileInfo : Old.FileInfos) {
SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
if (Slot)
continue;
Slot = CloneContentCache(FileInfo.second);
}
}
ContentCache &SourceManager::getOrCreateContentCache(FileEntryRef FileEnt,
bool isSystemFile) {
// Do we already have information about this file?
ContentCache *&Entry = FileInfos[FileEnt];
if (Entry)
return *Entry;
// Nope, create a new Cache entry.
Entry = ContentCacheAlloc.Allocate<ContentCache>();
if (OverriddenFilesInfo) {
// If the file contents are overridden with contents from another file,
// pass that file to ContentCache.
auto overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
if (overI == OverriddenFilesInfo->OverriddenFiles.end())
new (Entry) ContentCache(FileEnt);
else
new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
: overI->second,
overI->second);
} else {
new (Entry) ContentCache(FileEnt);
}
Entry->IsFileVolatile = UserFilesAreVolatile && !isSystemFile;
Entry->IsTransient = FilesAreTransient;
Entry->BufferOverridden |= FileEnt.isNamedPipe();
return *Entry;
}
/// Create a new ContentCache for the specified memory buffer.
/// This does no caching.
ContentCache &SourceManager::createMemBufferContentCache(
std::unique_ptr<llvm::MemoryBuffer> Buffer) {
// Add a new ContentCache to the MemBufferInfos list and return it.
ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
new (Entry) ContentCache();
MemBufferInfos.push_back(Entry);
Entry->setBuffer(std::move(Buffer));
return *Entry;
}
const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
bool *Invalid) const {
assert(!SLocEntryLoaded[Index]);
if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
if (Invalid)
*Invalid = true;
// If the file of the SLocEntry changed we could still have loaded it.
if (!SLocEntryLoaded[Index]) {
// Try to recover; create a SLocEntry so the rest of clang can handle it.
if (!FakeSLocEntryForRecovery)
FakeSLocEntryForRecovery = std::make_unique<SLocEntry>(SLocEntry::get(
0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(),
SrcMgr::C_User, "")));
return *FakeSLocEntryForRecovery;
}
}
return LoadedSLocEntryTable[Index];
}
std::pair<int, SourceLocation::UIntTy>
SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
SourceLocation::UIntTy TotalSize) {
assert(ExternalSLocEntries && "Don't have an external sloc source");
// Make sure we're not about to run out of source locations.
if (CurrentLoadedOffset < TotalSize ||
CurrentLoadedOffset - TotalSize < NextLocalOffset) {
return std::make_pair(0, 0);
}
LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
SLocEntryOffsetLoaded.resize(LoadedSLocEntryTable.size());
CurrentLoadedOffset -= TotalSize;
int BaseID = -int(LoadedSLocEntryTable.size()) - 1;
LoadedSLocEntryAllocBegin.push_back(FileID::get(BaseID));
return std::make_pair(BaseID, CurrentLoadedOffset);
}
/// As part of recovering from missing or changed content, produce a
/// fake, non-empty buffer.
llvm::MemoryBufferRef SourceManager::getFakeBufferForRecovery() const {
if (!FakeBufferForRecovery)
FakeBufferForRecovery =
llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
return *FakeBufferForRecovery;
}
/// As part of recovering from missing or changed content, produce a
/// fake content cache.
SrcMgr::ContentCache &SourceManager::getFakeContentCacheForRecovery() const {
if (!FakeContentCacheForRecovery) {
FakeContentCacheForRecovery = std::make_unique<SrcMgr::ContentCache>();
FakeContentCacheForRecovery->setUnownedBuffer(getFakeBufferForRecovery());
}
return *FakeContentCacheForRecovery;
}
/// Returns the previous in-order FileID or an invalid FileID if there
/// is no previous one.
FileID SourceManager::getPreviousFileID(FileID FID) const {
if (FID.isInvalid())
return FileID();
int ID = FID.ID;
if (ID == -1)
return FileID();
if (ID > 0) {
if (ID-1 == 0)
return FileID();
} else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
return FileID();
}
return FileID::get(ID-1);
}
/// Returns the next in-order FileID or an invalid FileID if there is
/// no next one.
FileID SourceManager::getNextFileID(FileID FID) const {
if (FID.isInvalid())
return FileID();
int ID = FID.ID;
if (ID > 0) {
if (unsigned(ID+1) >= local_sloc_entry_size())
return FileID();
} else if (ID+1 >= -1) {
return FileID();
}
return FileID::get(ID+1);
}
//===----------------------------------------------------------------------===//
// Methods to create new FileID's and macro expansions.
//===----------------------------------------------------------------------===//
/// Create a new FileID that represents the specified file
/// being \#included from the specified IncludePosition.
FileID SourceManager::createFileID(FileEntryRef SourceFile,
SourceLocation IncludePos,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile,
isSystem(FileCharacter));
// If this is a named pipe, immediately load the buffer to ensure subsequent
// calls to ContentCache::getSize() are accurate.
if (IR.ContentsEntry->isNamedPipe())
(void)IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
return createFileIDImpl(IR, SourceFile.getName(), IncludePos, FileCharacter,
LoadedID, LoadedOffset);
}
/// Create a new FileID that represents the specified memory buffer.
///
/// This does no caching of the buffer and takes ownership of the
/// MemoryBuffer, so only pass a MemoryBuffer to this once.
FileID SourceManager::createFileID(std::unique_ptr<llvm::MemoryBuffer> Buffer,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset,
SourceLocation IncludeLoc) {
StringRef Name = Buffer->getBufferIdentifier();
return createFileIDImpl(createMemBufferContentCache(std::move(Buffer)), Name,
IncludeLoc, FileCharacter, LoadedID, LoadedOffset);
}
/// Create a new FileID that represents the specified memory buffer.
///
/// This does not take ownership of the MemoryBuffer. The memory buffer must
/// outlive the SourceManager.
FileID SourceManager::createFileID(const llvm::MemoryBufferRef &Buffer,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset,
SourceLocation IncludeLoc) {
return createFileID(llvm::MemoryBuffer::getMemBuffer(Buffer), FileCharacter,
LoadedID, LoadedOffset, IncludeLoc);
}
/// Get the FileID for \p SourceFile if it exists. Otherwise, create a
/// new FileID for the \p SourceFile.
FileID
SourceManager::getOrCreateFileID(FileEntryRef SourceFile,
SrcMgr::CharacteristicKind FileCharacter) {
FileID ID = translateFile(SourceFile);
return ID.isValid() ? ID : createFileID(SourceFile, SourceLocation(),
FileCharacter);
}
/// createFileID - Create a new FileID for the specified ContentCache and
/// include position. This works regardless of whether the ContentCache
/// corresponds to a file or some other input source.
FileID SourceManager::createFileIDImpl(ContentCache &File, StringRef Filename,
SourceLocation IncludePos,
SrcMgr::CharacteristicKind FileCharacter,
int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
if (LoadedID < 0) {
assert(LoadedID != -1 && "Loading sentinel FileID");
unsigned Index = unsigned(-LoadedID) - 2;
assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
assert(!SLocEntryLoaded[Index] && "FileID already loaded");
LoadedSLocEntryTable[Index] = SLocEntry::get(
LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter, Filename));
SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
return FileID::get(LoadedID);
}
unsigned FileSize = File.getSize();
if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
Diag.Report(IncludePos, diag::err_sloc_space_too_large);
noteSLocAddressSpaceUsage(Diag);
return FileID();
}
LocalSLocEntryTable.push_back(
SLocEntry::get(NextLocalOffset,
FileInfo::get(IncludePos, File, FileCharacter, Filename)));
// We do a +1 here because we want a SourceLocation that means "the end of the
// file", e.g. for the "no newline at the end of the file" diagnostic.
NextLocalOffset += FileSize + 1;
// Set LastFileIDLookup to the newly created file. The next getFileID call is
// almost guaranteed to be from that file.
FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
return LastFileIDLookup = FID;
}
SourceLocation SourceManager::createMacroArgExpansionLoc(
SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length) {
ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
ExpansionLoc);
return createExpansionLocImpl(Info, Length);
}
SourceLocation SourceManager::createExpansionLoc(
SourceLocation SpellingLoc, SourceLocation ExpansionLocStart,
SourceLocation ExpansionLocEnd, unsigned Length,
bool ExpansionIsTokenRange, int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
ExpansionInfo Info = ExpansionInfo::create(
SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
return createExpansionLocImpl(Info, Length, LoadedID, LoadedOffset);
}
SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
SourceLocation TokenStart,
SourceLocation TokenEnd) {
assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
"token spans multiple files");
return createExpansionLocImpl(
ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
TokenEnd.getOffset() - TokenStart.getOffset());
}
SourceLocation
SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
unsigned Length, int LoadedID,
SourceLocation::UIntTy LoadedOffset) {
if (LoadedID < 0) {
assert(LoadedID != -1 && "Loading sentinel FileID");
unsigned Index = unsigned(-LoadedID) - 2;
assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
assert(!SLocEntryLoaded[Index] && "FileID already loaded");
LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
SLocEntryLoaded[Index] = SLocEntryOffsetLoaded[Index] = true;
return SourceLocation::getMacroLoc(LoadedOffset);
}
LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
#ifndef _WIN32
if (NextLocalOffset + Length + 1 <= NextLocalOffset ||
NextLocalOffset + Length + 1 > CurrentLoadedOffset) {
Diag.Report(SourceLocation(), diag::err_sloc_space_too_large);
// FIXME: call `noteSLocAddressSpaceUsage` to report details to users and
// use a source location from `Info` to point at an error.
// Currently, both cause Clang to run indefinitely, this needs to be fixed.
// FIXME: return an error instead of crashing. Returning invalid source
// locations causes compiler to run indefinitely.
llvm::report_fatal_error("ran out of source locations");
}
#endif
// See createFileID for that +1.
NextLocalOffset += Length + 1;
return SourceLocation::getMacroLoc(NextLocalOffset - (Length + 1));
}
std::optional<llvm::MemoryBufferRef>
SourceManager::getMemoryBufferForFileOrNone(FileEntryRef File) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(File);
return IR.getBufferOrNone(Diag, getFileManager(), SourceLocation());
}
void SourceManager::overrideFileContents(
FileEntryRef SourceFile, std::unique_ptr<llvm::MemoryBuffer> Buffer) {
SrcMgr::ContentCache &IR = getOrCreateContentCache(SourceFile);
IR.setBuffer(std::move(Buffer));
IR.BufferOverridden = true;
getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
}
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
FileEntryRef NewFile) {
assert(SourceFile->getSize() == NewFile.getSize() &&
"Different sizes, use the FileManager to create a virtual file with "
"the correct size");
assert(FileInfos.find_as(SourceFile) == FileInfos.end() &&
"This function should be called at the initialization stage, before "
"any parsing occurs.");
// FileEntryRef is not default-constructible.
auto Pair = getOverriddenFilesInfo().OverriddenFiles.insert(
std::make_pair(SourceFile, NewFile));
if (!Pair.second)
Pair.first->second = NewFile;
}
OptionalFileEntryRef
SourceManager::bypassFileContentsOverride(FileEntryRef File) {
assert(isFileOverridden(&File.getFileEntry()));
OptionalFileEntryRef BypassFile = FileMgr.getBypassFile(File);
// If the file can't be found in the FS, give up.
if (!BypassFile)
return std::nullopt;
(void)getOrCreateContentCache(*BypassFile);
return BypassFile;
}
void SourceManager::setFileIsTransient(FileEntryRef File) {
getOrCreateContentCache(File).IsTransient = true;
}
std::optional<StringRef>
SourceManager::getNonBuiltinFilenameForID(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
if (Entry->getFile().getContentCache().OrigEntry)
return Entry->getFile().getName();
return std::nullopt;
}
StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
auto B = getBufferDataOrNone(FID);
if (Invalid)
*Invalid = !B;
return B ? *B : "<<<<<INVALID SOURCE LOCATION>>>>>";
}
std::optional<StringRef>
SourceManager::getBufferDataIfLoaded(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
return Entry->getFile().getContentCache().getBufferDataIfLoaded();
return std::nullopt;
}
std::optional<StringRef> SourceManager::getBufferDataOrNone(FileID FID) const {
if (const SrcMgr::SLocEntry *Entry = getSLocEntryForFile(FID))
if (auto B = Entry->getFile().getContentCache().getBufferOrNone(
Diag, getFileManager(), SourceLocation()))
return B->getBuffer();
return std::nullopt;
}
//===----------------------------------------------------------------------===//
// SourceLocation manipulation methods.
//===----------------------------------------------------------------------===//
/// Return the FileID for a SourceLocation.
///
/// This is the cache-miss path of getFileID. Not as hot as that function, but
/// still very important. It is responsible for finding the entry in the
/// SLocEntry tables that contains the specified location.
FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
if (!SLocOffset)
return FileID::get(0);
// Now it is time to search for the correct file. See where the SLocOffset
// sits in the global view and consult local or loaded buffers for it.
if (SLocOffset < NextLocalOffset)
return getFileIDLocal(SLocOffset);
return getFileIDLoaded(SLocOffset);
}
/// Return the FileID for a SourceLocation with a low offset.
///
/// This function knows that the SourceLocation is in a local buffer, not a
/// loaded one.
FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
assert(SLocOffset < NextLocalOffset && "Bad function choice");
// After the first and second level caches, I see two common sorts of
// behavior: 1) a lot of searched FileID's are "near" the cached file
// location or are "near" the cached expansion location. 2) others are just
// completely random and may be a very long way away.
//
// To handle this, we do a linear search for up to 8 steps to catch #1 quickly
// then we fall back to a less cache efficient, but more scalable, binary
// search to find the location.
// See if this is near the file point - worst case we start scanning from the
// most newly created FileID.
// LessIndex - This is the lower bound of the range that we're searching.
// We know that the offset corresponding to the FileID is less than
// SLocOffset.
unsigned LessIndex = 0;
// upper bound of the search range.
unsigned GreaterIndex = LocalSLocEntryTable.size();
if (LastFileIDLookup.ID >= 0) {
// Use the LastFileIDLookup to prune the search space.
if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
LessIndex = LastFileIDLookup.ID;
else
GreaterIndex = LastFileIDLookup.ID;
}
// Find the FileID that contains this.
unsigned NumProbes = 0;
while (true) {
--GreaterIndex;
assert(GreaterIndex < LocalSLocEntryTable.size());
if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
FileID Res = FileID::get(int(GreaterIndex));
// Remember it. We have good locality across FileID lookups.
LastFileIDLookup = Res;
NumLinearScans += NumProbes+1;
return Res;
}
if (++NumProbes == 8)
break;
}
NumProbes = 0;
while (true) {
unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
SourceLocation::UIntTy MidOffset =
getLocalSLocEntry(MiddleIndex).getOffset();
++NumProbes;
// If the offset of the midpoint is too large, chop the high side of the
// range to the midpoint.
if (MidOffset > SLocOffset) {
GreaterIndex = MiddleIndex;
continue;
}
// If the middle index contains the value, succeed and return.
if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
FileID Res = FileID::get(MiddleIndex);
// Remember it. We have good locality across FileID lookups.
LastFileIDLookup = Res;
NumBinaryProbes += NumProbes;
return Res;
}
// Otherwise, move the low-side up to the middle index.
LessIndex = MiddleIndex;
}
}
/// Return the FileID for a SourceLocation with a high offset.
///
/// This function knows that the SourceLocation is in a loaded buffer, not a
/// local one.
FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
if (SLocOffset < CurrentLoadedOffset) {
assert(0 && "Invalid SLocOffset or bad function choice");
return FileID();
}
return FileID::get(ExternalSLocEntries->getSLocEntryID(SLocOffset));
}
SourceLocation SourceManager::
getExpansionLocSlowCase(SourceLocation Loc) const {
do {
// Note: If Loc indicates an offset into a token that came from a macro
// expansion (e.g. the 5th character of the token) we do not want to add
// this offset when going to the expansion location. The expansion
// location is the macro invocation, which the offset has nothing to do
// with. This is unlike when we get the spelling loc, because the offset
// directly correspond to the token whose spelling we're inspecting.
Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
} while (!Loc.isFileID());
return Loc;
}
SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
do {
std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Loc = Loc.getLocWithOffset(LocInfo.second);
} while (!Loc.isFileID());
return Loc;
}
SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
do {
if (isMacroArgExpansion(Loc))
Loc = getImmediateSpellingLoc(Loc);
else
Loc = getImmediateExpansionRange(Loc).getBegin();
} while (!Loc.isFileID());
return Loc;
}
std::pair<FileID, unsigned>
SourceManager::getDecomposedExpansionLocSlowCase(
const SrcMgr::SLocEntry *E) const {
// If this is an expansion record, walk through all the expansion points.
FileID FID;
SourceLocation Loc;
unsigned Offset;
do {
Loc = E->getExpansion().getExpansionLocStart();
FID = getFileID(Loc);
E = &getSLocEntry(FID);
Offset = Loc.getOffset()-E->getOffset();
} while (!Loc.isFileID());
return std::make_pair(FID, Offset);
}
std::pair<FileID, unsigned>
SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
unsigned Offset) const {
// If this is an expansion record, walk through all the expansion points.
FileID FID;
SourceLocation Loc;
do {
Loc = E->getExpansion().getSpellingLoc();
Loc = Loc.getLocWithOffset(Offset);
FID = getFileID(Loc);
E = &getSLocEntry(FID);
Offset = Loc.getOffset()-E->getOffset();