Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Basic/SourceManager.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SourceManager.cpp - Track and cache source files -------------------===//
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
//  This file implements the SourceManager interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/SourceManager.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/FileManager.h"
16
#include "clang/Basic/LLVM.h"
17
#include "clang/Basic/SourceLocation.h"
18
#include "clang/Basic/SourceManagerInternals.h"
19
#include "llvm/ADT/DenseMap.h"
20
#include "llvm/ADT/Optional.h"
21
#include "llvm/ADT/None.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/StringSwitch.h"
25
#include "llvm/ADT/StringRef.h"
26
#include "llvm/Support/Allocator.h"
27
#include "llvm/Support/Capacity.h"
28
#include "llvm/Support/Compiler.h"
29
#include "llvm/Support/ErrorHandling.h"
30
#include "llvm/Support/FileSystem.h"
31
#include "llvm/Support/MathExtras.h"
32
#include "llvm/Support/MemoryBuffer.h"
33
#include "llvm/Support/Path.h"
34
#include "llvm/Support/raw_ostream.h"
35
#include <algorithm>
36
#include <cassert>
37
#include <cstddef>
38
#include <cstdint>
39
#include <memory>
40
#include <tuple>
41
#include <utility>
42
#include <vector>
43
44
using namespace clang;
45
using namespace SrcMgr;
46
using llvm::MemoryBuffer;
47
48
//===----------------------------------------------------------------------===//
49
// SourceManager Helper Classes
50
//===----------------------------------------------------------------------===//
51
52
147k
ContentCache::~ContentCache() {
53
147k
  if (shouldFreeBuffer())
54
146k
    delete Buffer.getPointer();
55
147k
}
56
57
/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
58
/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
59
7
unsigned ContentCache::getSizeBytesMapped() const {
60
7
  return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 
00
;
61
7
}
62
63
/// Returns the kind of memory used to back the memory buffer for
64
/// this content cache.  This is used for performance analysis.
65
1
llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
66
1
  assert(Buffer.getPointer());
67
1
68
1
  // Should be unreachable, but keep for sanity.
69
1
  if (!Buffer.getPointer())
70
0
    return llvm::MemoryBuffer::MemoryBuffer_Malloc;
71
1
72
1
  const llvm::MemoryBuffer *buf = Buffer.getPointer();
73
1
  return buf->getBufferKind();
74
1
}
75
76
/// getSize - Returns the size of the content encapsulated by this ContentCache.
77
///  This can be the size of the source file or the size of an arbitrary
78
///  scratch buffer.  If the ContentCache encapsulates a source file, that
79
///  file is not lazily brought in from disk to satisfy this query.
80
640k
unsigned ContentCache::getSize() const {
81
640k
  return Buffer.getPointer() ? 
(unsigned) Buffer.getPointer()->getBufferSize()92.3k
82
640k
                             : 
(unsigned) ContentsEntry->getSize()548k
;
83
640k
}
84
85
75.3k
void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
86
75.3k
  if (B && 
B == Buffer.getPointer()75.3k
) {
87
0
    assert(0 && "Replacing with the same buffer");
88
0
    Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
89
0
    return;
90
0
  }
91
75.3k
92
75.3k
  if (shouldFreeBuffer())
93
75.2k
    delete Buffer.getPointer();
94
75.3k
  Buffer.setPointer(B);
95
75.3k
  Buffer.setInt((B && 
DoNotFree75.3k
) ?
DoNotFreeFlag513
:
074.8k
);
96
75.3k
}
97
98
const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
99
                                                  const SourceManager &SM,
100
                                                  SourceLocation Loc,
101
65.1M
                                                  bool *Invalid) const {
102
65.1M
  // Lazily create the Buffer for ContentCaches that wrap files.  If we already
103
65.1M
  // computed it, just return what we have.
104
65.1M
  if (Buffer.getPointer() || 
!ContentsEntry546k
) {
105
64.5M
    if (Invalid)
106
62.1M
      *Invalid = isBufferInvalid();
107
64.5M
108
64.5M
    return Buffer.getPointer();
109
64.5M
  }
110
546k
111
546k
  // Check that the file's size fits in an 'unsigned' (with room for a
112
546k
  // past-the-end value). This is deeply regrettable, but various parts of
113
546k
  // Clang (including elsewhere in this file!) use 'unsigned' to represent file
114
546k
  // offsets, line numbers, string literal lengths, and so on, and fail
115
546k
  // miserably on large source files.
116
546k
  if ((uint64_t)ContentsEntry->getSize() >=
117
546k
      std::numeric_limits<unsigned>::max()) {
118
0
    // We can't make a memory buffer of the required size, so just make a small
119
0
    // one. We should never hit a situation where we've already parsed to a
120
0
    // later offset of the file, so it shouldn't matter that the buffer is
121
0
    // smaller than the file.
122
0
    Buffer.setPointer(
123
0
        llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
124
0
            .release());
125
0
    if (Diag.isDiagnosticInFlight())
126
0
      Diag.SetDelayedDiagnostic(diag::err_file_too_large,
127
0
                                ContentsEntry->getName());
128
0
    else
129
0
      Diag.Report(Loc, diag::err_file_too_large)
130
0
        << ContentsEntry->getName();
131
0
132
0
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
133
0
    if (Invalid) *Invalid = true;
134
0
    return Buffer.getPointer();
135
0
  }
136
546k
137
546k
  bool isVolatile = SM.userFilesAreVolatile() && 
!IsSystemFile1.99k
;
138
546k
  auto BufferOrError =
139
546k
      SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
140
546k
141
546k
  // If we were unable to open the file, then we are in an inconsistent
142
546k
  // situation where the content cache referenced a file which no longer
143
546k
  // exists. Most likely, we were using a stat cache with an invalid entry but
144
546k
  // the file could also have been removed during processing. Since we can't
145
546k
  // really deal with this situation, just create an empty buffer.
146
546k
  //
147
546k
  // FIXME: This is definitely not ideal, but our immediate clients can't
148
546k
  // currently handle returning a null entry here. Ideally we should detect
149
546k
  // that we are in an inconsistent situation and error out as quickly as
150
546k
  // possible.
151
546k
  if (!BufferOrError) {
152
0
    StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
153
0
    auto BackupBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
154
0
        ContentsEntry->getSize(), "<invalid>");
155
0
    char *Ptr = BackupBuffer->getBufferStart();
156
0
    for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
157
0
      Ptr[i] = FillStr[i % FillStr.size()];
158
0
    Buffer.setPointer(BackupBuffer.release());
159
0
160
0
    if (Diag.isDiagnosticInFlight())
161
0
      Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
162
0
                                ContentsEntry->getName(),
163
0
                                BufferOrError.getError().message());
164
0
    else
165
0
      Diag.Report(Loc, diag::err_cannot_open_file)
166
0
          << ContentsEntry->getName() << BufferOrError.getError().message();
167
0
168
0
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
169
0
170
0
    if (Invalid) *Invalid = true;
171
0
    return Buffer.getPointer();
172
0
  }
173
546k
174
546k
  Buffer.setPointer(BufferOrError->release());
175
546k
176
546k
  // Check that the file's size is the same as in the file entry (which may
177
546k
  // have come from a stat cache).
178
546k
  if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
179
0
    if (Diag.isDiagnosticInFlight())
180
0
      Diag.SetDelayedDiagnostic(diag::err_file_modified,
181
0
                                ContentsEntry->getName());
182
0
    else
183
0
      Diag.Report(Loc, diag::err_file_modified)
184
0
        << ContentsEntry->getName();
185
0
186
0
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
187
0
    if (Invalid) *Invalid = true;
188
0
    return Buffer.getPointer();
189
0
  }
190
546k
191
546k
  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
192
546k
  // (BOM).  We only support UTF-8 with and without a BOM right now.  See
193
546k
  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
194
546k
  StringRef BufStr = Buffer.getPointer()->getBuffer();
195
546k
  const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
196
546k
    .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
197
546k
                                                  "UTF-32 (BE)")
198
546k
    .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
199
546k
                                                  "UTF-32 (LE)")
200
546k
    .StartsWith("\xFE\xFF", "UTF-16 (BE)")
201
546k
    .StartsWith("\xFF\xFE", "UTF-16 (LE)")
202
546k
    .StartsWith("\x2B\x2F\x76", "UTF-7")
203
546k
    .StartsWith("\xF7\x64\x4C", "UTF-1")
204
546k
    .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
205
546k
    .StartsWith("\x0E\xFE\xFF", "SCSU")
206
546k
    .StartsWith("\xFB\xEE\x28", "BOCU-1")
207
546k
    .StartsWith("\x84\x31\x95\x33", "GB-18030")
208
546k
    .Default(nullptr);
209
546k
210
546k
  if (InvalidBOM) {
211
1
    Diag.Report(Loc, diag::err_unsupported_bom)
212
1
      << InvalidBOM << ContentsEntry->getName();
213
1
    Buffer.setInt(Buffer.getInt() | InvalidFlag);
214
1
  }
215
546k
216
546k
  if (Invalid)
217
543k
    *Invalid = isBufferInvalid();
218
546k
219
546k
  return Buffer.getPointer();
220
546k
}
221
222
164k
unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
223
164k
  auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
224
164k
  if (IterBool.second)
225
117k
    FilenamesByID.push_back(&*IterBool.first);
226
164k
  return IterBool.first->second;
227
164k
}
228
229
/// Add a line note to the line table that indicates that there is a \#line or
230
/// GNU line marker at the specified FID/Offset location which changes the
231
/// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
232
/// change the presumed \#include stack.  If it is 1, this is a file entry, if
233
/// it is 2 then this is a file exit. FileKind specifies whether this is a
234
/// system header or extern C system header.
235
void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
236
                                int FilenameID, unsigned EntryExit,
237
153k
                                SrcMgr::CharacteristicKind FileKind) {
238
153k
  std::vector<LineEntry> &Entries = LineEntries[FID];
239
153k
240
153k
  // An unspecified FilenameID means use the last filename if available, or the
241
153k
  // main source file otherwise.
242
153k
  if (FilenameID == -1 && 
!Entries.empty()1.45k
)
243
1.32k
    FilenameID = Entries.back().FilenameID;
244
153k
245
153k
  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
246
153k
         "Adding line entries out of order!");
247
153k
248
153k
  unsigned IncludeOffset = 0;
249
153k
  if (EntryExit == 0) {  // No #include stack change.
250
71.4k
    IncludeOffset = Entries.empty() ? 
069.3k
:
Entries.back().IncludeOffset2.11k
;
251
82.0k
  } else if (EntryExit == 1) {
252
41.0k
    IncludeOffset = Offset-1;
253
41.0k
  } else 
if (41.0k
EntryExit == 241.0k
) {
254
41.0k
    assert(!Entries.empty() && Entries.back().IncludeOffset &&
255
41.0k
       "PPDirectives should have caught case when popping empty include stack");
256
41.0k
257
41.0k
    // Get the include loc of the last entries' include loc as our include loc.
258
41.0k
    IncludeOffset = 0;
259
41.0k
    if (const LineEntry *PrevEntry =
260
40.9k
          FindNearestLineEntry(FID, Entries.back().IncludeOffset))
261
40.9k
      IncludeOffset = PrevEntry->IncludeOffset;
262
41.0k
  }
263
153k
264
153k
  Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
265
153k
                                   IncludeOffset));
266
153k
}
267
268
/// FindNearestLineEntry - Find the line entry nearest to FID that is before
269
/// it.  If there is no line entry before Offset in FID, return null.
270
const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
271
40.0M
                                                     unsigned Offset) {
272
40.0M
  const std::vector<LineEntry> &Entries = LineEntries[FID];
273
40.0M
  assert(!Entries.empty() && "No #line entries for this FID after all!");
274
40.0M
275
40.0M
  // It is very common for the query to be after the last #line, check this
276
40.0M
  // first.
277
40.0M
  if (Entries.back().FileOffset <= Offset)
278
39.9M
    return &Entries.back();
279
57.3k
280
57.3k
  // Do a binary search to find the maximal element that is still before Offset.
281
57.3k
  std::vector<LineEntry>::const_iterator I = llvm::upper_bound(Entries, Offset);
282
57.3k
  if (I == Entries.begin())
283
3.13k
    return nullptr;
284
54.2k
  return &*--I;
285
54.2k
}
286
287
/// Add a new line entry that has already been encoded into
288
/// the internal representation of the line table.
289
void LineTableInfo::AddEntry(FileID FID,
290
6.03k
                             const std::vector<LineEntry> &Entries) {
291
6.03k
  LineEntries[FID] = Entries;
292
6.03k
}
293
294
/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
295
152k
unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
296
152k
  return getLineTable().getLineTableFilenameID(Name);
