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