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