297
152k
}
298
299
/// AddLineNote - Add a line note to the line table for the FileID and offset
300
/// specified by Loc.  If FilenameID is -1, it is considered to be
301
/// unspecified.
302
void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
303
                                int FilenameID, bool IsFileEntry,
304
                                bool IsFileExit,
305
153k
                                SrcMgr::CharacteristicKind FileKind) {
306
153k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
307
153k
308
153k
  bool Invalid = false;
309
153k
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
310
153k
  if (!Entry.isFile() || Invalid)
311
0
    return;
312
153k
313
153k
  const SrcMgr::FileInfo &FileInfo = Entry.getFile();
314
153k
315
153k
  // Remember that this file has #line directives now if it doesn't already.
316
153k
  const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
317
153k
318
153k
  (void) getLineTable();
319
153k
320
153k
  unsigned EntryExit = 0;
321
153k
  if (IsFileEntry)
322
41.0k
    EntryExit = 1;
323
112k
  else if (IsFileExit)
324
41.0k
    EntryExit = 2;
325
153k
326
153k
  LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
327
153k
                         EntryExit, FileKind);
328
153k
}
329
330
315k
LineTableInfo &SourceManager::getLineTable() {
331
315k
  if (!LineTable)
332
43.3k
    LineTable.reset(new LineTableInfo());
333
315k
  return *LineTable;
334
315k
}
335
336
//===----------------------------------------------------------------------===//
337
// Private 'Create' methods.
338
//===----------------------------------------------------------------------===//
339
340
SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
341
                             bool UserFilesAreVolatile)
342
92.3k
  : Diag(Diag), FileMgr(FileMgr), UserFilesAreVolatile(UserFilesAreVolatile) {
343
92.3k
  clearIDTables();
344
92.3k
  Diag.setSourceManager(this);
345
92.3k
}
346
347
77.9k
SourceManager::~SourceManager() {
348
77.9k
  // Delete FileEntry objects corresponding to content caches.  Since the actual
349
77.9k
  // content cache objects are bump pointer allocated, we just have to run the
350
77.9k
  // dtors, but we call the deallocate method for completeness.
351
122k
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i44.0k
) {
352
44.0k
    if (MemBufferInfos[i]) {
353
44.0k
      MemBufferInfos[i]->~ContentCache();
354
44.0k
      ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
355
44.0k
    }
356
44.0k
  }
357
77.9k
  for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
358
181k
       I = FileInfos.begin(), E = FileInfos.end(); I != E; 
++I103k
) {
359
103k
    if (I->second) {
360
103k
      I->second->~ContentCache();
361
103k
      ContentCacheAlloc.Deallocate(I->second);
362
103k
    }
363
103k
  }
364
77.9k
}
365
366
97.1k
void SourceManager::clearIDTables() {
367
97.1k
  MainFileID = FileID();
368
97.1k
  LocalSLocEntryTable.clear();
369
97.1k
  LoadedSLocEntryTable.clear();
370
97.1k
  SLocEntryLoaded.clear();
371
97.1k
  LastLineNoFileIDQuery = FileID();
372
97.1k
  LastLineNoContentCache = nullptr;
373
97.1k
  LastFileIDLookup = FileID();
374
97.1k
375
97.1k
  if (LineTable)
376
33
    LineTable->clear();
377
97.1k
378
97.1k
  // Use up FileID #0 as an invalid expansion.
379
97.1k
  NextLocalOffset = 0;
380
97.1k
  CurrentLoadedOffset = MaxLoadedOffset;
381
97.1k
  createExpansionLoc(SourceLocation(), SourceLocation(), SourceLocation(), 1);
382
97.1k
}
383
384
15
void SourceManager::initializeForReplay(const SourceManager &Old) {
385
15
  assert(MainFileID.isInvalid() && "expected uninitialized SourceManager");
386
15
387
52
  auto CloneContentCache = [&](const ContentCache *Cache) -> ContentCache * {
388
52
    auto *Clone = new (ContentCacheAlloc.Allocate<ContentCache>()) ContentCache;
389
52
    Clone->OrigEntry = Cache->OrigEntry;
390
52
    Clone->ContentsEntry = Cache->ContentsEntry;
391
52
    Clone->BufferOverridden = Cache->BufferOverridden;
392
52
    Clone->IsSystemFile = Cache->IsSystemFile;
393
52
    Clone->IsTransient = Cache->IsTransient;
394
52
    Clone->replaceBuffer(Cache->getRawBuffer(), /*DoNotFree*/true);
395
52
    return Clone;
396
52
  };
397
15
398
15
  // Ensure all SLocEntries are loaded from the external source.
399
142
  for (unsigned I = 0, N = Old.LoadedSLocEntryTable.size(); I != N; 
++I127
)
400
127
    if (!Old.SLocEntryLoaded[I])
401
102
      Old.loadSLocEntry(I, nullptr);
402
15
403
15
  // Inherit any content cache data from the old source manager.
404
52
  for (auto &FileInfo : Old.FileInfos) {
405
52
    SrcMgr::ContentCache *&Slot = FileInfos[FileInfo.first];
406
52
    if (Slot)
407
0
      continue;
408
52
    Slot = CloneContentCache(FileInfo.second);
409
52
  }
410
15
}
411
412
/// getOrCreateContentCache - Create or return a cached ContentCache for the
413
/// specified file.
414
const ContentCache *
415
SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
416
587k
                                       bool isSystemFile) {
417
587k
  assert(FileEnt && "Didn't specify a file entry to use?");
418
587k
419
587k
  // Do we already have information about this file?
420
587k
  ContentCache *&Entry = FileInfos[FileEnt];
421
587k
  if (Entry) 
return Entry36.0k
;
422
551k
423
551k
  // Nope, create a new Cache entry.
424
551k
  Entry = ContentCacheAlloc.Allocate<ContentCache>();
425
551k
426
551k
  if (OverriddenFilesInfo) {
427
1.37k
    // If the file contents are overridden with contents from another file,
428
1.37k
    // pass that file to ContentCache.
429
1.37k
    llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
430
1.37k
        overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
431
1.37k
    if (overI == OverriddenFilesInfo->OverriddenFiles.end())
432
1.36k
      new (Entry) ContentCache(FileEnt);
433
10
    else
434
10
      new (Entry) ContentCache(OverridenFilesKeepOriginalName ? 
FileEnt8
435
10
                                                              : 
overI->second2
,
436
10
                               overI->second);
437
549k
  } else {
438
549k
    new (Entry) ContentCache(FileEnt);
439
549k
  }
440
551k
441
551k
  Entry->IsSystemFile = isSystemFile;
442
551k
  Entry->IsTransient = FilesAreTransient;
443
551k
444
551k
  return Entry;
445
551k
}
446
447
/// Create a new ContentCache for the specified memory buffer.
448
/// This does no caching.
449
const ContentCache *
450
SourceManager::createMemBufferContentCache(const llvm::MemoryBuffer *Buffer,
451
72.9k
                                           bool DoNotFree) {
452
72.9k
  // Add a new ContentCache to the MemBufferInfos list and return it.
453
72.9k
  ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
454
72.9k
  new (Entry) ContentCache();
455
72.9k
  MemBufferInfos.push_back(Entry);
456
72.9k
  Entry->replaceBuffer(Buffer, DoNotFree);
457
72.9k
  return Entry;
458
72.9k
}
459
460
const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
461
12.3k
                                                      bool *Invalid) const {
462
12.3k
  assert(!SLocEntryLoaded[Index]);
463
12.3k
  if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
464
82
    if (Invalid)
465
38
      *Invalid = true;
466
82
    // If the file of the SLocEntry changed we could still have loaded it.
467
82
    if (!SLocEntryLoaded[Index]) {
468
82
      // Try to recover; create a SLocEntry so the rest of clang can handle it.
469
82
      LoadedSLocEntryTable[Index] = SLocEntry::get(0,
470
82
                                 FileInfo::get(SourceLocation(),
471
82
                                               getFakeContentCacheForRecovery(),
472
82
                                               SrcMgr::C_User));
473
82
    }
474
82
  }
475
12.3k
476
12.3k
  return LoadedSLocEntryTable[Index];
477
12.3k
}
478
479
std::pair<int, unsigned>
480
SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
481
6.13k
                                         unsigned TotalSize) {
482
6.13k
  assert(ExternalSLocEntries && "Don't have an external sloc source");
483
6.13k
  // Make sure we're not about to run out of source locations.
484
6.13k
  if (CurrentLoadedOffset - TotalSize < NextLocalOffset)
485
0
    return std::make_pair(0, 0);
486
6.13k
  LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
487
6.13k
  SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
488
6.13k
  CurrentLoadedOffset -= TotalSize;
489
6.13k
  int ID = LoadedSLocEntryTable.size();
490
6.13k
  return std::make_pair(-ID - 1, CurrentLoadedOffset);
491
6.13k
}
492
493
/// As part of recovering from missing or changed content, produce a
494
/// fake, non-empty buffer.
495
746
llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
496
746
  if (!FakeBufferForRecovery)
497
21
    FakeBufferForRecovery =
498
21
        llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
499
746
500
746
  return FakeBufferForRecovery.get();
501
746
}
502
503
/// As part of recovering from missing or changed content, produce a
504
/// fake content cache.
505
const SrcMgr::ContentCache *
506
82
SourceManager::getFakeContentCacheForRecovery() const {
507
82
  if (!FakeContentCacheForRecovery) {
508
2
    FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
509
2
    FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
510
2
                                               /*DoNotFree=*/true);
511
2
  }
512
82
  return FakeContentCacheForRecovery.get();
513
82
}
514
515
/// Returns the previous in-order FileID or an invalid FileID if there
516
/// is no previous one.
517
177k
FileID SourceManager::getPreviousFileID(FileID FID) const {
518
177k
  if (FID.isInvalid())
519
0
    return FileID();
520
177k
521
177k
  int ID = FID.ID;
522
177k
  if (ID == -1)
523
0
    return FileID();
524
177k
525
177k
  if (ID > 0) {
526
177k
    if (ID-1 == 0)
527
0
      return FileID();
528
0
  } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
529
0
    return FileID();
530
0
  }
531
177k
532
177k
  return FileID::get(ID-1);
533
177k
}
534
535
/// Returns the next in-order FileID or an invalid FileID if there is
536
/// no next one.
537
28.4k
FileID SourceManager::getNextFileID(FileID FID) const {
538
28.4k
  if (FID.isInvalid())
539
0
    return FileID();
540
28.4k
541
28.4k
  int ID = FID.ID;
542
28.4k
  if (ID > 0) {
543
28.4k
    if (unsigned(ID+1) >= local_sloc_entry_size())
544
34
      return FileID();
545
0
  } else if (ID+1 >= -1) {
546
0
    return FileID();
547
0
  }
548
28.4k
549
28.4k
  return FileID::get(ID+1);
550
28.4k
}
551
552
//===----------------------------------------------------------------------===//
553
// Methods to create new FileID's and macro expansions.
554
//===----------------------------------------------------------------------===//
555
556
/// createFileID - Create a new FileID for the specified ContentCache and
557
/// include position.  This works regardless of whether the ContentCache
558
/// corresponds to a file or some other input source.
559
FileID SourceManager::createFileID(const ContentCache *File,
560
                                   SourceLocation IncludePos,
561
                                   SrcMgr::CharacteristicKind FileCharacter,
562
651k
                                   int LoadedID, unsigned LoadedOffset) {
563
651k
  if (LoadedID < 0) {
564
11.3k
    assert(LoadedID != -1 && "Loading sentinel FileID");
565
11.3k
    unsigned Index = unsigned(-LoadedID) - 2;
566
11.3k
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
567
11.3k
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
568
11.3k
    LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
569
11.3k
        FileInfo::get(IncludePos, File, FileCharacter));
570
11.3k
    SLocEntryLoaded[Index] = true;
571
11.3k
    return FileID::get(LoadedID);
572
11.3k
  }
573
640k
  LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
574
640k
                                               FileInfo::get(IncludePos, File,
575
640k
                                                             FileCharacter)));
576
640k
  unsigned FileSize = File->getSize();
577
640k
  assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
578
640k
         NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
579
640k
         "Ran out of source locations!");
580
640k
  // We do a +1 here because we want a SourceLocation that means "the end of the
581
640k
  // file", e.g. for the "no newline at the end of the file" diagnostic.
582
640k
  NextLocalOffset += FileSize + 1;
583
640k
584
640k
  // Set LastFileIDLookup to the newly created file.  The next getFileID call is
585
640k
  // almost guaranteed to be from that file.
586
640k
  FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
587
640k
  return LastFileIDLookup = FID;
588
640k
}
589
590
SourceLocation
591
SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
592
                                          SourceLocation ExpansionLoc,
593
8.21M
                                          unsigned TokLength) {
594
8.21M
  ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
595
8.21M
                                                        ExpansionLoc);
