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  assert(Buffer);
63 
64  // Should be unreachable, but keep for sanity.
65  if (!Buffer)
66  return llvm::MemoryBuffer::MemoryBuffer_Malloc;
67 
68  return Buffer->getBufferKind();
69 }
70 
71 /// getSize - Returns the size of the content encapsulated by this ContentCache.
72 /// This can be the size of the source file or the size of an arbitrary
73 /// scratch buffer. If the ContentCache encapsulates a source file, that
74 /// file is not lazily brought in from disk to satisfy this query.
75 unsigned ContentCache::getSize() const {
76  return Buffer ? (unsigned)Buffer->getBufferSize()
78 }
79 
80 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
81  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
82  // (BOM). We only support UTF-8 with and without a BOM right now. See
83  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
84  const char *InvalidBOM =
85  llvm::StringSwitch<const char *>(BufStr)
86  .StartsWith(llvm::StringLiteral::withInnerNUL("\x00\x00\xFE\xFF"),
87  "UTF-32 (BE)")
88  .StartsWith(llvm::StringLiteral::withInnerNUL("\xFF\xFE\x00\x00"),
89  "UTF-32 (LE)")
90  .StartsWith("\xFE\xFF", "UTF-16 (BE)")
91  .StartsWith("\xFF\xFE", "UTF-16 (LE)")
92  .StartsWith("\x2B\x2F\x76", "UTF-7")
93  .StartsWith("\xF7\x64\x4C", "UTF-1")
94  .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
95  .StartsWith("\x0E\xFE\xFF", "SCSU")
96  .StartsWith("\xFB\xEE\x28", "BOCU-1")
97  .StartsWith("\x84\x31\x95\x33", "GB-18030")
98  .Default(nullptr);
99 
100  return InvalidBOM;
101 }
102 
105  SourceLocation Loc) const {
106  // Lazily create the Buffer for ContentCaches that wrap files. If we already
107  // computed it, just return what we have.
108  if (IsBufferInvalid)
109  return None;
110  if (Buffer)
111  return Buffer->getMemBufferRef();
112  if (!ContentsEntry)
113  return None;
114 
115  // Start with the assumption that the buffer is invalid to simplify early
116  // return paths.
117  IsBufferInvalid = true;
118 
119  auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
120 
121  // If we were unable to open the file, then we are in an inconsistent
122  // situation where the content cache referenced a file which no longer
123  // exists. Most likely, we were using a stat cache with an invalid entry but
124  // the file could also have been removed during processing. Since we can't
125  // really deal with this situation, just create an empty buffer.
126  if (!BufferOrError) {
127  if (Diag.isDiagnosticInFlight())
128  Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
130  BufferOrError.getError().message());
131  else
132  Diag.Report(Loc, diag::err_cannot_open_file)
133  << ContentsEntry->getName() << BufferOrError.getError().message();
134 
135  return None;
136  }
137 
138  Buffer = std::move(*BufferOrError);
139 
140  // Check that the file's size fits in an 'unsigned' (with room for a
141  // past-the-end value). This is deeply regrettable, but various parts of
142  // Clang (including elsewhere in this file!) use 'unsigned' to represent file
143  // offsets, line numbers, string literal lengths, and so on, and fail
144  // miserably on large source files.
145  //
146  // Note: ContentsEntry could be a named pipe, in which case
147  // ContentsEntry::getSize() could have the wrong size. Use
148  // MemoryBuffer::getBufferSize() instead.
149  if (Buffer->getBufferSize() >= std::numeric_limits<unsigned>::max()) {
150  if (Diag.isDiagnosticInFlight())
151  Diag.SetDelayedDiagnostic(diag::err_file_too_large,
153  else
154  Diag.Report(Loc, diag::err_file_too_large)
155  << ContentsEntry->getName();
156 
157  return None;
158  }
159 
160  // Unless this is a named pipe (in which case we can handle a mismatch),
161  // check that the file's size is the same as in the file entry (which may
162  // have come from a stat cache).
163  if (!ContentsEntry->isNamedPipe() &&
164  Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
165  if (Diag.isDiagnosticInFlight())
166  Diag.SetDelayedDiagnostic(diag::err_file_modified,
168  else
169  Diag.Report(Loc, diag::err_file_modified)
170  << ContentsEntry->getName();
171 
172  return None;
173  }
174 
175  // If the buffer is valid, check to see if it has a UTF Byte Order Mark
176  // (BOM). We only support UTF-8 with and without a BOM right now. See
177  // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
178  StringRef BufStr = Buffer->getBuffer();
179  const char *InvalidBOM = getInvalidBOM(BufStr);
180 
181  if (InvalidBOM) {
182  Diag.Report(Loc, diag::err_unsupported_bom)
183  << InvalidBOM << ContentsEntry->getName();
184  return None;
185  }
186 
187  // Buffer has been validated.
188  IsBufferInvalid = false;
189  return Buffer->getMemBufferRef();
190 }
191 
192 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
193  auto IterBool = FilenameIDs.try_emplace(Name, FilenamesByID.size());
194  if (IterBool.second)
195  FilenamesByID.push_back(&*IterBool.first);
196  return IterBool.first->second;
197 }
198 
199 /// Add a line note to the line table that indicates that there is a \#line or
200 /// GNU line marker at the specified FID/Offset location which changes the
201 /// presumed location to LineNo/FilenameID. If EntryExit is 0, then this doesn't
202 /// change the presumed \#include stack. If it is 1, this is a file entry, if
203 /// it is 2 then this is a file exit. FileKind specifies whether this is a
204 /// system header or extern C system header.
205 void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo,
206  int FilenameID, unsigned EntryExit,
207  SrcMgr::CharacteristicKind FileKind) {
208  std::vector<LineEntry> &Entries = LineEntries[FID];
209 
210  // An unspecified FilenameID means use the last filename if available, or the
211  // main source file otherwise.
212  if (FilenameID == -1 && !Entries.empty())
213  FilenameID = Entries.back().FilenameID;
214 
215  assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
216  "Adding line entries out of order!");
217 
218  unsigned IncludeOffset = 0;
219  if (EntryExit == 0) { // No #include stack change.
220  IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
221  } else if (EntryExit == 1) {
222  IncludeOffset = Offset-1;
223  } else if (EntryExit == 2) {
224  assert(!Entries.empty() && Entries.back().IncludeOffset &&
225  "PPDirectives should have caught case when popping empty include stack");
226 
227  // Get the include loc of the last entries' include loc as our include loc.
228  IncludeOffset = 0;
229  if (const LineEntry *PrevEntry =
230  FindNearestLineEntry(FID, Entries.back().IncludeOffset))
231  IncludeOffset = PrevEntry->IncludeOffset;
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  // Sanity checking, otherwise a bug may lead to hanging in release build.
866  if (SLocOffset < CurrentLoadedOffset) {
867  assert(0 && "Invalid SLocOffset or bad function choice");
868  return FileID();
869  }
870 
871  // Essentially the same as the local case, but the loaded array is sorted
872  // in the other direction.
873 
874  // First do a linear scan from the last lookup position, if possible.
875  unsigned I;
876  int LastID = LastFileIDLookup.ID;
877  if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
878  I = 0;
879  else
880  I = (-LastID - 2) + 1;
881 
882  unsigned NumProbes;
883  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
884  // Make sure the entry is loaded!
886  if (E.getOffset() <= SLocOffset) {
887  FileID Res = FileID::get(-int(I) - 2);
888  LastFileIDLookup = Res;
889  NumLinearScans += NumProbes + 1;
890  return Res;
891  }
892  }
893 
894  // Linear scan failed. Do the binary search. Note the reverse sorting of the
895  // table: GreaterIndex is the one where the offset is greater, which is
896  // actually a lower index!
897  unsigned GreaterIndex = I;
898  unsigned LessIndex = LoadedSLocEntryTable.size();
899  NumProbes = 0;
900  while (true) {
901  ++NumProbes;
902  unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
903  const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
904  if (E.getOffset() == 0)
905  return FileID(); // invalid entry.
906 
907  ++NumProbes;
908 
909  if (E.getOffset() > SLocOffset) {
910  // Sanity checking, otherwise a bug may lead to hanging in release build.
911  if (GreaterIndex == MiddleIndex) {
912  assert(0 && "binary search missed the entry");
913  return FileID();
914  }
915  GreaterIndex = MiddleIndex;
916  continue;
917  }
918 
919  if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
920  FileID Res = FileID::get(-int(MiddleIndex) - 2);
921  LastFileIDLookup = Res;
922  NumBinaryProbes += NumProbes;
923  return Res;
924  }
925 
926  // Sanity checking, otherwise a bug may lead to hanging in release build.
927  if (LessIndex == MiddleIndex) {
928  assert(0 && "binary search missed the entry");
929  return FileID();
930  }
931  LessIndex = MiddleIndex;
932  }
933 }
934 
935 SourceLocation SourceManager::
936 getExpansionLocSlowCase(SourceLocation Loc) const {
937  do {
938  // Note: If Loc indicates an offset into a token that came from a macro
939  // expansion (e.g. the 5th character of the token) we do not want to add
940  // this offset when going to the expansion location. The expansion
941  // location is the macro invocation, which the offset has nothing to do
942  // with. This is unlike when we get the spelling loc, because the offset
943  // directly correspond to the token whose spelling we're inspecting.
945  } while (!Loc.isFileID());
946 
947  return Loc;
948 }
949 
950 SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
951  do {
952  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
953  Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
954  Loc = Loc.getLocWithOffset(LocInfo.second);
955  } while (!Loc.isFileID());
956  return Loc;
957 }
958 
959 SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
960  do {
961  if (isMacroArgExpansion(Loc))
962  Loc = getImmediateSpellingLoc(Loc);
963  else
965  } while (!Loc.isFileID());
966  return Loc;
967 }
968 
969 
970 std::pair<FileID, unsigned>
971 SourceManager::getDecomposedExpansionLocSlowCase(
972  const SrcMgr::SLocEntry *E) const {
973  // If this is an expansion record, walk through all the expansion points.
974  FileID FID;
975  SourceLocation Loc;
976  unsigned Offset;
977  do {
978  Loc = E->getExpansion().getExpansionLocStart();
979 
980  FID = getFileID(Loc);
981  E = &getSLocEntry(FID);
982  Offset = Loc.getOffset()-E->getOffset();
983  } while (!Loc.isFileID());
984 
985  return std::make_pair(FID, Offset);
986 }
987 
988 std::pair<FileID, unsigned>
989 SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
990  unsigned Offset) const {
991  // If this is an expansion record, walk through all the expansion points.
992  FileID FID;
993  SourceLocation Loc;
994  do {
995  Loc = E->getExpansion().getSpellingLoc();
996  Loc = Loc.getLocWithOffset(Offset);
997 
998  FID = getFileID(Loc);
999  E = &getSLocEntry(FID);
1000  Offset = Loc.getOffset()-E->getOffset();
1001  } while (!Loc.isFileID());
1002 
1003  return std::make_pair(FID, Offset);
1004 }
1005 
1006 /// getImmediateSpellingLoc - Given a SourceLocation object, return the
1007 /// spelling location referenced by the ID. This is the first level down
1008 /// towards the place where the characters that make up the lexed token can be
1009 /// found. This should not generally be used by clients.
1011  if (Loc.isFileID()) return Loc;
1012  std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
1013  Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
1014  return Loc.getLocWithOffset(LocInfo.second);
1015 }
1016 
1017 /// Return the filename of the file containing a SourceLocation.
1018 StringRef SourceManager::getFilename(SourceLocation SpellingLoc) const {
1019  if (const FileEntry *F = getFileEntryForID(getFileID(SpellingLoc)))
1020  return F->getName();
1021  return StringRef();
1022 }
1023 
1024 /// getImmediateExpansionRange - Loc is required to be an expansion location.
1025 /// Return the start/end of the expansion information.
1028  assert(Loc.isMacroID() && "Not a macro expansion loc!");
1029  const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
1030  return Expansion.getExpansionLocRange();
1031 }
1032 
1034  while (isMacroArgExpansion(Loc))
1035  Loc = getImmediateSpellingLoc(Loc);
1036  return Loc;
1037 }
1038 
1039 /// getExpansionRange - Given a SourceLocation object, return the range of
1040 /// tokens covered by the expansion in the ultimate file.
1042  if (Loc.isFileID())
1043  return CharSourceRange(SourceRange(Loc, Loc), true);
1044 
1046 
1047  // Fully resolve the start and end locations to their ultimate expansion
1048  // points.
1049  while (!Res.getBegin().isFileID())
1051  while (!Res.getEnd().isFileID()) {
1053  Res.setEnd(EndRange.getEnd());
1054  Res.setTokenRange(EndRange.isTokenRange());
1055  }
1056  return Res;
1057 }
1058 
1060  SourceLocation *StartLoc) const {
1061  if (!Loc.isMacroID()) return false;
1062 
1063  FileID FID = getFileID(Loc);
1064  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1065  if (!Expansion.isMacroArgExpansion()) return false;
1066 
1067  if (StartLoc)
1068  *StartLoc = Expansion.getExpansionLocStart();
1069  return true;
1070 }
1071 
1073  if (!Loc.isMacroID()) return false;
1074 
1075  FileID FID = getFileID(Loc);
1076  const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1077  return Expansion.isMacroBodyExpansion();
1078 }
1079 
1081  SourceLocation *MacroBegin) const {
1082  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1083 
1084  std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1085  if (DecompLoc.second > 0)
1086  return false; // Does not point at the start of expansion range.
1087 
1088  bool Invalid = false;
1089  const SrcMgr::ExpansionInfo &ExpInfo =
1090  getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1091  if (Invalid)
1092  return false;
1093  SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1094 
1095  if (ExpInfo.isMacroArgExpansion()) {
1096  // For macro argument expansions, check if the previous FileID is part of
1097  // the same argument expansion, in which case this Loc is not at the
1098  // beginning of the expansion.
1099  FileID PrevFID = getPreviousFileID(DecompLoc.first);
1100  if (!PrevFID.isInvalid()) {
1101  const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1102  if (Invalid)
1103  return false;
1104  if (PrevEntry.isExpansion() &&
1105  PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1106  return false;
1107  }
1108  }
1109 
1110  if (MacroBegin)
1111  *MacroBegin = ExpLoc;
1112  return true;
1113 }
1114 
1116  SourceLocation *MacroEnd) const {
1117  assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1118 
1119  FileID FID = getFileID(Loc);
1120  SourceLocation NextLoc = Loc.getLocWithOffset(1);
1121  if (isInFileID(NextLoc, FID))
1122  return false; // Does not point at the end of expansion range.
1123 
1124  bool Invalid = false;
1125  const SrcMgr::ExpansionInfo &ExpInfo =
1126  getSLocEntry(FID, &Invalid).getExpansion();
1127  if (Invalid)
1128  return false;
1129 
1130  if (ExpInfo.isMacroArgExpansion()) {
1131  // For macro argument expansions, check if the next FileID is part of the
1132  // same argument expansion, in which case this Loc is not at the end of the
1133  // expansion.
1134  FileID NextFID = getNextFileID(FID);
1135  if (!NextFID.isInvalid()) {
1136  const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1137  if (Invalid)
1138  return false;
1139  if (NextEntry.isExpansion() &&
1140  NextEntry.getExpansion().getExpansionLocStart() ==
1141  ExpInfo.getExpansionLocStart())
1142  return false;
1143  }
1144  }
1145 
1146  if (MacroEnd)
1147  *MacroEnd = ExpInfo.getExpansionLocEnd();
1148  return true;
1149 }
1150 
1151 //===----------------------------------------------------------------------===//
1152 // Queries about the code at a SourceLocation.
1153 //===----------------------------------------------------------------------===//
1154 
1155 /// getCharacterData - Return a pointer to the start of the specified location
1156 /// in the appropriate MemoryBuffer.
1158  bool *Invalid) const {
1159  // Note that this is a hot function in the getSpelling() path, which is
1160  // heavily used by -E mode.
1161  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
1162 
1163  // Note that calling 'getBuffer()' may lazily page in a source file.
1164  bool CharDataInvalid = false;
1165  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1166  if (CharDataInvalid || !Entry.isFile()) {
1167  if (Invalid)
1168  *Invalid = true;
1169 
1170  return "<<<<INVALID BUFFER>>>>";
1171  }
1174  SourceLocation());
1175  if (Invalid)
1176  *Invalid = !Buffer;
1177  return Buffer ? Buffer->getBufferStart() + LocInfo.second
1178  : "<<<<INVALID BUFFER>>>>";
1179 }
1180 
1181 /// getColumnNumber - Return the column # for the specified file position.
1182 /// this is significantly cheaper to compute than the line number.
1183 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1184  bool *Invalid) const {
1186  if (Invalid)
1187  *Invalid = !MemBuf;
1188 
1189  if (!MemBuf)
1190  return 1;
1191 
1192  // It is okay to request a position just past the end of the buffer.
1193  if (FilePos > MemBuf->getBufferSize()) {
1194  if (Invalid)
1195  *Invalid = true;
1196  return 1;
1197  }
1198 
1199  const char *Buf = MemBuf->getBufferStart();
1200  // See if we just calculated the line number for this FilePos and can use
1201  // that to lookup the start of the line instead of searching for it.
1202  if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache &&
1203  LastLineNoResult < LastLineNoContentCache->SourceLineCache.size()) {
1204  const unsigned *SourceLineCache =
1205  LastLineNoContentCache->SourceLineCache.begin();
1206  unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1207  unsigned LineEnd = SourceLineCache[LastLineNoResult];
1208  if (FilePos >= LineStart && FilePos < LineEnd) {
1209  // LineEnd is the LineStart of the next line.
1210  // A line ends with separator LF or CR+LF on Windows.
1211  // FilePos might point to the last separator,
1212  // but we need a column number at most 1 + the last column.
1213  if (FilePos + 1 == LineEnd && FilePos > LineStart) {
1214  if (Buf[FilePos - 1] == '\r' || Buf[FilePos - 1] == '\n')
1215  --FilePos;
1216  }
1217  return FilePos - LineStart + 1;
1218  }
1219  }
1220 
1221  unsigned LineStart = FilePos;
1222  while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1223  --LineStart;
1224  return FilePos-LineStart+1;
1225 }
1226 
1227 // isInvalid - Return the result of calling loc.isInvalid(), and
1228 // if Invalid is not null, set its value to same.
1229 template<typename LocType>
1230 static bool isInvalid(LocType Loc, bool *Invalid) {
1231  bool MyInvalid = Loc.isInvalid();
1232  if (Invalid)
1233  *Invalid = MyInvalid;
1234  return MyInvalid;
1235 }
1236 
1238  bool *Invalid) const {
1239  if (isInvalid(Loc, Invalid)) return 0;
1240  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1241  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1242 }
1243 
1245  bool *Invalid) const {
1246  if (isInvalid(Loc, Invalid)) return 0;
1247  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1248  return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
1249 }
1250 
1252  bool *Invalid) const {
1253  PresumedLoc PLoc = getPresumedLoc(Loc);
1254  if (isInvalid(PLoc, Invalid)) return 0;
1255  return PLoc.getColumn();
1256 }
1257 
1258 // Check if mutli-byte word x has bytes between m and n, included. This may also
1259 // catch bytes equal to n + 1.
1260 // The returned value holds a 0x80 at each byte position that holds a match.
1261 // see http://graphics.stanford.edu/~seander/bithacks.html#HasBetweenInWord
1262 template <class T>
1263 static constexpr inline T likelyhasbetween(T x, unsigned char m,
1264  unsigned char n) {
1265  return ((x - ~static_cast<T>(0) / 255 * (n + 1)) & ~x &
1266  ((x & ~static_cast<T>(0) / 255 * 127) +
1267  (~static_cast<T>(0) / 255 * (127 - (m - 1))))) &
1268  ~static_cast<T>(0) / 255 * 128;
1269 }
1270 
1271 LineOffsetMapping LineOffsetMapping::get(llvm::MemoryBufferRef Buffer,
1272  llvm::BumpPtrAllocator &Alloc) {
1273 
1274  // Find the file offsets of all of the *physical* source lines. This does
1275  // not look at trigraphs, escaped newlines, or anything else tricky.
1276  SmallVector<unsigned, 256> LineOffsets;
1277 
1278  // Line #1 starts at char 0.
1279  LineOffsets.push_back(0);
1280 
1281  const unsigned char *Buf = (const unsigned char *)Buffer.getBufferStart();
1282  const unsigned char *End = (const unsigned char *)Buffer.getBufferEnd();
1283  const std::size_t BufLen = End - Buf;
1284 
1285  unsigned I = 0;
1286  uint64_t Word;
1287 
1288  // scan sizeof(Word) bytes at a time for new lines.
1289  // This is much faster than scanning each byte independently.
1290  if (BufLen > sizeof(Word)) {
1291  do {
1292  Word = llvm::support::endian::read64(Buf + I, llvm::support::little);
1293  // no new line => jump over sizeof(Word) bytes.
1294  auto Mask = likelyhasbetween(Word, '\n', '\r');
1295  if (!Mask) {
1296  I += sizeof(Word);
1297  continue;
1298  }
1299 
1300  // At that point, Mask contains 0x80 set at each byte that holds a value
1301  // in [\n, \r + 1 [
1302 
1303  // Scan for the next newline - it's very likely there's one.
1304  unsigned N =
1305  llvm::countTrailingZeros(Mask) - 7; // -7 because 0x80 is the marker
1306  Word >>= N;
1307  I += N / 8 + 1;
1308  unsigned char Byte = Word;
1309  if (Byte == '\n') {
1310  LineOffsets.push_back(I);
1311  } else if (Byte == '\r') {
1312  // If this is \r\n, skip both characters.
1313  if (Buf[I] == '\n')
1314  ++I;
1315  LineOffsets.push_back(I);
1316  }
1317  } while (I < BufLen - sizeof(Word) - 1);
1318  }
1319 
1320  // Handle tail using a regular check.
1321  while (I < BufLen) {
1322  if (Buf[I] == '\n') {
1323  LineOffsets.push_back(I + 1);
1324  } else if (Buf[I] == '\r') {
1325  // If this is \r\n, skip both characters.
1326  if (I + 1 < BufLen && Buf[I + 1] == '\n')
1327  ++I;
1328  LineOffsets.push_back(I + 1);
1329  }
1330  ++I;
1331  }
1332 
1333  return LineOffsetMapping(LineOffsets, Alloc);
1334 }
1335 
1336 LineOffsetMapping::LineOffsetMapping(ArrayRef<unsigned> LineOffsets,
1337  llvm::BumpPtrAllocator &Alloc)
1338  : Storage(Alloc.Allocate<unsigned>(LineOffsets.size() + 1)) {
1339  Storage[0] = LineOffsets.size();
1340  std::copy(LineOffsets.begin(), LineOffsets.end(), Storage + 1);
1341 }
1342 
1343 /// getLineNumber - Given a SourceLocation, return the spelling line number
1344 /// for the position indicated. This requires building and caching a table of
1345 /// line offsets for the MemoryBuffer, so this is not cheap: use only when
1346 /// about to emit a diagnostic.
1347 unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1348  bool *Invalid) const {
1349  if (FID.isInvalid()) {
1350  if (Invalid)
1351  *Invalid = true;
1352  return 1;
1353  }
1354 
1355  const ContentCache *Content;
1356  if (LastLineNoFileIDQuery == FID)
1357  Content = LastLineNoContentCache;
1358  else {
1359  bool MyInvalid = false;
1360  const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1361  if (MyInvalid || !Entry.isFile()) {
1362  if (Invalid)
1363  *Invalid = true;
1364  return 1;
1365  }
1366 
1367  Content = &Entry.getFile().getContentCache();
1368  }
1369 
1370  // If this is the first use of line information for this buffer, compute the
1371  /// SourceLineCache for it on demand.
1372  if (!Content->SourceLineCache) {
1374  Content->getBufferOrNone(Diag, getFileManager(), SourceLocation());
1375  if (Invalid)
1376  *Invalid = !Buffer;
1377  if (!Buffer)
1378  return 1;
1379 
1380  Content->SourceLineCache =
1381  LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1382  } else if (Invalid)
1383  *Invalid = false;
1384 
1385  // Okay, we know we have a line number table. Do a binary search to find the
1386  // line number that this character position lands on.
1387  const unsigned *SourceLineCache = Content->SourceLineCache.begin();
1388  const unsigned *SourceLineCacheStart = SourceLineCache;
1389  const unsigned *SourceLineCacheEnd = Content->SourceLineCache.end();
1390 
1391  unsigned QueriedFilePos = FilePos+1;
1392 
1393  // FIXME: I would like to be convinced that this code is worth being as
1394  // complicated as it is, binary search isn't that slow.
1395  //
1396  // If it is worth being optimized, then in my opinion it could be more
1397  // performant, simpler, and more obviously correct by just "galloping" outward
1398  // from the queried file position. In fact, this could be incorporated into a
1399  // generic algorithm such as lower_bound_with_hint.
1400  //
1401  // If someone gives me a test case where this matters, and I will do it! - DWD
1402 
1403  // If the previous query was to the same file, we know both the file pos from
1404  // that query and the line number returned. This allows us to narrow the
1405  // search space from the entire file to something near the match.
1406  if (LastLineNoFileIDQuery == FID) {
1407  if (QueriedFilePos >= LastLineNoFilePos) {
1408  // FIXME: Potential overflow?
1409  SourceLineCache = SourceLineCache+LastLineNoResult-1;
1410 
1411  // The query is likely to be nearby the previous one. Here we check to
1412  // see if it is within 5, 10 or 20 lines. It can be far away in cases
1413  // where big comment blocks and vertical whitespace eat up lines but
1414  // contribute no tokens.
1415  if (SourceLineCache+5 < SourceLineCacheEnd) {
1416  if (SourceLineCache[5] > QueriedFilePos)
1417  SourceLineCacheEnd = SourceLineCache+5;
1418  else if (SourceLineCache+10 < SourceLineCacheEnd) {
1419  if (SourceLineCache[10] > QueriedFilePos)
1420  SourceLineCacheEnd = SourceLineCache+10;
1421  else if (SourceLineCache+20 < SourceLineCacheEnd) {
1422  if (SourceLineCache[20] > QueriedFilePos)
1423  SourceLineCacheEnd = SourceLineCache+20;
1424  }
1425  }
1426  }
1427  } else {
1428  if (LastLineNoResult < Content->SourceLineCache.size())
1429  SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
1430  }
1431  }
1432 
1433  const unsigned *Pos =
1434  std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
1435  unsigned LineNo = Pos-SourceLineCacheStart;
1436 
1437  LastLineNoFileIDQuery = FID;
1438  LastLineNoContentCache = Content;
1439  LastLineNoFilePos = QueriedFilePos;
1440  LastLineNoResult = LineNo;
1441  return LineNo;
1442 }
1443 
1445  bool *Invalid) const {
1446  if (isInvalid(Loc, Invalid)) return 0;
1447  std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1448  return getLineNumber(LocInfo.first, LocInfo.second);
1449 }
1451  bool *Invalid) const {
1452  if (isInvalid(Loc, Invalid)) return 0;
1453  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1454  return getLineNumber(LocInfo.first, LocInfo.second);
1455 }
1457  bool *Invalid) const {
1458  PresumedLoc PLoc = getPresumedLoc(Loc);
1459  if (isInvalid(PLoc, Invalid)) return 0;
1460  return PLoc.getLine();
1461 }
1462 
1463 /// getFileCharacteristic - return the file characteristic of the specified
1464 /// source location, indicating whether this is a normal file, a system
1465 /// header, or an "implicit extern C" system header.
1466 ///
1467 /// This state can be modified with flags on GNU linemarker directives like:
1468 /// # 4 "foo.h" 3
1469 /// which changes all source locations in the current file after that to be
1470 /// considered to be from a system header.
1473  assert(Loc.isValid() && "Can't get file characteristic of invalid loc!");
1474  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1475  const SLocEntry *SEntry = getSLocEntryForFile(LocInfo.first);
1476  if (!SEntry)
1477  return C_User;
1478 
1479  const SrcMgr::FileInfo &FI = SEntry->getFile();
1480 
1481  // If there are no #line directives in this file, just return the whole-file
1482  // state.
1483  if (!FI.hasLineDirectives())
1484  return FI.getFileCharacteristic();
1485 
1486  assert(LineTable && "Can't have linetable entries without a LineTable!");
1487  // See if there is a #line directive before the location.
1488  const LineEntry *Entry =
1489  LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
1490 
1491  // If this is before the first line marker, use the file characteristic.
1492  if (!Entry)
1493  return FI.getFileCharacteristic();
1494 
1495  return Entry->FileKind;
1496 }
1497 
1498 /// Return the filename or buffer identifier of the buffer the location is in.
1499 /// Note that this name does not respect \#line directives. Use getPresumedLoc
1500 /// for normal clients.
1502  bool *Invalid) const {
1503  if (isInvalid(Loc, Invalid)) return "<invalid loc>";
1504 
1505  auto B = getBufferOrNone(getFileID(Loc));
1506  if (Invalid)
1507  *Invalid = !B;
1508  return B ? B->getBufferIdentifier() : "<invalid buffer>";
1509 }
1510 
1511 /// getPresumedLoc - This method returns the "presumed" location of a
1512 /// SourceLocation specifies. A "presumed location" can be modified by \#line
1513 /// or GNU line marker directives. This provides a view on the data that a
1514 /// user should see in diagnostics, for example.
1515 ///
1516 /// Note that a presumed location is always given as the expansion point of an
1517 /// expansion location, not at the spelling location.
1519  bool UseLineDirectives) const {
1520  if (Loc.isInvalid()) return PresumedLoc();
1521 
1522  // Presumed locations are always for expansion points.
1523  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1524 
1525  bool Invalid = false;
1526  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1527  if (Invalid || !Entry.isFile())
1528  return PresumedLoc();
1529 
1530  const SrcMgr::FileInfo &FI = Entry.getFile();
1531  const SrcMgr::ContentCache *C = &FI.getContentCache();
1532 
1533  // To get the source name, first consult the FileEntry (if one exists)
1534  // before the MemBuffer as this will avoid unnecessarily paging in the
1535  // MemBuffer.
1536  FileID FID = LocInfo.first;
1537  StringRef Filename;
1538  if (C->OrigEntry)
1539  Filename = C->OrigEntry->getName();
1540  else if (auto Buffer = C->getBufferOrNone(Diag, getFileManager()))
1541  Filename = Buffer->getBufferIdentifier();
1542 
1543  unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1544  if (Invalid)
1545  return PresumedLoc();
1546  unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1547  if (Invalid)
1548  return PresumedLoc();
1549 
1550  SourceLocation IncludeLoc = FI.getIncludeLoc();
1551 
1552  // If we have #line directives in this file, update and overwrite the physical
1553  // location info if appropriate.
1554  if (UseLineDirectives && FI.hasLineDirectives()) {
1555  assert(LineTable && "Can't have linetable entries without a LineTable!");
1556  // See if there is a #line directive before this. If so, get it.
1557  if (const LineEntry *Entry =
1558  LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
1559  // If the LineEntry indicates a filename, use it.
1560  if (Entry->FilenameID != -1) {
1561  Filename = LineTable->getFilename(Entry->FilenameID);
1562  // The contents of files referenced by #line are not in the
1563  // SourceManager
1564  FID = FileID::get(0);
1565  }
1566 
1567  // Use the line number specified by the LineEntry. This line number may
1568  // be multiple lines down from the line entry. Add the difference in
1569  // physical line numbers from the query point and the line marker to the
1570  // total.
1571  unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1572  LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
1573 
1574  // Note that column numbers are not molested by line markers.
1575 
1576  // Handle virtual #include manipulation.
1577  if (Entry->IncludeOffset) {
1578  IncludeLoc = getLocForStartOfFile(LocInfo.first);
1579  IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
1580  }
1581  }
1582  }
1583 
1584  return PresumedLoc(Filename.data(), FID, LineNo, ColNo, IncludeLoc);
1585 }
1586 
1587 /// Returns whether the PresumedLoc for a given SourceLocation is
1588 /// in the main file.
1589 ///
1590 /// This computes the "presumed" location for a SourceLocation, then checks
1591 /// whether it came from a file other than the main file. This is different
1592 /// from isWrittenInMainFile() because it takes line marker directives into
1593 /// account.
1595  if (Loc.isInvalid()) return false;
1596 
1597  // Presumed locations are always for expansion points.
1598  std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1599 
1600  const SLocEntry *Entry = getSLocEntryForFile(LocInfo.first);
1601  if (!Entry)
1602  return false;
1603 
1604  const SrcMgr::FileInfo &FI = Entry->getFile();
1605 
1606  // Check if there is a line directive for this location.
1607  if (FI.hasLineDirectives())
1608  if (const LineEntry *Entry =
1609  LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1610  if (Entry->IncludeOffset)
1611  return false;
1612 
1613  return FI.getIncludeLoc().isInvalid();
1614 }
1615 
1616 /// The size of the SLocEntry that \p FID represents.
1618  bool Invalid = false;
1619  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1620  if (Invalid)
1621  return 0;
1622 
1623  int ID = FID.ID;
1624  SourceLocation::UIntTy NextOffset;
1625  if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1626  NextOffset = getNextLocalOffset();
1627  else if (ID+1 == -1)
1628  NextOffset = MaxLoadedOffset;
1629  else
1630  NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1631 
1632  return NextOffset - Entry.getOffset() - 1;
1633 }
1634 
1635 //===----------------------------------------------------------------------===//
1636 // Other miscellaneous methods.
1637 //===----------------------------------------------------------------------===//
1638 
1639 /// Get the source location for the given file:line:col triplet.
1640 ///
1641 /// If the source file is included multiple times, the source location will
1642 /// be based upon an arbitrary inclusion.
1644  unsigned Line,
1645  unsigned Col) const {
1646  assert(SourceFile && "Null source file!");
1647  assert(Line && Col && "Line and column should start from 1!");
1648 
1649  FileID FirstFID = translateFile(SourceFile);
1650  return translateLineCol(FirstFID, Line, Col);
1651 }
1652 
1653 /// Get the FileID for the given file.
1654 ///
1655 /// If the source file is included multiple times, the FileID will be the
1656 /// first inclusion.
1658  assert(SourceFile && "Null source file!");
1659 
1660  // First, check the main file ID, since it is common to look for a
1661  // location in the main file.
1662  if (MainFileID.isValid()) {
1663  bool Invalid = false;
1664  const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1665  if (Invalid)
1666  return FileID();
1667 
1668  if (MainSLoc.isFile()) {
1669  if (MainSLoc.getFile().getContentCache().OrigEntry == SourceFile)
1670  return MainFileID;
1671  }
1672  }
1673 
1674  // The location we're looking for isn't in the main file; look
1675  // through all of the local source locations.
1676  for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1677  const SLocEntry &SLoc = getLocalSLocEntry(I);
1678  if (SLoc.isFile() &&
1679  SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1680  return FileID::get(I);
1681  }
1682 
1683  // If that still didn't help, try the modules.
1684  for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1685  const SLocEntry &SLoc = getLoadedSLocEntry(I);
1686  if (SLoc.isFile() &&
1687  SLoc.getFile().getContentCache().OrigEntry == SourceFile)
1688  return FileID::get(-int(I) - 2);
1689  }
1690 
1691  return FileID();
1692 }
1693 
1694 /// Get the source location in \arg FID for the given line:col.
1695 /// Returns null location if \arg FID is not a file SLocEntry.
1697  unsigned Line,
1698  unsigned Col) const {
1699  // Lines are used as a one-based index into a zero-based array. This assert
1700  // checks for possible buffer underruns.
1701  assert(Line && Col && "Line and column should start from 1!");
1702 
1703  if (FID.isInvalid())
1704  return SourceLocation();
1705 
1706  bool Invalid = false;
1707  const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1708  if (Invalid)
1709  return SourceLocation();
1710 
1711  if (!Entry.isFile())
1712  return SourceLocation();
1713 
1714  SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1715 
1716  if (Line == 1 && Col == 1)
1717  return FileLoc;
1718 
1719  const ContentCache *Content = &Entry.getFile().getContentCache();
1720 
1721  // If this is the first use of line information for this buffer, compute the
1722  // SourceLineCache for it on demand.
1724  Content->getBufferOrNone(Diag, getFileManager());
1725  if (!Buffer)
1726  return SourceLocation();
1727  if (!Content->SourceLineCache)
1728  Content->SourceLineCache =
1729  LineOffsetMapping::get(*Buffer, ContentCacheAlloc);
1730 
1731  if (Line > Content->SourceLineCache.size()) {
1732  unsigned Size = Buffer->getBufferSize();
1733  if (Size > 0)
1734  --Size;
1735  return FileLoc.getLocWithOffset(Size);
1736  }
1737 
1738  unsigned FilePos = Content->SourceLineCache[Line - 1];
1739  const char *Buf = Buffer->getBufferStart() + FilePos;
1740  unsigned BufLength = Buffer->getBufferSize() - FilePos;
1741  if (BufLength == 0)
1742  return FileLoc.getLocWithOffset(FilePos);
1743 
1744  unsigned i = 0;
1745 
1746  // Check that the given column is valid.
1747  while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1748  ++i;
1749  return FileLoc.getLocWithOffset(FilePos + i);
1750 }
1751 
1752 /// Compute a map of macro argument chunks to their expanded source
1753 /// location. Chunks that are not part of a macro argument will map to an
1754 /// invalid source location. e.g. if a file contains one macro argument at
1755 /// offset 100 with length 10, this is how the map will be formed:
1756 /// 0 -> SourceLocation()
1757 /// 100 -> Expanded macro arg location
1758 /// 110 -> SourceLocation()
1759 void SourceManager::computeMacroArgsCache(MacroArgsMap &MacroArgsCache,
1760  FileID FID) const {
1761  assert(FID.isValid());
1762 
1763  // Initially no macro argument chunk is present.
1764  MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1765 
1766  int ID = FID.ID;
1767  while (true) {
1768  ++ID;
1769  // Stop if there are no more FileIDs to check.
1770  if (ID > 0) {
1771  if (unsigned(ID) >= local_sloc_entry_size())
1772  return;
1773  } else if (ID == -1) {
1774  return;
1775  }
1776 
1777  bool Invalid = false;
1778  const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1779  if (Invalid)
1780  return;
1781  if (Entry.isFile()) {
1782  auto& File = Entry.getFile();
1783  if (File.getFileCharacteristic() == C_User_ModuleMap ||
1784  File.getFileCharacteristic() == C_System_ModuleMap)
1785  continue;
1786 
1787  SourceLocation IncludeLoc = File.getIncludeLoc();
1788  bool IncludedInFID =
1789  (IncludeLoc.isValid() && isInFileID(IncludeLoc, FID)) ||
1790  // Predefined header doesn't have a valid include location in main
1791  // file, but any files created by it should still be skipped when
1792  // computing macro args expanded in the main file.
1793  (FID == MainFileID && Entry.getFile().getName() == "<built-in>");
1794  if (IncludedInFID) {
1795  // Skip the files/macros of the #include'd file, we only care about
1796  // macros that lexed macro arguments from our file.
1797  if (Entry.getFile().NumCreatedFIDs)
1798  ID += Entry.getFile().NumCreatedFIDs - 1 /*because of next ++ID*/;
1799  continue;
1800  } else if (IncludeLoc.isValid()) {
1801  // If file was included but not from FID, there is no more files/macros
1802  // that may be "contained" in this file.
1803  return;
1804  }
1805  continue;
1806  }
1807 
1808  const ExpansionInfo &ExpInfo = Entry.getExpansion();
1809 
1810  if (ExpInfo.getExpansionLocStart().isFileID()) {
1811  if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1812  return; // No more files/macros that may be "contained" in this file.
1813  }
1814 
1815  if (!ExpInfo.isMacroArgExpansion())
1816  continue;
1817 
1818  associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1819  ExpInfo.getSpellingLoc(),
1820  SourceLocation::getMacroLoc(Entry.getOffset()),
1821  getFileIDSize(FileID::get(ID)));
1822  }
1823 }
1824 
1825 void SourceManager::associateFileChunkWithMacroArgExp(
1826  MacroArgsMap &MacroArgsCache,
1827  FileID FID,
1828  SourceLocation SpellLoc,
1829  SourceLocation ExpansionLoc,
1830  unsigned ExpansionLength) const {
1831  if (!SpellLoc.isFileID()) {
1832  SourceLocation::UIntTy SpellBeginOffs = SpellLoc.getOffset();
1833  SourceLocation::UIntTy SpellEndOffs = SpellBeginOffs + ExpansionLength;
1834 
1835  // The spelling range for this macro argument expansion can span multiple
1836  // consecutive FileID entries. Go through each entry contained in the
1837  // spelling range and if one is itself a macro argument expansion, recurse
1838  // and associate the file chunk that it represents.
1839 
1840  FileID SpellFID; // Current FileID in the spelling range.
1841  unsigned SpellRelativeOffs;
1842  std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
1843  while (true) {
1844  const SLocEntry &Entry = getSLocEntry(SpellFID);
1845  SourceLocation::UIntTy SpellFIDBeginOffs = Entry.getOffset();
1846  unsigned SpellFIDSize = getFileIDSize(SpellFID);
1847  SourceLocation::UIntTy SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1848  const ExpansionInfo &Info = Entry.getExpansion();
1849  if (Info.isMacroArgExpansion()) {
1850  unsigned CurrSpellLength;
1851  if (SpellFIDEndOffs < SpellEndOffs)
1852  CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1853  else
1854  CurrSpellLength = ExpansionLength;
1855  associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1856  Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1857  ExpansionLoc, CurrSpellLength);
1858  }
1859 
1860  if (SpellFIDEndOffs >= SpellEndOffs)
1861  return; // we covered all FileID entries in the spelling range.
1862 
1863  // Move to the next FileID entry in the spelling range.
1864  unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1865  ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1866  ExpansionLength -= advance;
1867  ++SpellFID.ID;
1868  SpellRelativeOffs = 0;
1869  }
1870  }
1871 
1872  assert(SpellLoc.isFileID());
1873 
1874  unsigned BeginOffs;
1875  if (!isInFileID(SpellLoc, FID, &BeginOffs))
1876  return;
1877 
1878  unsigned EndOffs = BeginOffs + ExpansionLength;
1879 
1880  // Add a new chunk for this macro argument. A previous macro argument chunk
1881  // may have been lexed again, so e.g. if the map is
1882  // 0 -> SourceLocation()
1883  // 100 -> Expanded loc #1
1884  // 110 -> SourceLocation()
1885  // and we found a new macro FileID that lexed from offset 105 with length 3,
1886  // the new map will be:
1887  // 0 -> SourceLocation()
1888  // 100 -> Expanded loc #1
1889  // 105 -> Expanded loc #2
1890  // 108 -> Expanded loc #1
1891  // 110 -> SourceLocation()
1892  //
1893  // Since re-lexed macro chunks will always be the same size or less of
1894  // previous chunks, we only need to find where the ending of the new macro
1895  // chunk is mapped to and update the map with new begin/end mappings.
1896 
1897  MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1898  --I;
1899  SourceLocation EndOffsMappedLoc = I->second;
1900  MacroArgsCache[BeginOffs] = ExpansionLoc;
1901  MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1902 }
1903 
1904 /// If \arg Loc points inside a function macro argument, the returned
1905 /// location will be the macro location in which the argument was expanded.
1906 /// If a macro argument is used multiple times, the expanded location will
1907 /// be at the first expansion of the argument.
1908 /// e.g.
1909 /// MY_MACRO(foo);
1910 /// ^
1911 /// Passing a file location pointing at 'foo', will yield a macro location
1912 /// where 'foo' was expanded into.
1915  if (Loc.isInvalid() || !Loc.isFileID())
1916  return Loc;
1917 
1918  FileID FID;
1919  unsigned Offset;
1920  std::tie(FID, Offset) = getDecomposedLoc(Loc);
1921  if (FID.isInvalid())
1922  return Loc;
1923 
1924  std::unique_ptr<MacroArgsMap> &MacroArgsCache = MacroArgsCacheMap[FID];
1925  if (!MacroArgsCache) {
1926  MacroArgsCache = std::make_unique<MacroArgsMap>();
1927  computeMacroArgsCache(*MacroArgsCache, FID);
1928  }
1929 
1930  assert(!MacroArgsCache->empty());
1931  MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
1932  // In case every element in MacroArgsCache is greater than Offset we can't
1933  // decrement the iterator.
1934  if (I == MacroArgsCache->begin())
1935  return Loc;
1936 
1937  --I;
1938 
1939  SourceLocation::UIntTy MacroArgBeginOffs = I->first;
1940  SourceLocation MacroArgExpandedLoc = I->second;
1941  if (MacroArgExpandedLoc.isValid())
1942  return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
1943 
1944  return Loc;
1945 }
1946 
1947 std::pair<FileID, unsigned>
1949  if (FID.isInvalid())
1950  return std::make_pair(FileID(), 0);
1951 
1952  // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1953 
1954  using DecompTy = std::pair<FileID, unsigned>;
1955  auto InsertOp = IncludedLocMap.try_emplace(FID);
1956  DecompTy &DecompLoc = InsertOp.first->second;
1957  if (!InsertOp.second)
1958  return DecompLoc; // already in map.
1959 
1960  SourceLocation UpperLoc;
1961  bool Invalid = false;
1962  const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1963  if (!Invalid) {
1964  if (Entry.isExpansion())
1965  UpperLoc = Entry.getExpansion().getExpansionLocStart();
1966  else
1967  UpperLoc = Entry.getFile().getIncludeLoc();
1968  }
1969 
1970  if (UpperLoc.isValid())
1971  DecompLoc = getDecomposedLoc(UpperLoc);
1972 
1973  return DecompLoc;
1974 }
1975 
1976 /// Given a decomposed source location, move it up the include/expansion stack
1977 /// to the parent source location. If this is possible, return the decomposed
1978 /// version of the parent in Loc and return false. If Loc is the top-level
1979 /// entry, return true and don't modify it.
1980 static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1981  const SourceManager &SM) {
1982  std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1983  if (UpperLoc.first.isInvalid())
1984  return true; // We reached the top.
1985 
1986  Loc = UpperLoc;
1987  return false;
1988 }
1989 
1990 /// Return the cache entry for comparing the given file IDs
1991 /// for isBeforeInTranslationUnit.
1992 InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1993  FileID RFID) const {
1994  // This is a magic number for limiting the cache size. It was experimentally
1995  // derived from a small Objective-C project (where the cache filled
1996  // out to ~250 items). We can make it larger if necessary.
1997  enum { MagicCacheSize = 300 };
1998  IsBeforeInTUCacheKey Key(LFID, RFID);
1999 
2000  // If the cache size isn't too large, do a lookup and if necessary default
2001  // construct an entry. We can then return it to the caller for direct
2002  // use. When they update the value, the cache will get automatically
2003  // updated as well.
2004  if (IBTUCache.size() < MagicCacheSize)
2005  return IBTUCache[Key];
2006 
2007  // Otherwise, do a lookup that will not construct a new value.
2008  InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2009  if (I != IBTUCache.end())
2010  return I->second;
2011 
2012  // Fall back to the overflow value.
2013  return IBTUCacheOverflow;
2014 }
2015 
2016 /// Determines the order of 2 source locations in the translation unit.
2017 ///
2018 /// \returns true if LHS source location comes before RHS, false otherwise.
2020  SourceLocation RHS) const {
2021  assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2022  if (LHS == RHS)
2023  return false;
2024 
2025  std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2026  std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
2027 
2028  // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2029  // is a serialized one referring to a file that was removed after we loaded
2030  // the PCH.
2031  if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
2032  return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
2033 
2034  std::pair<bool, bool> InSameTU = isInTheSameTranslationUnit(LOffs, ROffs);
2035  if (InSameTU.first)
2036  return InSameTU.second;
2037 
2038  // If we arrived here, the location is either in a built-ins buffer or
2039  // associated with global inline asm. PR5662 and PR22576 are examples.
2040 
2041  StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
2042  StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
2043  bool LIsBuiltins = LB == "<built-in>";
2044  bool RIsBuiltins = RB == "<built-in>";
2045  // Sort built-in before non-built-in.
2046  if (LIsBuiltins || RIsBuiltins) {
2047  if (LIsBuiltins != RIsBuiltins)
2048  return LIsBuiltins;
2049  // Both are in built-in buffers, but from different files. We just claim that
2050  // lower IDs come first.
2051  return LOffs.first < ROffs.first;
2052  }
2053  bool LIsAsm = LB == "<inline asm>";
2054  bool RIsAsm = RB == "<inline asm>";
2055  // Sort assembler after built-ins, but before the rest.
2056  if (LIsAsm || RIsAsm) {
2057  if (LIsAsm != RIsAsm)
2058  return RIsAsm;
2059  assert(LOffs.first == ROffs.first);
2060  return false;
2061  }
2062  bool LIsScratch = LB == "<scratch space>";
2063  bool RIsScratch = RB == "<scratch space>";
2064  // Sort scratch after inline asm, but before the rest.
2065  if (LIsScratch || RIsScratch) {
2066  if (LIsScratch != RIsScratch)
2067  return LIsScratch;
2068  return LOffs.second < ROffs.second;
2069  }
2070  llvm_unreachable("Unsortable locations found");
2071 }
2072 
2074  std::pair<FileID, unsigned> &LOffs,
2075  std::pair<FileID, unsigned> &ROffs) const {
2076  // If the source locations are in the same file, just compare offsets.
2077  if (LOffs.first == ROffs.first)
2078  return std::make_pair(true, LOffs.second < ROffs.second);
2079 
2080  // If we are comparing a source location with multiple locations in the same
2081  // file, we get a big win by caching the result.
2082  InBeforeInTUCacheEntry &IsBeforeInTUCache =
2083  getInBeforeInTUCache(LOffs.first, ROffs.first);
2084 
2085  // If we are comparing a source location with multiple locations in the same
2086  // file, we get a big win by caching the result.
2087  if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2088  return std::make_pair(
2089  true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2090 
2091  // Okay, we missed in the cache, start updating the cache for this query.
2092  IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2093  /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
2094 
2095  // We need to find the common ancestor. The only way of doing this is to
2096  // build the complete include chain for one and then walking up the chain
2097  // of the other looking for a match.
2098  // We use a map from FileID to Offset to store the chain. Easier than writing
2099  // a custom set hash info that only depends on the first part of a pair.
2100  using LocSet = llvm::SmallDenseMap<FileID, unsigned, 16>;
2101  LocSet LChain;
2102  do {
2103  LChain.insert(LOffs);
2104  // We catch the case where LOffs is in a file included by ROffs and
2105  // quit early. The other way round unfortunately remains suboptimal.
2106  } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2107  LocSet::iterator I;
2108  while((I = LChain.find(ROffs.first)) == LChain.end()) {
2109  if (MoveUpIncludeHierarchy(ROffs, *this))
2110  break; // Met at topmost file.
2111  }
2112  if (I != LChain.end())
2113  LOffs = *I;
2114 
2115  // If we exited because we found a nearest common ancestor, compare the
2116  // locations within the common file and cache them.
2117  if (LOffs.first == ROffs.first) {
2118  IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2119  return std::make_pair(
2120  true, IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second));
2121  }
2122  // Clear the lookup cache, it depends on a common location.
2123  IsBeforeInTUCache.clear();
2124  return std::make_pair(false, false);
2125 }
2126 
2128  llvm::errs() << "\n*** Source Manager Stats:\n";
2129  llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2130  << " mem buffers mapped.\n";
2131  llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
2132  << llvm::capacity_in_bytes(LocalSLocEntryTable)
2133  << " bytes of capacity), "
2134  << NextLocalOffset << "B of Sloc address space used.\n";
2135  llvm::errs() << LoadedSLocEntryTable.size()
2136  << " loaded SLocEntries allocated, "
2137  << MaxLoadedOffset - CurrentLoadedOffset
2138  << "B of Sloc address space used.\n";
2139 
2140  unsigned NumLineNumsComputed = 0;
2141  unsigned NumFileBytesMapped = 0;
2142  for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
2143  NumLineNumsComputed += bool(I->second->SourceLineCache);
2144  NumFileBytesMapped += I->second->getSizeBytesMapped();
2145  }
2146  unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
2147 
2148  llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
2149  << NumLineNumsComputed << " files with line #'s computed, "
2150  << NumMacroArgsComputed << " files with macro args computed.\n";
2151  llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2152  << NumBinaryProbes << " binary.\n";
2153 }
2154 
2155 LLVM_DUMP_METHOD void SourceManager::dump() const {
2156  llvm::raw_ostream &out = llvm::errs();
2157 
2158  auto DumpSLocEntry = [&](int ID, const SrcMgr::SLocEntry &Entry,
2160  out << "SLocEntry <FileID " << ID << "> " << (Entry.isFile() ? "file" : "expansion")
2161  << " <SourceLocation " << Entry.getOffset() << ":";
2162  if (NextStart)
2163  out << *NextStart << ">\n";
2164  else
2165  out << "???\?>\n";
2166  if (Entry.isFile()) {
2167  auto &FI = Entry.getFile();
2168  if (FI.NumCreatedFIDs)
2169  out << " covers <FileID " << ID << ":" << int(ID + FI.NumCreatedFIDs)
2170  << ">\n";
2171  if (FI.getIncludeLoc().isValid())
2172  out << " included from " << FI.getIncludeLoc().getOffset() << "\n";
2173  auto &CC = FI.getContentCache();
2174  out << " for " << (CC.OrigEntry ? CC.OrigEntry->getName() : "<none>")
2175  << "\n";
2176  if (CC.BufferOverridden)
2177  out << " contents overridden\n";
2178  if (CC.ContentsEntry != CC.OrigEntry) {
2179  out << " contents from "
2180  << (CC.ContentsEntry ? CC.ContentsEntry->getName() : "<none>")
2181  << "\n";
2182  }
2183  } else {
2184  auto &EI = Entry.getExpansion();
2185  out << " spelling from " << EI.getSpellingLoc().getOffset() << "\n";
2186  out << " macro " << (EI.isMacroArgExpansion() ? "arg" : "body")
2187  << " range <" << EI.getExpansionLocStart().getOffset() << ":"
2188  << EI.getExpansionLocEnd().getOffset() << ">\n";
2189  }
2190  };
2191 
2192  // Dump local SLocEntries.
2193  for (unsigned ID = 0, NumIDs = LocalSLocEntryTable.size(); ID != NumIDs; ++ID) {
2194  DumpSLocEntry(ID, LocalSLocEntryTable[ID],
2195  ID == NumIDs - 1 ? NextLocalOffset
2196  : LocalSLocEntryTable[ID + 1].getOffset());
2197  }
2198  // Dump loaded SLocEntries.
2200  for (unsigned Index = 0; Index != LoadedSLocEntryTable.size(); ++Index) {
2201  int ID = -(int)Index - 2;
2202  if (SLocEntryLoaded[Index]) {
2203  DumpSLocEntry(ID, LoadedSLocEntryTable[Index], NextStart);
2204  NextStart = LoadedSLocEntryTable[Index].getOffset();
2205  } else {
2206  NextStart = None;
2207  }
2208  }
2209 }
2210 
2212 
2213 /// Return the amount of memory used by memory buffers, breaking down
2214 /// by heap-backed versus mmap'ed memory.
2216  size_t malloc_bytes = 0;
2217  size_t mmap_bytes = 0;
2218 
2219  for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2220  if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2221  switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2222  case llvm::MemoryBuffer::MemoryBuffer_MMap:
2223  mmap_bytes += sized_mapped;
2224  break;
2225  case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2226  malloc_bytes += sized_mapped;
2227  break;
2228  }
2229 
2230  return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2231 }
2232 
2234  size_t size = llvm::capacity_in_bytes(MemBufferInfos)
2235  + llvm::capacity_in_bytes(LocalSLocEntryTable)
2236  + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2237  + llvm::capacity_in_bytes(SLocEntryLoaded)
2238  + llvm::capacity_in_bytes(FileInfos);
2239 
2240  if (OverriddenFilesInfo)
2241  size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2242 
2243  return size;
2244 }
2245 
2247  StringRef Content) {
2248  // This is referenced by `FileMgr` and will be released by `FileMgr` when it
2249  // is deleted.
2251  new llvm::vfs::InMemoryFileSystem);
2252  InMemoryFileSystem->addFile(
2253  FileName, 0,
2254  llvm::MemoryBuffer::getMemBuffer(Content, FileName,
2255  /*RequiresNullTerminator=*/false));
2256  // This is passed to `SM` as reference, so the pointer has to be referenced
2257  // in `Environment` so that `FileMgr` can out-live this function scope.
2258  FileMgr =
2259  std::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
2260  // This is passed to `SM` as reference, so the pointer has to be referenced
2261  // by `Environment` due to the same reason above.
2262  Diagnostics = std::make_unique<DiagnosticsEngine>(
2264  new DiagnosticOptions);
2265  SourceMgr = std::make_unique<SourceManager>(*Diagnostics, *FileMgr);
2266  FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
2268  assert(ID.isValid());
2269  SourceMgr->setMainFileID(ID);
2270 }
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:2073
clang::SourceManager::isMacroBodyExpansion
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
Definition: SourceManager.cpp:1072
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:80
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:1018
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:1472
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:285
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:212
clang::PresumedLoc::getLine
unsigned getLine() const
Return the presumed line number of this location.
Definition: SourceLocation.h:339
advance
static ParseState advance(ParseState S, size_t N)
Definition: Parsing.cpp:145
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:1010
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:1594
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:88
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:136
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:1271
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:1914
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:2333
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:1027
clang::SourceManager::getExpansionColumnNumber
unsigned getExpansionColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1244
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:1041
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:2127
clang::TypePropertyCache
The type-property cache.
Definition: Type.cpp:3776
clang::SourceManager::getPresumedLoc
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
Definition: SourceManager.cpp:1518
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:1080
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:291
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:1059
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:1237
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:2335
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:1696
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:1980
clang::SourceManager::getTopMacroCallerLoc
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
Definition: SourceManager.cpp:1033
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:46
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:1501
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:1183
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:1230
clang::SourceLocation::isFileID
bool isFileID() const
Definition: SourceLocation.h:104
clang::PresumedLoc::getColumn
unsigned getColumn() const
Return the presumed column number of this location.
Definition: SourceLocation.h:347
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:205
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:1251
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:2019
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:2215
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:302
Cache
TypePropertyCache< Private > Cache
Definition: Type.cpp:3822
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:192
clang::CharSourceRange::isTokenRange
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
Definition: SourceLocation.h:282
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:104
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:75
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:1115
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:1157
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:2246
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:255
clang::SourceManager::dump
void dump() const
Definition: SourceManager.cpp:2155
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:164
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:286
clang::SrcMgr::LineOffsetMapping::begin
const unsigned * begin() const
Definition: SourceManager.h:109
clang::CharSourceRange::setBegin
void setBegin(SourceLocation b)
Definition: SourceLocation.h:289
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:105
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:113
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:1948
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:40
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:112
clang::FileID::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:47
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:1263
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:304
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:1643
clang::SourceManager::getSpellingLineNumber
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
Definition: SourceManager.cpp:1444
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:1450
SM
#define SM(sm)
Definition: Cuda.cpp:78
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:1617
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:1657
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:2233
clang::CharSourceRange::setEnd
void setEnd(SourceLocation e)
Definition: SourceLocation.h:290
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:95
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:1508
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:1456
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:1347
clang::SrcMgr::SLocEntry
This is a discriminated union of FileInfo and ExpansionInfo.
Definition: SourceManager.h:467