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