596
8.21M
  return createExpansionLocImpl(Info, TokLength);
597
8.21M
}
598
599
SourceLocation
600
SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
601
                                  SourceLocation ExpansionLocStart,
602
                                  SourceLocation ExpansionLocEnd,
603
                                  unsigned TokLength,
604
                                  bool ExpansionIsTokenRange,
605
                                  int LoadedID,
606
20.5M
                                  unsigned LoadedOffset) {
607
20.5M
  ExpansionInfo Info = ExpansionInfo::create(
608
20.5M
      SpellingLoc, ExpansionLocStart, ExpansionLocEnd, ExpansionIsTokenRange);
609
20.5M
  return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
610
20.5M
}
611
612
SourceLocation SourceManager::createTokenSplitLoc(SourceLocation Spelling,
613
                                                  SourceLocation TokenStart,
614
19.1k
                                                  SourceLocation TokenEnd) {
615
19.1k
  assert(getFileID(TokenStart) == getFileID(TokenEnd) &&
616
19.1k
         "token spans multiple files");
617
19.1k
  return createExpansionLocImpl(
618
19.1k
      ExpansionInfo::createForTokenSplit(Spelling, TokenStart, TokenEnd),
619
19.1k
      TokenEnd.getOffset() - TokenStart.getOffset());
620
19.1k
}
621
622
SourceLocation
623
SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
624
                                      unsigned TokLength,
625
                                      int LoadedID,
626
28.7M
                                      unsigned LoadedOffset) {
627
28.7M
  if (LoadedID < 0) {
628
935
    assert(LoadedID != -1 && "Loading sentinel FileID");
629
935
    unsigned Index = unsigned(-LoadedID) - 2;
630
935
    assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
631
935
    assert(!SLocEntryLoaded[Index] && "FileID already loaded");
632
935
    LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
633
935
    SLocEntryLoaded[Index] = true;
634
935
    return SourceLocation::getMacroLoc(LoadedOffset);
635
935
  }
636
28.7M
  LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
637
28.7M
  assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
638
28.7M
         NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
639
28.7M
         "Ran out of source locations!");
640
28.7M
  // See createFileID for that +1.
641
28.7M
  NextLocalOffset += TokLength + 1;
642
28.7M
  return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
643
28.7M
}
644
645
const llvm::MemoryBuffer *
646
1.11k
SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
647
1.11k
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
648
1.11k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
649
1.11k
  return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
650
1.11k
}
651
652
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
653
                                         llvm::MemoryBuffer *Buffer,
654
2.35k
                                         bool DoNotFree) {
655
2.35k
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
656
2.35k
  assert(IR && "getOrCreateContentCache() cannot return NULL");
657
2.35k
658
2.35k
  const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
659
2.35k
  const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
660
2.35k
661
2.35k
  getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
662
2.35k
}
663
664
void SourceManager::overrideFileContents(const FileEntry *SourceFile,
665
16
                                         const FileEntry *NewFile) {
666
16
  assert(SourceFile->getSize() == NewFile->getSize() &&
667
16
         "Different sizes, use the FileManager to create a virtual file with "
668
16
         "the correct size");
669
16
  assert(FileInfos.count(SourceFile) == 0 &&
670
16
         "This function should be called at the initialization stage, before "
671
16
         "any parsing occurs.");
672
16
  getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
673
16
}
674
675
1
void SourceManager::disableFileContentsOverride(const FileEntry *File) {
676
1
  if (!isFileOverridden(File))
677
0
    return;
678
1
679
1
  const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
680
1
  const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
681
1
  const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
682
1
683
1
  assert(OverriddenFilesInfo);
684
1
  OverriddenFilesInfo->OverriddenFiles.erase(File);
685
1
  OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
686
1
}
687
688
2
void SourceManager::setFileIsTransient(const FileEntry *File) {
689
2
  const SrcMgr::ContentCache *CC = getOrCreateContentCache(File);
690
2
  const_cast<SrcMgr::ContentCache *>(CC)->IsTransient = true;
691
2
}
692
693
20.5M
StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
694
20.5M
  bool MyInvalid = false;
695
20.5M
  const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
696
20.5M
  if (!SLoc.isFile() || 
MyInvalid20.5M
) {
697
4
    if (Invalid)
698
4
      *Invalid = true;
699
4
    return "<<<<<INVALID SOURCE LOCATION>>>>>";
700
4
  }
701
20.5M
702
20.5M
  const llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
703
20.5M
      Diag, *this, SourceLocation(), &MyInvalid);
704
20.5M
  if (Invalid)
705
20.4M
    *Invalid = MyInvalid;
706
20.5M
707
20.5M
  if (MyInvalid)
708
0
    return "<<<<<INVALID SOURCE LOCATION>>>>>";
709
20.5M
710
20.5M
  return Buf->getBuffer();
711
20.5M
}
712
713
//===----------------------------------------------------------------------===//
714
// SourceLocation manipulation methods.
715
//===----------------------------------------------------------------------===//
716
717
/// Return the FileID for a SourceLocation.
718
///
719
/// This is the cache-miss path of getFileID. Not as hot as that function, but
720
/// still very important. It is responsible for finding the entry in the
721
/// SLocEntry tables that contains the specified location.
722
100M
FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
723
100M
  if (!SLocOffset)
724
26.8k
    return FileID::get(0);
725
100M
726
100M
  // Now it is time to search for the correct file. See where the SLocOffset
727
100M
  // sits in the global view and consult local or loaded buffers for it.
728
100M
  if (SLocOffset < NextLocalOffset)
729
100M
    return getFileIDLocal(SLocOffset);
730
39.3k
  return getFileIDLoaded(SLocOffset);
731
39.3k
}
732
733
/// Return the FileID for a SourceLocation with a low offset.
734
///
735
/// This function knows that the SourceLocation is in a local buffer, not a
736
/// loaded one.
737
100M
FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
738
100M
  assert(SLocOffset < NextLocalOffset && "Bad function choice");
739
100M
740
100M
  // After the first and second level caches, I see two common sorts of
741
100M
  // behavior: 1) a lot of searched FileID's are "near" the cached file
742
100M
  // location or are "near" the cached expansion location. 2) others are just
743
100M
  // completely random and may be a very long way away.
744
100M
  //
745
100M
  // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
746
100M
  // then we fall back to a less cache efficient, but more scalable, binary
747
100M
  // search to find the location.
748
100M
749
100M
  // See if this is near the file point - worst case we start scanning from the
750
100M
  // most newly created FileID.
751
100M
  const SrcMgr::SLocEntry *I;
752
100M
753
100M
  if (LastFileIDLookup.ID < 0 ||
754
100M
      
LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset100M
) {
755
91.6M
    // Neither loc prunes our search.
756
91.6M
    I = LocalSLocEntryTable.end();
757
91.6M
  } else {
758
8.48M
    // Perhaps it is near the file point.
759
8.48M
    I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
760
8.48M
  }
761
100M
762
100M
  // Find the FileID that contains this.  "I" is an iterator that points to a
763
100M
  // FileID whose offset is known to be larger than SLocOffset.
764
100M
  unsigned NumProbes = 0;
765
440M
  while (true) {
766
440M
    --I;
767
440M
    if (I->getOffset() <= SLocOffset) {
768
64.4M
      FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
769
64.4M
770
64.4M
      // If this isn't an expansion, remember it.  We have good locality across
771
64.4M
      // FileID lookups.
772
64.4M
      if (!I->isExpansion())
773
2.68M
        LastFileIDLookup = Res;
774
64.4M
      NumLinearScans += NumProbes+1;
775
64.4M
      return Res;
776
64.4M
    }
777
376M
    if (++NumProbes == 8)
778
35.6M
      break;
779
376M
  }
780
100M
781
100M
  // Convert "I" back into an index.  We know that it is an entry whose index is
782
100M
  // larger than the offset we are looking for.
783
100M
  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
784
35.6M
  // LessIndex - This is the lower bound of the range that we're searching.
785
35.6M
  // We know that the offset corresponding to the FileID is is less than
786
35.6M
  // SLocOffset.
787
35.6M
  unsigned LessIndex = 0;
788
35.6M
  NumProbes = 0;
789
389M
  while (true) {
790
389M
    bool Invalid = false;
791
389M
    unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
792
389M
    unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
793
389M
    if (Invalid)
794
0
      return FileID::get(0);
795
389M
796
389M
    ++NumProbes;
797
389M
798
389M
    // If the offset of the midpoint is too large, chop the high side of the
799
389M
    // range to the midpoint.
800
389M
    if (MidOffset > SLocOffset) {
801
114M
      GreaterIndex = MiddleIndex;
802
114M
      continue;
803
114M
    }
804
275M
805
275M
    // If the middle index contains the value, succeed and return.
806
275M
    // FIXME: This could be made faster by using a function that's aware of
807
275M
    // being in the local area.
808
275M
    if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
809
35.6M
      FileID Res = FileID::get(MiddleIndex);
810
35.6M
811
35.6M
      // If this isn't a macro expansion, remember it.  We have good locality
812
35.6M
      // across FileID lookups.
813
35.6M
      if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
814
13.4M
        LastFileIDLookup = Res;
815
35.6M
      NumBinaryProbes += NumProbes;
816
35.6M
      return Res;
817
35.6M
    }
818
239M
819
239M
    // Otherwise, move the low-side up to the middle index.
820
239M
    LessIndex = MiddleIndex;
821
239M
  }
822
35.6M
}
823
824
/// Return the FileID for a SourceLocation with a high offset.
825
///
826
/// This function knows that the SourceLocation is in a loaded buffer, not a
827
/// local one.
828
39.3k
FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
829
39.3k
  // Sanity checking, otherwise a bug may lead to hanging in release build.
830
39.3k
  if (SLocOffset < CurrentLoadedOffset) {
831
0
    assert(0 && "Invalid SLocOffset or bad function choice");
832
0
    return FileID();
833
0
  }
834
39.3k
835
39.3k
  // Essentially the same as the local case, but the loaded array is sorted
836
39.3k
  // in the other direction.
837
39.3k
838
39.3k
  // First do a linear scan from the last lookup position, if possible.
839
39.3k
  unsigned I;
840
39.3k
  int LastID = LastFileIDLookup.ID;
841
39.3k
  if (LastID >= 0 || 
getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset32.9k
)
842
23.3k
    I = 0;
843
16.0k
  else
844
16.0k
    I = (-LastID - 2) + 1;
845
39.3k
846
39.3k
  unsigned NumProbes;
847
136k
  for (NumProbes = 0; NumProbes < 8; 
++NumProbes, ++I97.0k
) {
848
130k
    // Make sure the entry is loaded!
849
130k
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
850
130k
    if (E.getOffset() <= SLocOffset) {
851
33.7k
      FileID Res = FileID::get(-int(I) - 2);
852
33.7k
853
33.7k
      if (!E.isExpansion())
854
32.5k
        LastFileIDLookup = Res;
855
33.7k
      NumLinearScans += NumProbes + 1;
856
33.7k
      return Res;
857
33.7k
    }
858
130k
  }
859
39.3k
860
39.3k
  // Linear scan failed. Do the binary search. Note the reverse sorting of the
861
39.3k
  // table: GreaterIndex is the one where the offset is greater, which is
862
39.3k
  // actually a lower index!
863
39.3k
  unsigned GreaterIndex = I;
864
5.65k
  unsigned LessIndex = LoadedSLocEntryTable.size();
865
5.65k
  NumProbes = 0;
866
36.3k
  while (true) {
867
36.3k
    ++NumProbes;
868
36.3k
    unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
869
36.3k
    const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
870
36.3k
    if (E.getOffset() == 0)
871
0
      return FileID(); // invalid entry.
872
36.3k
873
36.3k
    ++NumProbes;
874
36.3k
875
36.3k
    if (E.getOffset() > SLocOffset) {
876
22.1k
      // Sanity checking, otherwise a bug may lead to hanging in release build.
877
22.1k
      if (GreaterIndex == MiddleIndex) {
878
0
        assert(0 && "binary search missed the entry");
879
0
        return FileID();
880
0
      }
881
22.1k
      GreaterIndex = MiddleIndex;
882
22.1k
      continue;
883
22.1k
    }
884
14.1k
885
14.1k
    if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
886
5.65k
      FileID Res = FileID::get(-int(MiddleIndex) - 2);
887
5.65k
      if (!E.isExpansion())
888
5.29k
        LastFileIDLookup = Res;
889
5.65k
      NumBinaryProbes += NumProbes;
890
5.65k
      return Res;
891
5.65k
    }
892
8.53k
893
8.53k
    // Sanity checking, otherwise a bug may lead to hanging in release build.
894
8.53k
    if (LessIndex == MiddleIndex) {
895
0
      assert(0 && "binary search missed the entry");
896
0
      return FileID();
897
0
    }
898
8.53k
    LessIndex = MiddleIndex;
899
8.53k
  }
900
5.65k
}
901
902
SourceLocation SourceManager::
903
7.91M
getExpansionLocSlowCase(SourceLocation Loc) const {
904
16.5M
  do {
905
16.5M
    // Note: If Loc indicates an offset into a token that came from a macro
906
16.5M
    // expansion (e.g. the 5th character of the token) we do not want to add
907
16.5M
    // this offset when going to the expansion location.  The expansion
908
16.5M
    // location is the macro invocation, which the offset has nothing to do
909
16.5M
    // with.  This is unlike when we get the spelling loc, because the offset
910
16.5M
    // directly correspond to the token whose spelling we're inspecting.
911
16.5M
    Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
912
16.5M
  } while (!Loc.isFileID());
913
7.91M
914
7.91M
  return Loc;
915
7.91M
}
916
917
15.9M
SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
918
16.1M
  do {
919
16.1M
    std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
920
16.1M
    Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
921
16.1M
    Loc = Loc.getLocWithOffset(LocInfo.second);
922
16.1M
  } while (!Loc.isFileID());
923
15.9M
  return Loc;
924
15.9M
}
925
926
7.68k
SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
927
77.8k
  do {
928
77.8k
    if (isMacroArgExpansion(Loc))
929
11.3k
      Loc = getImmediateSpellingLoc(Loc);
930
66.4k
    else
931
66.4k
      Loc = getImmediateExpansionRange(Loc).getBegin();
932
77.8k
  } while (!Loc.isFileID());
933
7.68k
  return Loc;
934
7.68k
}
935
936
937
std::pair<FileID, unsigned>
938
SourceManager::getDecomposedExpansionLocSlowCase(
939
495k
                                             const SrcMgr::SLocEntry *E) const {
940
495k
  // If this is an expansion record, walk through all the expansion points.
941
495k
  FileID FID;
942
495k
  SourceLocation Loc;
943
495k
  unsigned Offset;
944
1.29M
  do {
945
1.29M
    Loc = E->getExpansion().getExpansionLocStart();
946
1.29M
947
1.29M
    FID = getFileID(Loc);
948
1.29M
    E = &getSLocEntry(FID);
949
1.29M
    Offset = Loc.getOffset()-E->getOffset();
950
1.29M
  } while (!Loc.isFileID());
951
495k
952
495k
  return std::make_pair(FID, Offset);
953
495k
}
954
955
std::pair<FileID, unsigned>
956
SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
957
1.21M
                                                unsigned Offset) const {
958
1.21M
  // If this is an expansion record, walk through all the expansion points.
959
1.21M
  FileID FID;
960
1.21M
  SourceLocation Loc;
961
1.24M
  do {
962
1.24M
    Loc = E->getExpansion().getSpellingLoc();
963
1.24M
    Loc = Loc.getLocWithOffset(Offset);
964
1.24M
965
1.24M
    FID = getFileID(Loc);
966
1.24M
    E = &getSLocEntry(FID);
967
1.24M
    Offset = Loc.getOffset()-E->getOffset();
968
1.24M
  } while (!Loc.isFileID());
969
1.21M
970
1.21M
  return std::make_pair(FID, Offset);
971
1.21M
}
972
973
/// getImmediateSpellingLoc - Given a SourceLocation object, return the
974
/// spelling location referenced by the ID.  This is the first level down
975
/// towards the place where the characters that make up the lexed token can be
976
/// found.  This should not generally be used by clients.
977
34.0k
SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
978
34.0k
  if (Loc.isFileID()) 
return Loc0
;
979
34.0k
  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
980
34.0k
  Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
981
34.0k
  return Loc.getLocWithOffset(LocInfo.second);
982
34.0k
}
983
984
/// getImmediateExpansionRange - Loc is required to be an expansion location.
985
/// Return the start/end of the expansion information.
986
CharSourceRange
987
4.97M
SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
988
4.97M
  assert(Loc.isMacroID() && "Not a macro expansion loc!");
989
4.97M
  const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
990
4.97M
  return Expansion.getExpansionLocRange();
991
4.97M
}
992
993
5.10k
SourceLocation SourceManager::getTopMacroCallerLoc(SourceLocation Loc) const {
994
5.28k
  while (isMacroArgExpansion(Loc))
995
180
    Loc = getImmediateSpellingLoc(Loc);
996
5.10k
  return Loc;
997
5.10k
}
998
999
/// getExpansionRange - Given a SourceLocation object, return the range of
1000
/// tokens covered by the expansion in the ultimate file.
1001
2.32M
CharSourceRange SourceManager::getExpansionRange(SourceLocation Loc) const {
1002
2.32M
  if (Loc.isFileID())
1003
7.50k
    return CharSourceRange(SourceRange(Loc, Loc), true);
1004
2.31M
1005
2.31M
  CharSourceRange Res = getImmediateExpansionRange(Loc);
1006
2.31M
1007
2.31M
  // Fully resolve the start and end locations to their ultimate expansion
1008
2.31M
  // points.
1009
2.83M
  while (!Res.getBegin().isFileID())
1010
517k
    Res.setBegin(getImmediateExpansionRange(Res.getBegin()).getBegin());
1011
2.79M
  while (!Res.getEnd().isFileID()) {
1012
477k
    CharSourceRange EndRange = getImmediateExpansionRange(Res.getEnd());
1013
477k
    Res.setEnd(EndRange.getEnd());
1014
477k
    Res.setTokenRange(EndRange.isTokenRange());
1015
477k
  }
1016
2.31M
  return Res;
1017
2.31M
}
1018
1019
bool SourceManager::isMacroArgExpansion(SourceLocation Loc,
1020
144k
                                        SourceLocation *StartLoc) const {
1021
144k
  if (!Loc.isMacroID()) 
return false30.9k
;
1022
113k
1023
113k
  FileID FID = getFileID(Loc);
1024
113k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1025
113k
  if (!Expansion.isMacroArgExpansion()) 
return false79.8k
;
1026
33.6k
1027
33.6k
  if (StartLoc)
1028
236
    *StartLoc = Expansion.getExpansionLocStart();
1029
33.6k
  return true;
1030
33.6k
}
1031
1032
3.53M
bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1033
3.53M
  if (!Loc.isMacroID()) 
return false3.13M
;
1034
395k
1035
395k
  FileID FID = getFileID(Loc);
1036
395k
  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1037
395k
  return Expansion.isMacroBodyExpansion();
1038
395k
}
1039
1040
bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1041
9.60M
                                             SourceLocation *MacroBegin) const {
1042
9.60M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1043
9.60M
1044
9.60M
  std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1045
9.60M
  if (DecompLoc.second > 0)
1046
1.68M
    return false; // Does not point at the start of expansion range.
1047
7.91M
1048
7.91M
  bool Invalid = false;
1049
7.91M
  const SrcMgr::ExpansionInfo &ExpInfo =
1050
7.91M
      getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1051
7.91M
  if (Invalid)
1052
0
    return false;
1053
7.91M
  SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1054
7.91M
1055
7.91M
  if (ExpInfo.isMacroArgExpansion()) {
1056
177k
    // For macro argument expansions, check if the previous FileID is part of
1057
177k
    // the same argument expansion, in which case this Loc is not at the
1058
177k
    // beginning of the expansion.
1059
177k
    FileID PrevFID = getPreviousFileID(DecompLoc.first);
1060
177k
    if (!PrevFID.isInvalid()) {
1061
177k
      const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1062
177k
      if (Invalid)
1063
0
        return false;
1064
177k
      if (PrevEntry.isExpansion() &&
1065
177k
          PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1066
11.9k
        return false;
1067
7.90M
    }
1068
177k
  }
1069
7.90M
1070
7.90M
  if (MacroBegin)
1071
7.90M
    *MacroBegin = ExpLoc;
1072
7.90M
  return true;
1073
7.90M
}
1074
1075
bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1076
9.28M
                                               SourceLocation *MacroEnd) const {
1077
9.28M
  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1078
9.28M
1079
9.28M
  FileID FID = getFileID(Loc);
1080
9.28M
  SourceLocation NextLoc = Loc.getLocWithOffset(1);
1081
9.28M
  if (isInFileID(NextLoc, FID))
1082
1.37M
    return false; // Does not point at the end of expansion range.
1083
7.91M
1084
7.91M
  bool Invalid = false;
1085
7.91M
  const SrcMgr::ExpansionInfo &ExpInfo =
1086
7.91M
      getSLocEntry(FID, &Invalid).getExpansion();
1087
7.91M
  if (Invalid)
1088
0
    return false;
1089
7.91M
1090
7.91M
  if (ExpInfo.isMacroArgExpansion()) {
1091
28.4k
    // For macro argument expansions, check if the next FileID is part of the
1092
28.4k
    // same argument expansion, in which case this Loc is not at the end of the
1093
28.4k
    // expansion.
1094
28.4k
    FileID NextFID = getNextFileID(FID);
1095
28.4k
    if (!NextFID.isInvalid()) {
1096
28.4k
      const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1097
28.4k
      if (Invalid)
1098
0
        return false;
1099
28.4k
      if (NextEntry.isExpansion() &&
1100
28.4k
          NextEntry.getExpansion().getExpansionLocStart() ==
1101
28.4k
              ExpInfo.getExpansionLocStart())
1102
28.1k
        return false;
1103
7.88M
    }
1104
28.4k
  }
1105
7.88M
1106
7.88M
  if (MacroEnd)
1107
7.88M
    *MacroEnd = ExpInfo.getExpansionLocEnd();
1108
7.88M
  return true;
1109
7.88M
}
1110
1111
//===----------------------------------------------------------------------===//
1112
// Queries about the code at a SourceLocation.
1113
//===----------------------------------------------------------------------===//
1114
1115
/// getCharacterData - Return a pointer to the start of the specified location
1116
/// in the appropriate MemoryBuffer.
1117
const char *SourceManager::getCharacterData(SourceLocation SL,
1118
7.99M
                                            bool *Invalid) const {
1119
7.99M
  // Note that this is a hot function in the getSpelling() path, which is
1120
7.99M
  // heavily used by -E mode.
1121
7.99M
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1122
7.99M
1123
7.99M
  // Note that calling 'getBuffer()' may lazily page in a source file.
1124
7.99M
  bool CharDataInvalid = false;
1125
7.99M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1126
7.99M
  if (CharDataInvalid || 
!Entry.isFile()7.99M
) {
1127
4
    if (Invalid)
1128
0
      *Invalid = true;
1129
4
1130
4
    return "<<<<INVALID BUFFER>>>>";
1131
4
  }
1132
7.99M
  const llvm::MemoryBuffer *Buffer =
1133
7.99M
      Entry.getFile().getContentCache()->getBuffer(
1134
7.99M
          Diag, *this, SourceLocation(), &CharDataInvalid);
1135
7.99M
  if (Invalid)
1136
2.57M
    *Invalid = CharDataInvalid;
1137
7.99M
  return Buffer->getBufferStart() + (CharDataInvalid? 
00
: LocInfo.second);
1138
7.99M
}
1139
1140
/// getColumnNumber - Return the column # for the specified file position.
1141
/// this is significantly cheaper to compute than the line number.
1142
unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1143
33.4M
                                        bool *Invalid) const {
1144
33.4M
  bool MyInvalid = false;
1145
33.4M
  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
1146
33.4M
  if (Invalid)
1147
33.0M
    *Invalid = MyInvalid;
1148
33.4M
1149
33.4M
  if (MyInvalid)
1150
63
    return 1;
1151
33.4M
1152
33.4M
  // It is okay to request a position just past the end of the buffer.
1153
33.4M
  if (FilePos > MemBuf->getBufferSize()) {
1154
1
    if (Invalid)
1155
1
      *Invalid = true;
1156
1
    return 1;
1157
1
  }
1158
33.4M
1159
33.4M
  const char *Buf = MemBuf->getBufferStart();
1160
33.4M
  // See if we just calculated the line number for this FilePos and can use
1161
33.4M
  // that to lookup the start of the line instead of searching for it.
1162
33.4M
  if (LastLineNoFileIDQuery == FID &&
1163
33.4M
      
LastLineNoContentCache->SourceLineCache != nullptr33.4M
&&
1164
33.4M
      
LastLineNoResult < LastLineNoContentCache->NumLines33.4M
) {
1165
33.3M
    unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1166
33.3M
    unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1167
33.3M
    unsigned LineEnd = SourceLineCache[LastLineNoResult];
1168
33.3M
    if (FilePos >= LineStart && 
FilePos < LineEnd33.3M
) {
1169
33.3M
      // LineEnd is the LineStart of the next line.
1170
33.3M
      // A line ends with separator LF or CR+LF on Windows.
1171
33.3M
      // FilePos might point to the last separator,
1172
33.3M
      // but we need a column number at most 1 + the last column.
1173
33.3M
      if (FilePos + 1 == LineEnd && 
FilePos > LineStart142k
) {
1174
141k
        if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1175
0
          --FilePos;
1176
141k
      }
1177
33.3M
      return FilePos - LineStart + 1;
1178
33.3M
    }
1179
43.7k
  }
1180
43.7k
1181
43.7k
  unsigned LineStart = FilePos;
1182
755k
  while (LineStart && 
Buf[LineStart-1] != '\n'737k
&&
Buf[LineStart-1] != '\r'711k
)
1183
711k
    --LineStart;
1184
43.7k
  return FilePos-LineStart+1;
1185
43.7k
}
1186
1187
// isInvalid - Return the result of calling loc.isInvalid(), and
1188
// if Invalid is not null, set its value to same.
1189
template<typename LocType>
1190
4.43M
static bool isInvalid(LocType Loc, bool *Invalid) {
1191
4.43M
  bool MyInvalid = Loc.isInvalid();
1192
4.43M
  if (Invalid)
1193
33.5k
    *Invalid = MyInvalid;
1194
4.43M
  return MyInvalid;
1195
4.43M
}
SourceManager.cpp:bool isInvalid<clang::SourceLocation>(clang::SourceLocation, bool*)
Line
Count
Source
1190
3.09M
static bool isInvalid(LocType Loc, bool *Invalid) {
1191
3.09M
  bool MyInvalid = Loc.isInvalid();
1192
3.09M
  if (Invalid)
1193
31.7k
    *Invalid = MyInvalid;
1194
3.09M
  return MyInvalid;
1195
3.09M
}
SourceManager.cpp:bool isInvalid<clang::PresumedLoc>(clang::PresumedLoc, bool*)
Line
Count
Source
1190
1.33M
static bool isInvalid(LocType Loc, bool *Invalid) {
1191
1.33M
  bool MyInvalid = Loc.isInvalid();
1192
1.33M
  if (Invalid)
1193
1.71k
    *Invalid = MyInvalid;
1194
1.33M
  return MyInvalid;
1195
1.33M
}
1196
1197
unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1198
28.2k
                                                bool *Invalid) const {
1199
28.2k
  if (isInvalid(Loc, Invalid)) 
return 0224
;
1200
28.0k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1201
28.0k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1202
28.0k
}
1203
1204
unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1205
48.7k
                                                 bool *Invalid) const {
1206
48.7k
  if (isInvalid(Loc, Invalid)) 
return 00
;
1207
48.7k
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1208
48.7k
  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1209
48.7k
}
1210
1211
unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1212
898
                                                bool *Invalid) const {
1213
898
  PresumedLoc PLoc = getPresumedLoc(Loc);
1214
898
  if (isInvalid(PLoc, Invalid)) 
return 00
;
1215
898
  return PLoc.getColumn();
1216
898
}
1217
1218
#ifdef __SSE2__
1219
#include <emmintrin.h>
1220
#endif
1221
1222
static LLVM_ATTRIBUTE_NOINLINE void
1223
ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1224
                   llvm::BumpPtrAllocator &Alloc,
1225
                   const SourceManager &SM, bool &Invalid);
1226
static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
1227
                               llvm::BumpPtrAllocator &Alloc,
1228
141k
                               const SourceManager &SM, bool &Invalid) {
1229
141k
  // Note that calling 'getBuffer()' may lazily page in the file.
1230
141k
  const MemoryBuffer *Buffer =
1231
141k
      FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
1232
141k
  if (Invalid)
1233
0
    return;
1234
141k
1235
141k
  // Find the file offsets of all of the *physical* source lines.  This does
1236
141k
  // not look at trigraphs, escaped newlines, or anything else tricky.
1237
141k
  SmallVector<unsigned, 256> LineOffsets;
1238
141k
1239
141k
  // Line #1 starts at char 0.
1240
141k
  LineOffsets.push_back(0);
1241
141k
1242
141k
  const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1243
141k
  const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1244
141k
  unsigned I = 0;
1245
200M
  while (true) {
1246
200M
    // Skip over the contents of the line.
1247
16.5G
    while (Buf[I] != '\n' && 
Buf[I] != '\r'16.3G
&&
Buf[I] != '\0'16.3G
)
1248
16.3G
      ++I;
1249
200M
1250
200M
    if (Buf[I] == '\n' || 
Buf[I] == '\r'782k
) {
1251
199M
      // If this is \r\n, skip both characters.
1252
199M
      if (Buf[I] == '\r' && 
Buf[I+1] == '\n'8.76k
)
1253
8.76k
        ++I;
1254
199M
      ++I;
1255
199M
      LineOffsets.push_back(I);
1256
199M
    } else {
1257
773k
      // Otherwise, this is a NUL. If end of file, exit.
1258
773k
      if (Buf+I == End) 
break141k
;
1259
632k
      ++I;
1260
632k
    }
1261
200M
  }
1262
141k
1263
141k
  // Copy the offsets into the FileInfo structure.
1264
141k
  FI->NumLines = LineOffsets.size();
1265
141k
  FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
1266
141k
  std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1267
141k
}
1268
1269
/// getLineNumber - Given a SourceLocation, return the spelling line number
1270
/// for the position indicated.  This requires building and caching a table of
1271
/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1272
/// about to emit a diagnostic.
1273
unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1274
39.6M
                                      bool *Invalid) const {
1275
39.6M
  if (FID.isInvalid()) {
1276
52
    if (Invalid)
1277
0
      *Invalid = true;
1278
52
    return 1;
1279
52
  }
1280
39.6M
1281
39.6M
  ContentCache *Content;
1282
39.6M
  if (LastLineNoFileIDQuery == FID)
1283
39.2M
    Content = LastLineNoContentCache;
1284
476k
  else {
1285
476k
    bool MyInvalid = false;
1286
476k
    const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1287
476k
    if (MyInvalid || !Entry.isFile()) {
1288
9
      if (Invalid)
1289
0
        *Invalid = true;
1290
9
      return 1;
1291
9
    }
1292
476k
1293
476k
    Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1294
476k
  }
1295
39.6M
1296
39.6M
  // If this is the first use of line information for this buffer, compute the
1297
39.6M
  /// SourceLineCache for it on demand.
1298
39.6M
  
if (39.6M
!Content->SourceLineCache39.6M
) {
1299
141k
    bool MyInvalid = false;
1300
141k
    ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1301
141k
    if (Invalid)
1302
137k
      *Invalid = MyInvalid;
1303
141k
    if (MyInvalid)
1304
0
      return 1;
1305
39.5M
  } else if (Invalid)
1306
32.9M
    *Invalid = false;
1307
39.6M
1308
39.6M
  // Okay, we know we have a line number table.  Do a binary search to find the
1309
39.6M
  // line number that this character position lands on.
1310
39.6M
  unsigned *SourceLineCache = Content->SourceLineCache;
1311
39.6M
  unsigned *SourceLineCacheStart = SourceLineCache;
1312
39.6M
  unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
1313
39.6M
1314
39.6M
  unsigned QueriedFilePos = FilePos+1;
1315
39.6M
1316
39.6M
  // FIXME: I would like to be convinced that this code is worth being as
1317
39.6M
  // complicated as it is, binary search isn't that slow.
1318
39.6M
  //
1319
39.6M
  // If it is worth being optimized, then in my opinion it could be more
1320
39.6M
  // performant, simpler, and more obviously correct by just "galloping" outward
1321
39.6M
  // from the queried file position. In fact, this could be incorporated into a
1322
39.6M
  // generic algorithm such as lower_bound_with_hint.
1323
39.6M
  //
1324
39.6M
  // If someone gives me a test case where this matters, and I will do it! - DWD
1325
39.6M
1326
39.6M
  // If the previous query was to the same file, we know both the file pos from
1327
39.6M
  // that query and the line number returned.  This allows us to narrow the
1328
39.6M
  // search space from the entire file to something near the match.
1329
39.6M
  if (LastLineNoFileIDQuery == FID) {
1330
39.2M
    if (QueriedFilePos >= LastLineNoFilePos) {
1331
32.4M
      // FIXME: Potential overflow?
1332
32.4M
      SourceLineCache = SourceLineCache+LastLineNoResult-1;
1333
32.4M
1334
32.4M
      // The query is likely to be nearby the previous one.  Here we check to
1335
32.4M
      // see if it is within 5, 10 or 20 lines.  It can be far away in cases
1336
32.4M
      // where big comment blocks and vertical whitespace eat up lines but
1337
32.4M
      // contribute no tokens.
1338
32.4M
      if (SourceLineCache+5 < SourceLineCacheEnd) {
1339
32.3M
        if (SourceLineCache[5] > QueriedFilePos)
1340
26.3M
          SourceLineCacheEnd = SourceLineCache+5;
1341
6.01M
        else if (SourceLineCache+10 < SourceLineCacheEnd) {
1342
6.01M
          if (SourceLineCache[10] > QueriedFilePos)
1343
460k
            SourceLineCacheEnd = SourceLineCache+10;
1344
5.55M
          else if (SourceLineCache+20 < SourceLineCacheEnd) {
1345
5.55M
            if (SourceLineCache[20] > QueriedFilePos)
1346
166k
              SourceLineCacheEnd = SourceLineCache+20;
1347
5.55M
          }
1348
6.01M
        }
1349
32.3M
      }
1350
32.4M
    } else {
1351
6.73M
      if (LastLineNoResult < Content->NumLines)
1352
6.72M
        SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1353
6.73M
    }
1354
39.2M
  }
1355
39.6M
1356
39.6M
  unsigned *Pos
1357
39.6M
    = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1358
39.6M
  unsigned LineNo = Pos-SourceLineCacheStart;
1359
39.6M
1360
39.6M
  LastLineNoFileIDQuery = FID;
1361
39.6M
  LastLineNoContentCache = Content;
1362
39.6M
  LastLineNoFilePos = QueriedFilePos;
1363
39.6M
  LastLineNoResult = LineNo;
1364
39.6M
  return LineNo;
1365
39.6M
}
1366
1367
unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1368
41.4k
                                              bool *Invalid) const {
1369
41.4k
  if (isInvalid(Loc, Invalid)) 
return 0581
;
1370
40.8k
  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1371
40.8k
  return getLineNumber(LocInfo.first, LocInfo.second);
1372
40.8k
}
1373
unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1374
1.04M
                                               bool *Invalid) const {
1375
1.04M
  if (isInvalid(Loc, Invalid)) 
return 00
;
1376
1.04M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1377
1.04M
  return getLineNumber(LocInfo.first, LocInfo.second);
1378
1.04M
}
1379
unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
1380
1.33M
                                              bool *Invalid) const {
1381
1.33M
  PresumedLoc PLoc = getPresumedLoc(Loc);
1382
1.33M
  if (isInvalid(PLoc, Invalid)) 
return 043
;
1383
1.33M
  return PLoc.getLine();
1384
1.33M
}
1385
1386
/// getFileCharacteristic - return the file characteristic of the specified
1387
/// source location, indicating whether this is a normal file, a system
1388
/// header, or an "implicit extern C" system header.
1389
///
1390
/// This state can be modified with flags on GNU linemarker directives like:
1391
///   # 4 "foo.h" 3
1392
/// which changes all source locations in the current file after that to be
1393
/// considered to be from a system header.
1394
SrcMgr::CharacteristicKind
1395
59.1M
SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1396
59.1M
  assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1397
59.1M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1398
59.1M
  bool Invalid = false;
1399
59.1M
  const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1400
59.1M
  if (Invalid || 
!SEntry.isFile()59.1M
)
1401
3
    return C_User;
1402
59.1M
1403
59.1M
  const SrcMgr::FileInfo &FI = SEntry.getFile();
1404
59.1M
1405
59.1M
  // If there are no #line directives in this file, just return the whole-file
1406
59.1M
  // state.
1407
59.1M
  if (!FI.hasLineDirectives())
1408
40.4M
    return FI.getFileCharacteristic();
1409
18.7M
1410
18.7M
  assert(LineTable && "Can't have linetable entries without a LineTable!");
1411
18.7M
  // See if there is a #line directive before the location.
1412
18.7M
  const LineEntry *Entry =
1413
18.7M
    LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1414
18.7M
1415
18.7M
  // If this is before the first line marker, use the file characteristic.
1416
18.7M
  if (!Entry)
1417
456
    return FI.getFileCharacteristic();
1418
18.7M
1419
18.7M
  return Entry->FileKind;
1420
18.7M
}
1421
1422
/// Return the filename or buffer identifier of the buffer the location is in.
1423
/// Note that this name does not respect \#line directives.  Use getPresumedLoc
1424
/// for normal clients.
1425
StringRef SourceManager::getBufferName(SourceLocation Loc,
1426
1.92M
                                       bool *Invalid) const {
1427
1.92M
  if (isInvalid(Loc, Invalid)) 
return "<invalid loc>"4
;
1428
1.92M
1429
1.92M
  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
1430
1.92M
}
1431
1432
/// getPresumedLoc - This method returns the "presumed" location of a
1433
/// SourceLocation specifies.  A "presumed location" can be modified by \#line
1434
/// or GNU line marker directives.  This provides a view on the data that a
1435
/// user should see in diagnostics, for example.
1436
///
1437
/// Note that a presumed location is always given as the expansion point of an
1438
/// expansion location, not at the spelling location.
1439
PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1440
33.0M
                                          bool UseLineDirectives) const {
1441
33.0M
  if (Loc.isInvalid()) 
return PresumedLoc()5.33k
;
1442
33.0M
1443
33.0M
  // Presumed locations are always for expansion points.
1444
33.0M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1445
33.0M
1446
33.0M
  bool Invalid = false;
1447
33.0M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1448
33.0M
  if (Invalid || 
!Entry.isFile()33.0M
)
1449
4
    return PresumedLoc();
1450
33.0M
1451
33.0M
  const SrcMgr::FileInfo &FI = Entry.getFile();
1452
33.0M
  const SrcMgr::ContentCache *C = FI.getContentCache();
1453
33.0M
1454
33.0M
  // To get the source name, first consult the FileEntry (if one exists)
1455
33.0M
  // before the MemBuffer as this will avoid unnecessarily paging in the
1456
33.0M
  // MemBuffer.
1457
33.0M
  FileID FID = LocInfo.first;
1458
33.0M
  StringRef Filename;
1459
33.0M
  if (C->OrigEntry)
1460
32.9M
    Filename = C->OrigEntry->getName();
1461
49.8k
  else
1462
49.8k
    Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
1463
33.0M
1464
33.0M
  unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1465
33.0M
  if (Invalid)
1466
0
    return PresumedLoc();
1467
33.0M
  unsigned ColNo  = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1468
33.0M
  if (Invalid)
1469
0
    return PresumedLoc();
1470
33.0M
1471
33.0M
  SourceLocation IncludeLoc = FI.getIncludeLoc();
1472
33.0M
1473
33.0M
  // If we have #line directives in this file, update and overwrite the physical
1474
33.0M
  // location info if appropriate.
1475
33.0M
  if (UseLineDirectives && 
FI.hasLineDirectives()33.0M
) {
1476
5.23M
    assert(LineTable && "Can't have linetable entries without a LineTable!");
1477
5.23M
    // See if there is a #line directive before this.  If so, get it.
1478
5.23M
    if (const LineEntry *Entry =
1479
5.22M
          LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1480
5.22M
      // If the LineEntry indicates a filename, use it.
1481
5.22M
      if (Entry->FilenameID != -1) {
1482
5.22M
        Filename = LineTable->getFilename(Entry->FilenameID);
1483
5.22M
        // The contents of files referenced by #line are not in the
1484
5.22M
        // SourceManager
1485
5.22M
        FID = FileID::get(0);
1486
5.22M
      }
1487
5.22M
1488
5.22M
      // Use the line number specified by the LineEntry.  This line number may
1489
5.22M
      // be multiple lines down from the line entry.  Add the difference in
1490
5.22M
      // physical line numbers from the query point and the line marker to the
1491
5.22M
      // total.
1492
5.22M
      unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1493
5.22M
      LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1494
5.22M
1495
5.22M
      // Note that column numbers are not molested by line markers.
1496
5.22M
1497
5.22M
      // Handle virtual #include manipulation.
1498
5.22M
      if (Entry->IncludeOffset) {
1499
42.3k
        IncludeLoc = getLocForStartOfFile(LocInfo.first);
1500
42.3k
        IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1501
42.3k
      }
1502
5.22M
    }
1503
5.23M
  }
1504
33.0M
1505
33.0M
  return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1506
33.0M
}
1507
1508
/// Returns whether the PresumedLoc for a given SourceLocation is
1509
/// in the main file.
1510
///
1511
/// This computes the "presumed" location for a SourceLocation, then checks
1512
/// whether it came from a file other than the main file. This is different
1513
/// from isWrittenInMainFile() because it takes line marker directives into
1514
/// account.
1515
29.6M
bool SourceManager::isInMainFile(SourceLocation Loc) const {
1516
29.6M
  if (Loc.isInvalid()) 
return false286
;
1517
29.6M
1518
29.6M
  // Presumed locations are always for expansion points.
1519
29.6M
  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1520
29.6M
1521
29.6M
  bool Invalid = false;
1522
29.6M
  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1523
29.6M
  if (Invalid || 
!Entry.isFile()29.6M
)
1524
2
    return false;
1525
29.6M
1526
29.6M
  const SrcMgr::FileInfo &FI = Entry.getFile();
1527
29.6M
1528
29.6M
  // Check if there is a line directive for this location.
1529
29.6M
  if (FI.hasLineDirectives())
1530
15.9M
    if (const LineEntry *Entry =
1531
15.9M
            LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1532
15.9M
      if (Entry->IncludeOffset)
1533
327k
        return false;
1534
29.3M
1535
29.3M
  return FI.getIncludeLoc().isInvalid();
1536
29.3M
}
1537
1538
/// The size of the SLocEntry that \p FID represents.
1539
4.43k
unsigned SourceManager::getFileIDSize(FileID FID) const {
1540
4.43k
  bool Invalid = false;
1541
4.43k
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1542
4.43k
  if (Invalid)
1543
0
    return 0;
1544
4.43k
1545
4.43k
  int ID = FID.ID;
1546
4.43k
  unsigned NextOffset;
1547
4.43k
  if ((ID > 0 && 
unsigned(ID+1) == local_sloc_entry_size()4.39k
))
1548
2.24k
    NextOffset = getNextLocalOffset();
1549
2.18k
  else if (ID+1 == -1)
1550
6
    NextOffset = MaxLoadedOffset;
1551
2.18k
  else
1552
2.18k
    NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1553
4.43k
1554
4.43k
  return NextOffset - Entry.getOffset() - 1;
1555
4.43k
}
1556
1557
//===----------------------------------------------------------------------===//
1558
// Other miscellaneous methods.
1559
//===----------------------------------------------------------------------===//
1560
1561
/// Retrieve the inode for the given file entry, if possible.
1562
///
1563
/// This routine involves a system call, and therefore should only be used
1564
/// in non-performance-critical code.
1565
static Optional<llvm::sys::fs::UniqueID>
1566
186
getActualFileUID(const FileEntry *File) {
1567
186
  if (!File)
1568
0
    return None;
1569
186
1570
186
  llvm::sys::fs::UniqueID ID;
1571
186
  if (llvm::sys::fs::getUniqueID(File->getName(), ID))
1572
10
    return None;
1573
176
1574
176
  return ID;
1575
176
}
1576
1577
/// Get the source location for the given file:line:col triplet.
1578
///
1579
/// If the source file is included multiple times, the source location will
1580
/// be based upon an arbitrary inclusion.
1581
SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1582
                                                  unsigned Line,
1583
11.2k
                                                  unsigned Col) const {
1584
11.2k
  assert(SourceFile && "Null source file!");
1585
11.2k
  assert(Line && Col && "Line and column should start from 1!");
1586
11.2k
1587
11.2k
  FileID FirstFID = translateFile(SourceFile);
1588
11.2k
  return translateLineCol(FirstFID, Line, Col);
1589
11.2k
}
1590
1591
/// Get the FileID for the given file.
1592
///
1593
/// If the source file is included multiple times, the FileID will be the
1594
/// first inclusion.
1595
52.5k
FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1596
52.5k
  assert(SourceFile && "Null source file!");
1597
52.5k
1598
52.5k
  // Find the first file ID that corresponds to the given file.
1599
52.5k
  FileID FirstFID;
1600
52.5k
1601
52.5k
  // First, check the main file ID, since it is common to look for a
1602
52.5k
  // location in the main file.
1603
52.5k
  Optional<llvm::sys::fs::UniqueID> SourceFileUID;
1604
52.5k
  Optional<StringRef> SourceFileName;
1605
52.5k
  if (MainFileID.isValid()) {
1606
13.1k
    bool Invalid = false;
1607
13.1k
    const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1608
13.1k
    if (Invalid)
1609
0
      return FileID();
1610
13.1k
1611
13.1k
    if (MainSLoc.isFile()) {
1612
13.1k
      const ContentCache *MainContentCache
1613
13.1k
        = MainSLoc.getFile().getContentCache();
1614
13.1k
      if (!MainContentCache || !MainContentCache->OrigEntry) {
1615
1
        // Can't do anything
1616
13.1k
      } else if (MainContentCache->OrigEntry == SourceFile) {
1617
9.64k
        FirstFID = MainFileID;
1618
9.64k
      } else {
1619
3.47k
        // Fall back: check whether we have the same base name and inode
1620
3.47k
        // as the main file.
1621
3.47k
        const FileEntry *MainFile = MainContentCache->OrigEntry;
1622
3.47k
        SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1623
3.47k
        if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1624
0
          SourceFileUID = getActualFileUID(SourceFile);
1625
0
          if (SourceFileUID) {
1626
0
            if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1627
0
                    getActualFileUID(MainFile)) {
1628
0
              if (*SourceFileUID == *MainFileUID) {
1629
0
                FirstFID = MainFileID;
1630
0
                SourceFile = MainFile;
1631
0
              }
1632
0
            }
1633
0
          }
1634
0
        }
1635
3.47k
      }
1636
13.1k
    }
1637
13.1k
  }
1638
52.5k
1639
52.5k
  if (FirstFID.isInvalid()) {
1640
42.9k
    // The location we're looking for isn't in the main file; look
1641
42.9k
    // through all of the local source locations.
1642
97.8k
    for (unsigned I = 0, N = local_sloc_entry_size(); I != N; 
++I54.9k
) {
1643
95.6k
      bool Invalid = false;
1644
95.6k
      const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
1645
95.6k
      if (Invalid)
1646
0
        return FileID();
1647
95.6k
1648
95.6k
      if (SLoc.isFile() &&
1649
95.6k
          
SLoc.getFile().getContentCache()51.1k
&&
1650
95.6k
          
SLoc.getFile().getContentCache()->OrigEntry == SourceFile51.1k
) {
1651
40.6k
        FirstFID = FileID::get(I);
1652
40.6k
        break;
1653
40.6k
      }
1654
95.6k
    }
1655
42.9k
    // If that still didn't help, try the modules.
1656
42.9k
    if (FirstFID.isInvalid()) {
1657
129k
      for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; 
++I126k
) {
1658
128k
        const SLocEntry &SLoc = getLoadedSLocEntry(I);
1659
128k
        if (SLoc.isFile() &&
1660
128k
            
SLoc.getFile().getContentCache()9.02k
&&
1661
128k
            
SLoc.getFile().getContentCache()->OrigEntry == SourceFile9.02k
) {
1662
2.05k
          FirstFID = FileID::get(-int(I) - 2);
1663
2.05k
          break;
1664
2.05k
        }
1665
128k
      }
1666
2.24k
    }
1667
42.9k
  }
1668
52.5k
1669
52.5k
  // If we haven't found what we want yet, try again, but this time stat()
1670
52.5k
  // each of the files in case the files have changed since we originally
1671
52.5k
  // parsed the file.
1672
52.5k
  if (FirstFID.isInvalid() &&
1673
52.5k
      
(186
SourceFileName186
||
1674
186
       
(SourceFileName = llvm::sys::path::filename(SourceFile->getName()))62
) &&
1675
52.5k
      
(186
SourceFileUID186
||
(SourceFileUID = getActualFileUID(SourceFile))186
)) {
1676
176
    bool Invalid = false;
1677
176
    for (unsigned I = 0, N = local_sloc_entry_size(); I != N; 
++I0
) {
1678
176
      FileID IFileID;
1679
176
      IFileID.ID = I;
1680
176
      const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
1681
176
      if (Invalid)
1682
176
        return FileID();
1683
0
1684
0
      if (SLoc.isFile()) {
1685
0
        const ContentCache *FileContentCache
1686
0
          = SLoc.getFile().getContentCache();
1687
0
        const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1688
0
                                                  : nullptr;
1689
0
        if (Entry &&
1690
0
            *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1691
0
          if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1692
0
                  getActualFileUID(Entry)) {
1693
0
            if (*SourceFileUID == *EntryUID) {
1694
0
              FirstFID = FileID::get(I);
1695
0
              SourceFile = Entry;
1696
0
              break;
1697
0
            }
1698
0
          }
1699
0
        }
1700
0
      }
1701
0
    }
1702
176
  }
1703
52.5k
1704
52.5k
  (void) SourceFile;
1705
52.3k
  return FirstFID;
1706
52.5k
}
1707
1708
/// Get the source location in \arg FID for the given line:col.
1709
/// Returns null location if \arg FID is not a file SLocEntry.
1710
SourceLocation SourceManager::translateLineCol(FileID FID,
1711
                                               unsigned Line,
1712
63.0k
                                               unsigned Col) const {
1713
63.0k
  // Lines are used as a one-based index into a zero-based array. This assert
1714
63.0k
  // checks for possible buffer underruns.
1715
63.0k
  assert(Line && Col && "Line and column should start from 1!");
1716
63.0k
1717
63.0k
  if (FID.isInvalid())
1718
0
    return SourceLocation();
1719
63.0k
1720
63.0k
  bool Invalid = false;
1721
63.0k
  const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1722
63.0k
  if (Invalid)
1723
0
    return SourceLocation();
1724
63.0k
1725
63.0k
  if (!Entry.isFile())
1726
0
    return SourceLocation();
1727
63.0k
1728
63.0k
  SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1729
63.0k
1730
63.0k
  if (Line == 1 && 
Col == 12.15k
)
1731
1.86k
    return FileLoc;
1732
61.2k
1733
61.2k
  ContentCache *Content
1734
61.2k
    = const_cast<ContentCache *>(Entry.getFile().getContentCache());
1735
61.2k
  if (!Content)
1736
0
    return SourceLocation();
1737
61.2k
1738
61.2k
  // If this is the first use of line information for this buffer, compute the
1739
61.2k
  // SourceLineCache for it on demand.
1740
61.2k
  if (!Content->SourceLineCache) {
1741
508
    bool MyInvalid = false;
1742
508
    ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
1743
508
    if (MyInvalid)
1744
0
      return SourceLocation();
1745
61.2k
  }
1746
61.2k
1747
61.2k
  if (Line > Content->NumLines) {
1748
3
    unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
1749
3
    if (Size > 0)
1750
3
      --Size;
1751
3
    return FileLoc.getLocWithOffset(Size);
1752
3
  }
1753
61.2k
1754
61.2k
  const llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
1755
61.2k
  unsigned FilePos = Content->SourceLineCache[Line - 1];
1756
61.2k
  const char *Buf = Buffer->getBufferStart() + FilePos;
1757
61.2k
  unsigned BufLength = Buffer->getBufferSize() - FilePos;
1758
61.2k
  if (BufLength == 0)
1759
10
    return FileLoc.getLocWithOffset(FilePos);
1760
61.2k
1761
61.2k
  unsigned i = 0;
1762
61.2k
1763
61.2k
  // Check that the given column is valid.
1764
320k
  while (i < BufLength-1 && 
i < Col-1320k
&&
Buf[i] != '\n'259k
&&
Buf[i] != '\r'259k
)
1765
259k
    ++i;
1766
61.2k
  return FileLoc.getLocWithOffset(FilePos + i);
1767
61.2k
}
1768
1769
/// Compute a map of macro argument chunks to their expanded source
1770
/// location. Chunks that are not part of a macro argument will map to an
1771
/// invalid source location. e.g. if a file contains one macro argument at
1772
/// offset 100 with length 10, this is how the map will be formed:
1773
///     0   -> SourceLocation()
1774
///     100 -> Expanded macro arg location
1775
///     110 -> SourceLocation()
1776
void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1777
261
                                          FileID FID) const {
1778
261
  assert(FID.isValid());
1779
261
1780
261
  // Initially no macro argument chunk is present.
1781
261
  MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1782
261
1783
261
  int ID = FID.ID;
1784
1.54k
  while (true) {
1785
1.54k
    ++ID;
1786
1.54k
    // Stop if there are no more FileIDs to check.
1787
1.54k
    if (ID > 0) {
1788
1.39k
      if (unsigned(ID) >= local_sloc_entry_size())
1789
194
        return;
1790
145
    } else if (ID == -1) {
1791
37
      return;
1792
37
    }
1793
1.31k
1794
1.31k
    bool Invalid = false;
1795
1.31k
    const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1796
1.31k
    if (Invalid)
1797
0
      return;
1798
1.31k
    if (Entry.isFile()) {
1799
388
      SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1800
388
      if (IncludeLoc.isInvalid())
1801
281
        continue;
1802
107
      if (!isInFileID(IncludeLoc, FID))
1803
29
        return; // No more files/macros that may be "contained" in this file.
1804
78
1805
78
      // Skip the files/macros of the #include'd file, we only care about macros
1806
78
      // that lexed macro arguments from our file.
1807
78
      if (Entry.getFile().NumCreatedFIDs)
1808
78
        ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1809
78
      continue;
1810
78
    }
1811
924
1812
924
    const ExpansionInfo &ExpInfo = Entry.getExpansion();
1813
924
1814
924
    if (ExpInfo.getExpansionLocStart().isFileID()) {
1815
358
      if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1816
1
        return; // No more files/macros that may be "contained" in this file.
1817
923
    }
1818
923
1819
923
    if (!ExpInfo.isMacroArgExpansion())
1820
424
      continue;
1821
499
1822
499
    associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1823
499
                                 ExpInfo.getSpellingLoc(),
1824
499
                                 SourceLocation::getMacroLoc(Entry.getOffset()),
1825
499
                                 getFileIDSize(FileID::get(ID)));
1826
499
  }
1827
261
}
1828
1829
void SourceManager::associateFileChunkWithMacroArgExp(
1830
                                         MacroArgsMap &MacroArgsCache,
1831
                                         FileID FID,
1832
                                         SourceLocation SpellLoc,
1833
                                         SourceLocation ExpansionLoc,
1834
542
                                         unsigned ExpansionLength) const {
1835
542
  if (!SpellLoc.isFileID()) {
1836
48
    unsigned SpellBeginOffs = SpellLoc.getOffset();
1837
48
    unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1838
48
1839
48
    // The spelling range for this macro argument expansion can span multiple
1840
48
    // consecutive FileID entries. Go through each entry contained in the
1841
48
    // spelling range and if one is itself a macro argument expansion, recurse
1842
48
    // and associate the file chunk that it represents.
1843
48
1844
48
    FileID SpellFID; // Current FileID in the spelling range.
1845
48
    unsigned SpellRelativeOffs;
1846
48
    std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1847
48
    while (true) {
1848
48
      const SLocEntry &Entry = getSLocEntry(SpellFID);
1849
48
      unsigned SpellFIDBeginOffs = Entry.getOffset();
1850
48
      unsigned SpellFIDSize = getFileIDSize(SpellFID);
1851
48
      unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1852
48
      const ExpansionInfo &Info = Entry.getExpansion();
1853
48
      if (Info.isMacroArgExpansion()) {
1854
43
        unsigned CurrSpellLength;
1855
43
        if (SpellFIDEndOffs < SpellEndOffs)
1856
0
          CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1857
43
        else
1858
43
          CurrSpellLength = ExpansionLength;
1859
43
        associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1860
43
                      Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1861
43
                      ExpansionLoc, CurrSpellLength);
1862
43
      }
1863
48
1864
48
      if (SpellFIDEndOffs >= SpellEndOffs)
1865
48
        return; // we covered all FileID entries in the spelling range.
1866
0
1867
0
      // Move to the next FileID entry in the spelling range.
1868
0
      unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1869
0
      ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1870
0
      ExpansionLength -= advance;
1871
0
      ++SpellFID.ID;
1872
0
      SpellRelativeOffs = 0;
1873
0
    }
1874
48
  }
1875
542
1876
542
  assert(SpellLoc.isFileID());
1877
494
1878
494
  unsigned BeginOffs;
1879
494
  if (!isInFileID(SpellLoc, FID, &BeginOffs))
1880
0
    return;
1881
494
1882
494
  unsigned EndOffs = BeginOffs + ExpansionLength;
1883
494
1884
494
  // Add a new chunk for this macro argument. A previous macro argument chunk
1885
494
  // may have been lexed again, so e.g. if the map is
1886
494
  //     0   -> SourceLocation()
1887
494
  //     100 -> Expanded loc #1
1888
494
  //     110 -> SourceLocation()
1889
494
  // and we found a new macro FileID that lexed from offset 105 with length 3,
1890
494
  // the new map will be:
1891
494
  //     0   -> SourceLocation()
1892
494
  //     100 -> Expanded loc #1
1893
494
  //     105 -> Expanded loc #2
1894
494
  //     108 -> Expanded loc #1
1895
494
  //     110 -> SourceLocation()
1896
494
  //
1897
494
  // Since re-lexed macro chunks will always be the same size or less of
1898
494
  // previous chunks, we only need to find where the ending of the new macro
1899
494
  // chunk is mapped to and update the map with new begin/end mappings.
1900
494
1901
494
  MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1902
494
  --I;
1903
494
  SourceLocation EndOffsMappedLoc = I->second;
1904
494
  MacroArgsCache[BeginOffs] = ExpansionLoc;
1905
494
  MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1906
494
}
1907
1908
/// If \arg Loc points inside a function macro argument, the returned
1909
/// location will be the macro location in which the argument was expanded.
1910
/// If a macro argument is used multiple times, the expanded location will
1911
/// be at the first expansion of the argument.
1912
/// e.g.
1913
///   MY_MACRO(foo);
1914
///             ^
1915
/// Passing a file location pointing at 'foo', will yield a macro location
1916
/// where 'foo' was expanded into.
1917
SourceLocation
1918
9.91k
SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
1919
9.91k
  if (Loc.isInvalid() || !Loc.isFileID())
1920
0
    return Loc;
1921
9.91k
1922
9.91k
  FileID FID;
1923
9.91k
  unsigned Offset;
1924
9.91k
  std::tie(FID, Offset) = getDecomposedLoc(Loc);
1925
9.91k
  if (FID.isInvalid())
1926
0
    return Loc;
1927
9.91k
1928
9.91k
  std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1929
9.91k
  if (!MacroArgsCache) {
1930
261
    MacroArgsCache = llvm::make_unique<MacroArgsMap>();
1931
261
    computeMacroArgsCache(*MacroArgsCache, FID);
1932
261
  }
1933
9.91k
1934
9.91k
  assert(!MacroArgsCache->empty());
1935
9.91k
  MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1936
9.91k
  --I;
1937
9.91k
1938
9.91k
  unsigned MacroArgBeginOffs = I->first;
1939
9.91k
  SourceLocation MacroArgExpandedLoc = I->second;
1940
9.91k
  if (MacroArgExpandedLoc.isValid())
1941
129
    return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1942
9.78k
1943
9.78k
  return Loc;
1944
9.78k
}
1945
1946
std::pair<FileID, unsigned>
1947
635k
SourceManager::getDecomposedIncludedLoc(FileID FID) const {
1948
635k
  if (FID.isInvalid())
1949
0
    return std::make_pair(FileID(), 0);
1950
635k
1951
635k
  // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1952
635k
1953
635k
  using DecompTy = std::pair<FileID, unsigned>;
1954
635k
  auto InsertOp = IncludedLocMap.try_emplace(FID);
1955
635k
  DecompTy &DecompLoc = InsertOp.first->second;
1956
635k
  if (!InsertOp.second)
1957
477k
    return DecompLoc; // already in map.
1958
158k
1959
158k
  SourceLocation UpperLoc;
1960
158k
  bool Invalid = false;
1961
158k
  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1962
158k
  if (!Invalid) {
1963
158k
    if (Entry.isExpansion())
1964
74.4k
      UpperLoc = Entry.getExpansion().getExpansionLocStart();
1965
83.5k
    else
1966
83.5k
      UpperLoc = Entry.getFile().getIncludeLoc();
1967
158k
  }
1968
158k
1969
158k
  if (UpperLoc.isValid())
1970
151k
    DecompLoc = getDecomposedLoc(UpperLoc);
1971
158k
1972
158k
  return DecompLoc;
1973
158k
}
1974
1975
/// Given a decomposed source location, move it up the include/expansion stack
1976
/// to the parent source location.  If this is possible, return the decomposed
1977
/// version of the parent in Loc and return false.  If Loc is the top-level
1978
/// entry, return true and don't modify it.
1979
static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1980
552k
                                   const SourceManager &SM) {
1981
552k
  std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1982
552k
  if (UpperLoc.first.isInvalid())
1983
188k
    return true; // We reached the top.
1984
363k
1985
363k
  Loc = UpperLoc;
1986
363k
  return false;
1987
363k
}
1988
1989
/// Return the cache entry for comparing the given file IDs
1990
/// for isBeforeInTranslationUnit.
1991
InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1992
1.71M
                                                            FileID RFID) const {
1993
1.71M
  // This is a magic number for limiting the cache size.  It was experimentally
1994
1.71M
  // derived from a small Objective-C project (where the cache filled
1995
1.71M
  // out to ~250 items).  We can make it larger if necessary.
1996
1.71M
  enum { MagicCacheSize = 300 };
1997
1.71M
  IsBeforeInTUCacheKey Key(LFID, RFID);
1998
1.71M
1999
1.71M
  // If the cache size isn't too large, do a lookup and if necessary default
2000
1.71M
  // construct an entry.  We can then return it to the caller for direct
2001
1.71M
  // use.  When they update the value, the cache will get automatically
2002
1.71M
  // updated as well.
2003
1.71M
  if (IBTUCache.size() < MagicCacheSize)
2004
1.71M
    return IBTUCache[Key];
2005
0
2006
0
  // Otherwise, do a lookup that will not construct a new value.
2007
0
  InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2008
0
  if (I != IBTUCache.end())
2009
0
    return I->second;
2010
0
2011
0
  // Fall back to the overflow value.
2012
0
  return IBTUCacheOverflow;
2013
0
}
2014
2015
/// Determines the order of 2 source locations in the translation unit.
2016
///
2017
/// \returns true if LHS source location comes before RHS, false otherwise.
2018
bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2019
30.2M
                                              SourceLocation RHS) const {
2020
30.2M
  assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2021
30.2M
  if (LHS == RHS)
2022
112k
    return false;
2023
30.1M
2024
30.1M
  std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2025
30.1M
  std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2026
30.1M
2027
30.1M
  // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2028
30.1M
  // is a serialized one referring to a file that was removed after we loaded
2029
30.1M
  // the PCH.
2030
30.1M
  if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2031
0
    return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2032
30.1M
2033
30.1M
  std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2034
30.1M
  if (InSameTU.first)
2035
30.0M
    return InSameTU.second;
2036
65.5k
2037
65.5k
  // If we arrived here, the location is either in a built-ins buffer or
2038
65.5k
  // associated with global inline asm. PR5662 and PR22576 are examples.
2039
65.5k
2040
65.5k
  StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
2041
65.5k
  StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
2042
65.5k
  bool LIsBuiltins = LB == "<built-in>";
2043
65.5k
  bool RIsBuiltins = RB == "<built-in>";
2044
65.5k
  // Sort built-in before non-built-in.
2045
65.5k
  if (LIsBuiltins || 
RIsBuiltins7.47k
) {
2046
65.5k
    if (LIsBuiltins != RIsBuiltins)
2047
65.5k
      return LIsBuiltins;
2048
0
    // Both are in built-in buffers, but from different files. We just claim that
2049
0
    // lower IDs come first.
2050
0
    return LOffs.first < ROffs.first;
2051
0
  }
2052
0
  bool LIsAsm = LB == "<inline asm>";
2053
0
  bool RIsAsm = RB == "<inline asm>";
2054
0
  // Sort assembler after built-ins, but before the rest.
2055
0
  if (LIsAsm || RIsAsm) {
2056
0
    if (LIsAsm != RIsAsm)
2057
0
      return RIsAsm;
2058
0
    assert(LOffs.first == ROffs.first);
2059
0
    return false;
2060
0
  }
2061
0
  bool LIsScratch = LB == "<scratch space>";
2062
0
  bool RIsScratch = RB == "<scratch space>";
2063
0
  // Sort scratch after inline asm, but before the rest.
2064
0
  if (LIsScratch || RIsScratch) {
2065
0
    if (LIsScratch != RIsScratch)
2066
0
      return LIsScratch;
2067
0
    return LOffs.second < ROffs.second;
2068
0
  }
2069
0
  llvm_unreachable("Unsortable locations found");
2070
0
}
2071
2072
std::pair<bool, bool> SourceManager::isInTheSameTranslationUnit(
2073
    std::pair<FileID, unsigned> &LOffs,
2074
30.1M
    std::pair<FileID, unsigned> &ROffs) const {
2075
30.1M
  // If the source locations are in the same file, just compare offsets.
2076
30.1M
  if (LOffs.first == ROffs.first)
2077
28.4M
    return std::make_pair(true, LOffs.second < ROffs.second);
2078
1.71M
2079
1.71M
  // If we are comparing a source location with multiple locations in the same
2080
1.71M
  // file, we get a big win by caching the result.
2081
1.71M
  InBeforeInTUCacheEntry &IsBeforeInTUCache =
2082
1.71M
    getInBeforeInTUCache(LOffs.first, ROffs.first);
2083
1.71M
2084
1.71M
  // If we are comparing a source location with multiple locations in the same
2085
1.71M
  // file, we get a big win by caching the result.
2086
1.71M
  if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2087
1.57M
    return std::make_pair(
2088
1.57M
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2089
139k
2090
139k
  // Okay, we missed in the cache, start updating the cache for this query.
2091
139k
  IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2092
139k
                          /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2093
139k
2094
139k
  // We need to find the common ancestor. The only way of doing this is to
2095
139k
  // build the complete include chain for one and then walking up the chain
2096
139k
  // of the other looking for a match.
2097
139k
  // We use a map from FileID to Offset to store the chain. Easier than writing
2098
139k
  // a custom set hash info that only depends on the first part of a pair.
2099
139k
  using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2100
139k
  LocSet LChain;
2101
343k
  do {
2102
343k
    LChain.insert(LOffs);
2103
343k
    // We catch the case where LOffs is in a file included by ROffs and
2104
343k
    // quit early. The other way round unfortunately remains suboptimal.
2105
343k
  } while (LOffs.first != ROffs.first && 
!MoveUpIncludeHierarchy(LOffs, *this)327k
);
2106
139k
  LocSet::iterator I;
2107
299k
  while((I = LChain.find(ROffs.first)) == LChain.end()) {
2108
224k
    if (MoveUpIncludeHierarchy(ROffs, *this))
2109
65.5k
      break; // Met at topmost file.
2110
224k
  }
2111
139k
  if (I != LChain.end())
2112
74.3k
    LOffs = *I;
2113
139k
2114
139k
  // If we exited because we found a nearest common ancestor, compare the
2115
139k
  // locations within the common file and cache them.
2116
139k
  if (LOffs.first == ROffs.first) {
2117
74.3k
    IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2118
74.3k
    return std::make_pair(
2119
74.3k
        true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2120
74.3k
  }
2121
65.5k
  // Clear the lookup cache, it depends on a common location.
2122
65.5k
  IsBeforeInTUCache.clear();
2123
65.5k
  return std::make_pair(false, false);
2124
65.5k
}
2125
2126
3
void SourceManager::PrintStats() const {
2127
3
  llvm::errs() << "\n*** Source Manager Stats:\n";
2128
3
  llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2129
3
               << " mem buffers mapped.\n";
2130
3
  llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2131
3
               << llvm::capacity_in_bytes(LocalSLocEntryTable)
2132
3
               << " bytes of capacity), "
2133
3
               << NextLocalOffset << "B of Sloc address space used.\n";
2134
3
  llvm::errs() << LoadedSLocEntryTable.size()
2135
3
               << " loaded SLocEntries allocated, "
2136
3
               << MaxLoadedOffset - CurrentLoadedOffset
2137
3
               << "B of Sloc address space used.\n";
2138
3
2139
3
  unsigned NumLineNumsComputed = 0;
2140
3
  unsigned NumFileBytesMapped = 0;
2141
9
  for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; 
++I6
){
2142
6
    NumLineNumsComputed += I->second->SourceLineCache != nullptr;
2143
6
    NumFileBytesMapped  += I->second->getSizeBytesMapped();
2144
6
  }
2145
3
  unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2146
3
2147
3
  llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2148
3
               << NumLineNumsComputed << " files with line #'s computed, "
2149
3
               << NumMacroArgsComputed << " files with macro args computed.\n";
2150
3
  llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2151
3
               << NumBinaryProbes << " binary.\n";
2152
3
}
2153
2154
0
LLVM_DUMP_METHOD void SourceManager::dump() const {
2155
0
  llvm::raw_ostream &out = llvm::errs();
2156
0
2157
0
  auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2158
0
                           llvm::Optional<unsigned> NextStart) {
2159
0
    out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2160
0
        << " <SourceLocation " << Entry.getOffset() << ":";
2161
0
    if (NextStart)
2162
0
      out << *NextStart << ">\n";
2163
0
    else
2164
0
      out << "???\?>\n";
2165
0
    if (Entry.isFile()) {
2166
0
      auto &FI = Entry.getFile();
2167
0
      if (FI.NumCreatedFIDs)
2168
0
        out << "  covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2169
0
            << ">\n";
2170
0
      if (FI.getIncludeLoc().isValid())
2171
0
        out << "  included from " << FI.getIncludeLoc().getOffset() << "\n";
2172
0
      if (auto *CC = FI.getContentCache()) {
2173
0
        out << "  for " << (CC->OrigEntry ? CC->OrigEntry->getName() : "<none>")
2174
0
            << "\n";
2175
0
        if (CC->BufferOverridden)
2176
0
          out << "  contents overridden\n";
2177
0
        if (CC->ContentsEntry != CC->OrigEntry) {
2178
0
          out << "  contents from "
2179
0
              << (CC->ContentsEntry ? CC->ContentsEntry->getName() : "<none>")
2180
0
              << "\n";
2181
0
        }
2182
0
      }
2183
0
    } else {
2184
0
      auto &EI = Entry.getExpansion();
2185
0
      out << "  spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2186
0
      out << "  macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2187
0
          << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2188
0
          << EI.getExpansionLocEnd().getOffset() << ">\n";
2189
0
    }
2190
0
  };
2191
0
2192
0
  // Dump local SLocEntries.
2193
0
  for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2194
0
    DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2195
0
                  ID == NumIDs - 1 ? NextLocalOffset
2196
0
                                   : LocalSLocEntryTable[ID + 1].getOffset());
2197
0
  }
2198
0
  // Dump loaded SLocEntries.
2199
0
  llvm::Optional<unsigned> NextStart;
2200
0
  for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2201
0
    int ID = -(int)Index - 2;
2202
0
    if (SLocEntryLoaded[Index]) {
2203
0
      DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2204
0
      NextStart = LoadedSLocEntryTable[Index].getOffset();
2205
0
    } else {
2206
0
      NextStart = None;
2207
0
    }
2208
0
  }
2209
0
}
2210
2211
5.27k
ExternalSLocEntrySource::~ExternalSLocEntrySource() = default;
2212
2213
/// Return the amount of memory used by memory buffers, breaking down
2214
/// by heap-backed versus mmap'ed memory.
2215
1
SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2216
1
  size_t malloc_bytes = 0;
2217
1
  size_t mmap_bytes = 0;
2218
1
2219
2
  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; 
++i1
)
2220
1
    if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2221
1
      switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2222
1
        case llvm::MemoryBuffer::MemoryBuffer_MMap:
2223
0
          mmap_bytes += sized_mapped;
2224
0
          break;
2225
1
        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2226
1
          malloc_bytes += sized_mapped;
2227
1
          break;
2228
1
      }
2229
1
2230
1
  return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2231
1
}
2232
2233
1
size_t SourceManager::getDataStructureSizes() const {
2234
1
  size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2235
1
    + llvm::capacity_in_bytes(LocalSLocEntryTable)
2236
1
    + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2237
1
    + llvm::capacity_in_bytes(SLocEntryLoaded)
2238
1
    + llvm::capacity_in_bytes(FileInfos);
2239
1
2240
1
  if (OverriddenFilesInfo)
2241
0
    size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2242
1
2243
1
  return size;
2244
1
}
2245
2246
SourceManagerForFile::SourceManagerForFile(StringRef FileName,
2247
30.7k
                                           StringRef Content) {
2248
30.7k
  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2249
30.7k
  // is deleted.
2250
30.7k
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
2251
30.7k
      new llvm::vfs::InMemoryFileSystem);
2252
30.7k
  InMemoryFileSystem->addFile(
2253
30.7k
      FileName, 0,
2254
30.7k
      llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2255
30.7k
                                       /*RequiresNullTerminator=*/false));
2256
30.7k
  // This is passed to `SM` as reference, so the pointer has to be referenced
2257
30.7k
  // in `Environment` so that `FileMgr` can out-live this function scope.
2258
30.7k
  FileMgr =
2259
30.7k
      llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2260
30.7k
  // This is passed to `SM` as reference, so the pointer has to be referenced
2261
30.7k
  // by `Environment` due to the same reason above.
2262
30.7k
  Diagnostics = llvm::make_unique<DiagnosticsEngine>(
2263
30.7k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
2264
30.7k
      new DiagnosticOptions);
2265
30.7k
  SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2266
30.7k
  FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
2267
30.7k
                                      SourceLocation(), clang::SrcMgr::C_User);
2268
30.7k
  assert(ID.isValid());
2269
30.7k
  SourceMgr->setMainFileID(ID);
2270
30.7k
}